<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model:search="search"
      v-model="form"
      :data="data"
      :option="option"
      v-model:page="page"
      @row-save="createRowSave"
      @row-update="updateRow"
      @row-del="deleteRow"
      :table-loading="loading"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
    >
      <!--      <template #menu-right="{}">
        <el-button
            class="ml-3"
            @click="handleExport"
        >
          <template #icon> <i-ep-download /> </template>导出
        </el-button>
      </template>-->
      <template #menu="{ size, row, index }">
        <!--        <el-button
            icon="el-icon-edit"
            text
            @click="openDialog(1, row.id)"
            type="primary"
            :size="size"
        >编辑</el-button
        >-->

        <el-button
          icon="el-icon-view"
          text
          @click="openDialog(0, row)"
          type="primary"
          :size="size"
          >详情</el-button
        >
      </template>
    </avue-crud>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1800px"
      @close="dialog.visible = false"
    >
      <el-form
        class="header-box"
        label-width="80px"
        size="midium"
        v-model="searchForm"
        ref="searchFormRef"
      >
        <el-row>
          <el-col :span="5">
            <el-form-item label="物料型号" prop="materialModel">
              <el-input
                v-model="searchForm.materialModel"
                placeholder="请输入物料型号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="产品批号" prop="workOrderCode">
              <el-input
                v-model="searchForm.workOrderCode"
                placeholder="请输入产品批号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="开始日期"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5" style="margin-left: -55px">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="结束日期"
                clearable
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button type="default" icon="el-icon-delete" @click="handleReset">
            清空
          </el-button>
        </el-row>
      </el-form>
      <el-table :data="itemList" border style="width: 100%">
        <el-table-column
          show-overflow-tooltip
          prop="operationName"
          label="工序"
          width="90"
        />
        <el-table-column
          show-overflow-tooltip
          prop="materialModel"
          label="物料型号"
          width="90"
        />
        <el-table-column
          show-overflow-tooltip
          prop="workOrderCode"
          label="产品批号"
          width="90"
        />
        <el-table-column prop="reReceiveUser" label="操作人" width="140">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.reReceiveUser"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="reDate" label="时间" width="120">
          <template v-if="dialog.type === 1" #default="scope">
            <el-date-picker
              value-format="YYYY-MM-DD"
              type="date"
              v-model="scope.row.reDate"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="reNum" label="接收数量" width="80">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.reNum"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="next0Num" label="合格品数" width="80">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next0Num"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="next1Num" label="不合格品数" width="80">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next1Num"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="passRate" label="合格品率" width="80">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.passRate"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="useDevice" label="使用设备及编号" width="150">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.useDevice"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="craftCondition" label="实时工艺条件" width="160">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.craftCondition"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="temperature" label="温度" width="85">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.temperature"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="humidity" label="湿度" width="85">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.humidity"></el-input>
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" width="100">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="none" label="关联表单">
          <!--          <template  #default="scope">
            <el-button v-if="scope.row.type == 1" @click="clickH(scope.row)" type="primary" link>
              工作记录表
            </el-button>
          </template>-->
          <template #default="scope">
            <el-button
              icon="el-icon-setting"
              text
              @click="formList(scope.row)"
              type="primary"
              size="small"
              >表单列表</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer" align="center" style="margin-top: 10px">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleExport"
          v-if="itemList.value !== 0"
          >导 出</el-button
        >
      </div>
      <div>
        <pagination
          v-model:total="total"
          v-model:page="searchForm.pageNo"
          v-model:limit="searchForm.pageSize"
          @pagination="handleQuery"
        />
      </div>
    </el-dialog>
    <el-dialog
      v-model="dialog1.visible"
      :title="dialog1.title"
      width="800px"
      @close="dialog1.visible = false"
    >
      <el-form
        label-width="120px"
        size="large"
        :model="hInfo"
        ref="applyFormRef"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="电路型号" prop="materialModel">
              <el-input v-model="hInfo.materialModel" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产批号" prop="workOrderCode">
              <el-input v-model="hInfo.workOrderCode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="工艺规程" prop="craft">
              <el-input v-model="hInfo.craft" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品装配图" prop="drawing">
              <el-input v-model="hInfo.drawing" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="温度" prop="temperature">
              <el-input v-model="hInfo.temperature" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相对湿度" prop="humidity">
              <el-input v-model="hInfo.humidity" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="烤箱温度设置" prop="temperatureSet">
              <el-input v-model="hInfo.temperatureSet" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="烘烤时间" prop="bakeTime">
              <el-input v-model="hInfo.bakeTime" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="烘箱真空度" prop="vacuum">
              <el-input v-model="hInfo.vacuum" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="氦气流量" prop="nitrogen">
              <el-input v-model="hInfo.nitrogen" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="氧含量" prop="oxygen">
              <el-input v-model="hInfo.oxygen" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="封前箱内相对湿度监控值" prop="frontHumidity">
              <el-input v-model="hInfo.frontHumidity" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="封焊功率" prop="sealPower">
              <el-input v-model="hInfo.sealPower" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="封焊压力" prop="sealPressure">
              <el-input v-model="hInfo.sealPressure" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="封焊速度" prop="sealSpeed">
              <el-input v-model="hInfo.sealSpeed" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="封装数" prop="num">
              <el-input v-model="hInfo.num" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格数" prop="passNum">
              <el-input v-model="hInfo.passNum" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="操作者" prop="operator">
              <el-input v-model="hInfo.operator" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="日期" prop="operatorTime">
              <el-date-picker
                value-format="YYYY-MM-DD"
                type="date"
                v-model="hInfo.operatorTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="dialog-footer" align="center" style="margin-top: 10px">
        <el-button @click="dialog1.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleExport1">导 出</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-model="dialog8.visible"
      :title="dialog8.title"
      width="950px"
      @close="dialog8.visible = false"
    >
      <el-card
        style="cursor: pointer; font-size: 20px"
        shadow="always"
        :key="index"
        @click="toShowExcel(item)"
        v-for="(item, index) in showProList"
        >{{ item.formName }}-{{ item.formCode }}({{ item.seqs }})</el-card
      >
    </el-dialog>
    <el-dialog
      v-model="excelShow"
      title="详情"
      @close="excelShow = false"
      width="1600"
      destroy-on-close
    >
      <ExcelDataBbox :data="ExDataObj" @close="excelShow = false" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
