<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="{ 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="90%"
      @close="dialog.visible = false"
    >
      <!--      <el-button
                class="ml-3"
                style="margin-bottom: 5px;"
                @click="handleExport"
            >
              <template #icon> <i-ep-download /> </template>导出
            </el-button>-->
      <el-form
        class="header-box"
        label-width="80px"
        size="midium"
        v-model="searchForm"
        ref="searchFormRef"
      >
        <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-form>

      <el-table
        :data="itemList"
        border
        style="width: 100%"
        span-method="objectSpanMethod"
      >
        <el-table-column
          show-overflow-tooltip
          prop="operationName"
          label="工序"
          width="100"
        />
        <el-table-column
          show-overflow-tooltip
          prop="materialModel"
          label="物料型号"
          width="100"
        />
        <el-table-column
          show-overflow-tooltip
          prop="workOrderCode"
          label="产品批号"
          width="120"
        />
        <el-table-column prop="reNum" label="数量(接收)" width="70">
          <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="reFrontUser" label="下传人(接收)" width="140">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.reFrontUser"></el-input>
          </template>
        </el-table-column>
        <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="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="next0FrontUser"
          label="下传人(下传合格)"
          width="140"
        >
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next0FrontUser"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="next0ReceiveUser"
          label="接收人(下传合格)"
          width="140"
        >
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next0ReceiveUser"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="next0Date" 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.next0Date"
            />
          </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="next1FrontUser"
          label="下传人(下传不合格)"
          width="140"
        >
          <template v-if="dialog.type === 1" #default="scope">
            <el-date-picker
              value-format="YYYY-MM-DD"
              type="date"
              v-model="scope.row.next1FrontUser"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="next1ReceiveUser"
          label="接收人(下传不合格)"
          width="140"
        >
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next1ReceiveUser"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="next1Date" label="时间(下传不合格)" width="100">
          <template v-if="dialog.type === 1" #default="scope">
            <el-input v-model="scope.row.next1Date"></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="remark" label="关联表单" width="120">
                  <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" style="margin-top: 10px" align="center">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleExport"
          v-if="itemList.value !== 0"
          >导 出</el-button
        >
        <pagination
          v-model:total="total"
          v-model:page="searchForm.pageNo"
          v-model:limit="searchForm.pageSize"
          @pagination="handleQuery"
        />
      </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,
  queryFormList,
  queryProductHandoverPage,
  updateHandoverList,
} 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 times = ref(null);
const crudRef = ref(null); //crudRef.value 获取avue-crud对象
const dialog = reactive({
  title: "产品交接",
  visible: false,
  type: 0,
});
const dialog0 = reactive({
  title: "完工工序",
  visible: false,
});
const createRowSave = (row, done, loading) => {
  if (!row.startDate || !row.endDate) {
    ElMessage.error("请选择日期");
    loading();
  } else {
    done();
    times.value = row;
    dialog0.visible = true;
  }

  /*form.value.type = "0"
  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 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 clickOperationType = ref(null);
const itemList = ref([]);
const openDialog = (type, row) => {
  clickOperationType.value = row.operationType;
  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 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 saveItemList = () => {
  updateHandoverList(itemList.value).then((data) => {
    if (data.code === "200") {
      ElMessage.success("操作成功");
      dialog.visible = false;
      dataList();
    } else {
      ElMessage.error(data.msg);
    }
  });
};
// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  searchEnter: true,
  editBtn: false,
  delBtn: false,
  viewBtn: 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 excelShow = ref(false);
const ExDataObj = ref({});
const toShowExcel = (item) => {
  ExDataObj.value = item;
  excelShow.value = true;
};
const handleExport = () => {
  if (data.value.length !== 0) {
    exportOperationRecord({
      ...searchForm.value,
      operationType: clickOperationType.value,
      type: 0,
    }).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);
      }
    });
  } else {
    ElMessage.error("请先搜索数据");
  }
};
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 = "0";
  search.value.type = "0";

  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; /* 灰色背景 */
}
</style>
