<template>
  <div class="app-container">
    <!-- 操作按钮 -->
    <el-row :gutter="5" class="mb5">
      <el-col :span="1.5">
        <el-button
          type="primary"
          :loading="ensureLoading"
          size="mini"
          icon="el-icon-check"
          plain
          :disabled="updateDisable"
          @click="handleAddInspectEnsure"
          >提交</el-button
        >
        <el-button
          v-if="$route.query.id && auditStatus === '1'"
          type="primary"
          size="mini"
          icon="el-icon-copy-document"
          plain
          @click="handleCopyCase"
          >复制</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="$route.query.id"
          v-hasPermi="['wms:material-item-master:update']"
          class="text-right"
          size="mini"
          type="primary"
          icon="el-icon-edit"
          :disabled="updateDisable"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
    </el-row>
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="88px"
    >
      <SearchBar :show-more="false" :show-span="18">
        <template #header>
          <el-col :span="6">
            <el-form-item label="方案编码" prop="inspectionNo">
              <el-input
                v-model="queryParams.inspectionNo"
                placeholder="方案编码为自动生成，无需填写"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方案名称" prop="inspectionName">
              <el-input
                v-model="queryParams.inspectionName"
                placeholder="请输入方案名称"
                :disabled="inspectDisable"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方案类型" prop="caseInspectionType">
              <el-select
                v-model="queryParams.caseInspectionType"
                placeholder="请选择方案类型"
                clearable
                size="small"
                disabled
              >
                <el-option
                  v-for="dict in getDictDatas(
                    DICT_TYPE.WMS_INSPECTION_CATEGORY
                  )"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </template>
      </SearchBar>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:material-item:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="updateDisable"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      max-height="450px"
      border
      size="mini"
    >
      <el-table-column label="检验项编码" align="center" prop="inspectionNo">
        <template slot-scope="scope">
          <div class="searchCase">
            <InspectCaseSelect
              ref="inspectCaseSelect"
              v-model="scope.row.inspectionNo"
              class="selects"
              filterable
              :list="list"
              :type="queryParams.type"
              placeholder="请选择检验项编码"
              :disabled="scope.row.isEditCase !== 0"
              @change="inspectCaseChange"
            />
            <el-button
              v-if="scope.row.isEditCase === 0"
              class="icon"
              icon="el-icon-zoom-out"
              @click="handleCaseDetail"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="检验项名称"
        align="center"
        prop="inspectionName"
      />
      <el-table-column label="检验项类型" align="center" prop="inspectionModel">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.WMS_INSPECTION_TYPE"
            :value="scope.row.inspectionModel"
          />
        </template>
      </el-table-column>
      <el-table-column label="检验类别" align="center" prop="inspectionType">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.WMS_INSPECTION_CATEGORY"
            :value="scope.row.inspectionType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['wms:material-item:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            class="text-danger"
            :disabled="updateDisable"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加检验项 -->
    <AddInspectionItems
      ref="addInspectionItems"
      :caselist="caselist"
      @addComplete="addComplete"
      @getSelectList="getSelectList"
      @closeIds="handleClosedIdList"
    />
  </div>
</template>

<script>
import {
  updateAllMaterialItem,
  modifyMaterialItem,
  getMaterialPage,
  createMaterialItemMaster,
} from "@/api/wms/quality/inspectionCase";
import AddInspectionItems from "./AddInspectionItems.vue";
import InspectCaseSelect from "./InspectCaseSelect.vue";