import { useCrud } from "@/hooks/userCrud";
import {
  exportOperationRecord,
  exportOperationRecord1,
  queryFormList,
  addProRecord,
  queryProductHandoverPage,
  updateHandoverList,
  queryHInfo,
  saveOpDetails,
} from "@/api/process";
import { useCommonStoreHook } from "@/store";
import dictDataUtil from "@/common/configs/dictDataUtil";
const { isShowTable, tableType } = toRefs(useCommonStoreHook());
import ExcelDataBbox from "@/views/base/apply/excelDataBbox.vue";
const test = () => {
  isShowTable.value = true;
  tableType.value = tableType.value == 1 ? 2 : 1;
};
const radio = ref(0);
// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    dataListUrl: "/api/v1/proRecord/queryCompleteOpList",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件
const { checkBtnPerm, downloadTemplate, exportData } = Utils; //按钮权限等工具
const loading = ref(false);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const dialog = reactive({
  title: "工作记录",
  visible: false,
  type: 0,
});

const searchForm = ref({
  materialModel: "",
  workOrderCode: "",
  startDate: "",
  endDate: "",
  pageNo: 1,
  pageSize: 10,
});
const total = ref(0);

const handleQuery = () => {
  queryProductHandoverPage(searchForm.value).then((data) => {
    itemList.value = data.data.records;
    total.value = data.data.totalCount;
  });
};

const handleSearch = () => {
  queryProductHandoverPage(searchForm.value).then((data) => {
    itemList.value = data.data.records;
    total.value = data.data.totalCount;
  });
};
const handleReset = () => {
  // 重置表单
  Object.assign(searchForm.value, {
    materialModel: "",
    workOrderCode: "",
    startDate: "",
    endDate: "",
    pageNo: 1,
    pageSize: 10,
  });
};

const dialog1 = reactive({
  title: "工作记录",
  visible: false,
});
const dialog8 = reactive({
  title: "表单列表",
  visible: false,
});
const showProList = ref([]);
const formList = (row) => {
  queryFormList({
    ...search.value,
    workOrderId: row.workOrderId,
    operationId: row.operationId,
  }).then((data) => {
    if (data.data.length > 0) {
      showProList.value = data.data;
      dialog8.visible = true;
    } else {
      ElMessage.error("未关联到表单");
    }
  });
};
const excelShow = ref(false);
const ExDataObj = ref({});
const toShowExcel = (item) => {
  ExDataObj.value = item;
  excelShow.value = true;
};
const createRowSave = (row, done, loading) => {
  form.value.type = "1";
  addProRecord(form.value)
    .then((data) => {
      ElMessage.success(data.msg);
      form.value.startDate = "";
      form.value.endDate = "";
      done();
      dialog.visible = true;
      dialog.type = 1;
      itemList.value = data.data;
      dataList();
    })
    .catch(() => {
      loading();
    });
};
const itemList = ref([]);
const hInfo = ref({
  operator: "",
  materialModel: "",
});
const clickOperationType = ref(null);
const openDialog = (type, row) => {
  clickOperationType.value = row.operationType;
  row.type = 1;
  searchForm.value = {
    ...row,
    pageNo: 1,
    pageSize: 10,
  };
  queryProductHandoverPage(row).then((data) => {
    itemList.value = data.data.records;
    total.value = data.data.totalCount;
    dialog.visible = true;
    dialog.type = type;
  });
};
const clickH = (row) => {
  if (null === row.detailId) {
    hInfo.value = JSON.parse(JSON.stringify(row));
    hInfo.value.operator = row.reReceiveUser;
    hInfo.value.operatorTime = row.reDate;
    hInfo.value.handoverId = row.id;
    hInfo.value.num = row.reNum;
  } else {
    queryHInfo(row.detailId).then((data) => {
      hInfo.value = data.data;
    });
  }
  dialog1.visible = true;
};

const saveDetails = () => {
  saveOpDetails(hInfo.value).then((data) => {
    ElMessage.success("操作成功");
    dialog1.visible = false;
  });
};
const saveItemList = () => {
  updateHandoverList(itemList.value).then((data) => {
    if (data.code === "200") {
      ElMessage.success("操作成功");
      dialog.visible = false;
      form.value.type = "1";
      search.value.type = "1";
      dataList();
    } else {
      ElMessage.error(data.msg);
    }
  });
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  editBtn: false,
  viewBtn: false,
  delBtn: false,
  addBtn: false,
  selection: false,
  column: [
    {
      label: "开始日期",
      prop: "startDate",
      type: "date",
      format: "YYYY-MM-DD", //前端展示格式
      valueFormat: "YYYY-MM-DD", //设置后端接收的日期格式
      overHidden: true,
      search: true,
    },
    {
      label: "结束日期",
      prop: "endDate",
      type: "date",
      format: "YYYY-MM-DD", //前端展示格式
      valueFormat: "YYYY-MM-DD", //设置后端接收的日期格式
      search: true,
      overHidden: true,
    },
    {
      label: "工序类型",
      overHidden: true,
      prop: "operationType",
      search: true,
      type: "select",
      dicUrl: dictDataUtil.request_url + dictDataUtil.TYPE_CODE.process_type,
      props: {
        label: "dictLabel",
        value: "dictValue",
      },
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: "完工数量",
      overHidden: true,
      prop: "completeNum",
      addDisplay: false,
      editDisplay: false,
    },
  ],
});
const handleExport = () => {
  exportOperationRecord({
    ...searchForm.value,
    operationType: clickOperationType.value,
    type: 1,
  }).then((response) => {
    try {
      const decoder = new TextDecoder("utf-8");
      const jsonString = decoder.decode(response.data);
      const jsonObject = JSON.parse(jsonString);
      const { code, msg } = jsonObject;
      if (code != "200") {
        ElMessage.error(msg);
      }
    } catch (e) {
      downFile(response);
    }
  });
};
const handleExport1 = () => {
  exportOperationRecord1(hInfo.value).then((response) => {
    try {
      const decoder = new TextDecoder("utf-8");
      const jsonString = decoder.decode(response.data);
      const jsonObject = JSON.parse(jsonString);
      const { code, msg } = jsonObject;
      if (code != "200") {
        ElMessage.error(msg);
      }
    } catch (e) {
      downFile(response);
    }
  });
};
const downFile = (response) => {
  const fileData = response.data;
  const fileName = decodeURI(
    response.headers["content-disposition"].split(";")[1].split("=")[1]
  );
  const fileType =
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
  const blob = new Blob([fileData], { type: fileType });
  const downloadUrl = window.URL.createObjectURL(blob);
  const downloadLink = document.createElement("a");
  downloadLink.href = downloadUrl;
  downloadLink.download = fileName;
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
  window.URL.revokeObjectURL(downloadUrl);
};
onMounted(() => {
  form.value.type = "1";
  search.value.type = "1";
  const now = new Date();
  const year = now.getFullYear();
  let month = now.getMonth() + 1; // 从0开始的月份
  // 当月结束日期
  const daysInMonth = new Date(year, now.getMonth() + 1, 0).getDate();
  month = month.toLocaleString().length === 1 ? "0" + month : month;
  search.value.startDate = year + "-" + month + "-" + "01";
  search.value.endDate = year + "-" + month + "-" + daysInMonth;
  dataList();
});
</script>
<style>
.gray-header-table .el-table__header-wrapper {
  background-color: #f2f2f2; /* 灰色背景 */
}
.header-box .el-form-item {
  margin-left: 10px;
}
</style>