export default {
  name: "HandleCase",
  components: {
    AddInspectionItems,
    InspectCaseSelect,
  },
  props: {
    inspectionType: {
      type: Number,
      default: 0,
    },
    caselist: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 确定遮罩层
      ensureLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 方案表头禁用
      inspectDisable: false,
      // 修改禁用
      updateDisable: false,
      // 总条数
      total: 0,
      // WMS 品质管理-检验项管理列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      caseParams: {},
      // 物料编码，modify时传
      materialNo: "",
      code: "",
      // 审批状态
      auditStatus: null,
      // 查询参数
      queryParams: {
        // pageNo: 1,
        // pageSize: 10,
        inspectionNo: null,
        inspectionName: null,
        inspectionModel: null,
        inspectionType: null,
        minValue: null,
        standValue: null,
        maxValue: null,
        createTime: [],
        inspectionItemId: null,
        // 检验项类型  iqc:0 oqc:2,fqc:1
        type: null,
        code: null,
        wmsMaterialAdditionalId: null,
        id: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inspectionNo: [
          { required: true, message: "检验项编码不能为空", trigger: "blur" },
        ],
        inspectionName: [
          { required: true, message: "检验项名称不能为空", trigger: "blur" },
        ],
      },
      // 过滤的id
      idList: [],
    };
  },
  created() {
    this.queryParams.caseInspectionType = this.$route.query.caseInspectionType;
    this.queryParams.type = this.$route.query.type;
    this.queryParams.inspectionNo = this.queryParams.code =
      this.$route.query.code;
    this.queryParams.inspectionName = this.$route.query.name;
    this.queryParams.id = this.$route.query.id;
    this.auditStatus = this.$route.query.auditStatus;
    this.queryParams.caseInspectionType = this.$route.query.type;
    if (this.auditStatus === "0" || this.auditStatus === "1") {
      this.updateDisable = true;
    }
    if (this.$route.query.id) {
      this.inspectDisable = true;
    }
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getMaterialPage(this.queryParams)
        .then((response) => {
          this.list = response.data.list;
          // const isExperiod = this.list.findIndex(item => item.inspectionNo === 'IQCEXPERIOD')
          // if (isExperiod === -1 && this.queryParams.type === '0' && (Number(this.auditStatus) === -1 || this.auditStatus === null)) {
          //   this.list.unshift(
          //     {
          //       inspectionNo: 'IQCEXPERIOD',
          //       inspectionName: '是否在保质期内',
          //       inspectionModel: 1,
          //       inspectionType: 0,
          //       id: '1000000000000000001',
          //       isEditCase: 1,
          //       inspectionItemId: '1000000000000000001'
          //     })
          //   if (this.list.length === 1) {
          //     this.idList.push(this.list[0].id)
          //   }
          // }
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        inspectionNo: undefined,
        inspectionName: undefined,
        inspectionModel: undefined,
        inspectionType: undefined,
        minValue: undefined,
        standValue: undefined,
        maxValue: undefined,
        code: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.list.push({
        inspectionNo: "",
        inspectionName: "",
        inspectionModel: "",
        inspectionType: "",
        id: "",
        isEditCase: 0,
      });
      // 新增滚动条定位到最下面
      this.$nextTick(() => {
        const wrapper = this.$refs.table.$el.querySelector(
          ".el-table__body-wrapper"
        );
        wrapper.scrollTop = wrapper.scrollHeight;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { id, inspectionName } = row;
      const index = this.list.findIndex((item) => item.id === id);
      if (index > -1) {
        this.$modal
          .confirm('是否确认删除检验项名称为"' + inspectionName + '"的数据项?')
          .then(() => {
            this.list.splice(index, 1);
            this.idList.splice(index, 1);
          })
          .catch(() => {
            this.$modal.msg("您已取消操作");
          });
      }
    },
    inspectCaseChange(v) {
      const {
        id,
        inspectionName,
        inspectionModel,
        inspectionType,
        inspectionNo,
        inspectionItemId,
      } = v;
      const filterObj = this.list.find(
        (item) => item.inspectionNo === inspectionNo
      );
      filterObj.inspectionName = inspectionName;
      filterObj.inspectionModel = inspectionModel;
      filterObj.inspectionNo = inspectionNo;
      filterObj.inspectionType = inspectionType;
      filterObj.inspectionItemId = inspectionItemId;
      filterObj.id = id;
      filterObj.isEditCase = 1;
      this.idList.push(id);
    },
    handleCaseDetail() {
      const { type, inspectionNo } = this.queryParams;
      this.reset();
      this.$refs.addInspectionItems.queryParams.materialItemCode = inspectionNo;
      this.$refs.addInspectionItems.queryParams.inspectionType = type;
      this.$refs.addInspectionItems.modifyParams = this.caseParams;
      this.$refs.addInspectionItems.modifyParams.wmsMaterialAdditionalId =
        this.queryParams.wmsMaterialAdditionalId;
      this.$refs.addInspectionItems.materialNo = this.materialNo;
      this.$refs.addInspectionItems.open = true;
      this.list.reduce((acc, cur) => {
        if (!acc.includes(cur.inspectionItemId)) {
          if (cur.inspectionItemId) {
            acc.push(cur.inspectionItemId);
          }
        }
        return acc;
      }, this.idList);
      this.$refs.addInspectionItems.queryParams.idList = this.idList;
    },
    // 新增完刷新页面
    addComplete() {
      this.getList();
      this.$emit("caseComplete");
    },
    // 复制方案
    handleCopyCase() {
      this.queryParams.inspectionNo = null;
      this.queryParams.inspectionName = null;
      this.queryParams.id = null;
      this.updateDisable = false;
      const isExperiod = this.list.findIndex(
        (item) => item.inspectionNo === "IQCEXPERIOD"
      );
      if (isExperiod > -1) {
        this.idList.push(this.list[isExperiod].id);
      }
    },
    // 提交
    async handleAddInspectEnsure() {
      const { inspectionName, id, inspectionNo, type, caseInspectionType } =
        this.queryParams;
      const itemList = this.list.map((item) => {
        const { inspectionItemId, inspectionType: type } = item;
        return {
          inspectionItemId,
          type,
        };
      });
      const paramsList = {
        itemList,
        code: inspectionNo,
        id,
        name: inspectionName,
        type: caseInspectionType,
        status: type,
      };
      const addParams = {
        itemList,
        code: inspectionNo,
        name: inspectionName,
        type,
      };
      this.ensureLoading = true;
      if (this.queryParams.id) {
        try {
          const { data } = await updateAllMaterialItem(paramsList);
          this.$modal.msgSuccess("修改成功！");
          this.getList();
          this.$router.replace({
            path: this.$route.path,
            query: {
              id: data,
              caseInspectionType: this.queryParams.caseInspectionType,
              code: this.queryParams.code,
              auditStatus: this.auditStatus,
            },
          });
        } catch (error) {
          console.log(error);
        } finally {
          this.ensureLoading = false;
        }

        // await updateAllMaterialItem(paramsList).then(response => {
        //   this.$modal.msgSuccess('修改成功')
        //   this.getList()
        //   // this.$emit('caseComplete')
        //   // 关闭当前窗口
        //   this.$tab.closeOpenPage()
        //   // this.$router.go(-1)
        //   // 检验项类型  iqc:0 oqc:2,fqc:1
        //   if (this.queryParams.type === '0') {
        //     this.$router.push({ path: '/quality/iqcInspection/inspectionCase', query: { id: response.data }})
        //   } else if (this.queryParams.type === '1') {
        //     this.$router.push({ path: '/quality/fqcInspection/fqcInspectionCase', query: { id: response.data }})
        //   } else if (this.queryParams.type === '2') {
        //     this.$router.push({ path: '/quality/oqcInspection/oqcInspectionCase', query: { id: response.data }})
        //   }
        // }).finally(() => {
        //   this.ensureLoading = false
        // })
      } else {
        try {
          const { data } = await createMaterialItemMaster(addParams);
          this.$modal.msgSuccess("新增成功!");
          this.getList();
          this.$tab.closeOpenPage();
          this.$router.go(-1);

          if (this.queryParams.type === "0") {
            this.$router.push({
              path: "/quality/iqcInspection/inspectionCase",
              query: { id: data },
            });
          } else if (this.queryParams.type === "1") {
            this.$router.push({
              path: "/quality/fqcInspection/fqcInspectionCase",
              query: { id: data },
            });
          } else if (this.queryParams.type === "2") {
            this.$router.push({
              path: "/quality/oqcInspection/oqcInspectionCase",
              query: { id: data },
            });
          }
        } catch (error) {
          console.log(error);
        } finally {
          this.ensureLoading = false;
        }

        // await createMaterialItemMaster(addParams).then(res => {
        //   this.$modal.msgSuccess('新增成功')
        //   this.getList()
        //   // this.$emit('caseComplete')
        //   // 关闭当前窗口
        // }).finally(() => {
        //   this.ensureLoading = false
        // })
      }

      const modifyMaterialParams = {
        updateReqVO: this.caselist,
        wmsMaterialItemMasterId: this.caseParams.id,
        wmsMaterialAdditionalId: this.queryParams.wmsMaterialAdditionalId,
        materialNo: this.materialNo,
      };
      if (this.queryParams.wmsMaterialAdditionalId === null) {
        return;
      }
      modifyMaterialItem(modifyMaterialParams).then(() => {
        this.$emit("caseComplete");
      });
    },
    // 修改检验方案-表头
    handleUpdate() {
      this.inspectDisable = false;
    },
    dialogClose() {
      this.queryParams.inspectionNo = undefined;
      this.queryParams.inspectionName = undefined;
      this.queryParams.code = undefined;
      this.getList();
      this.idList = [];
    },
    // 获取取消的idList
    handleClosedIdList(v) {
      this.idList = v;
      const isExperiod = this.list.findIndex(
        (item) => item.inspectionNo === "IQCEXPERIOD"
      );
      if (isExperiod > -1) {
        this.idList.push(this.list[isExperiod].id);
      }
    },
    // 添加多项检验方案传回来的值
    getSelectList(v, idList) {
      this.list = this.list.filter((item) => item.inspectionNo !== "");
      this.idList = v.map((item) => {
        const { id } = item;
        return id;
      });
      this.list.push(...v);
      this.list.push({
        inspectionNo: "",
        inspectionName: "",
        inspectionModel: "",
        inspectionType: "",
        id: "",
        isEditCase: 0,
      });
      this.idList = idList;
    },
  },
};
</script>
<style scoped>
.searchCase {
  width: 100%;
}
.selects {
  position: relative;
}
.icon {
  position: absolute;
  top: 9px;
  right: 44px;
  width: 40px;
  height: 30px;
  border: none;
  padding: 10px;
}
</style>
