<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: selectRow,
        }"
        :action-list="[]"
        @get-list="getList"
      >
        <!-- {
            text: '质检',
            disabled: selectData.length === 0,
            action: () => start(20),
          }, -->
        <template #fileSlot="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickFile(item)"
          >
            {{ item.fileName }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      title="到货质检"
      v-model="dialogVisible"
      width="80%"
      v-loading="submitLoading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #products>
          <div style="width: 100%">
            <el-table :data="formData.data.qualityDetailsList">
              <el-table-column
                prop="productDefinition"
                label="物品类型"
                :formatter="
                  (row) =>
                    row.productDefinition == 1
                      ? '产品'
                      : row.productDefinition == 2
                      ? '物料'
                      : ''
                "
              />
              <el-table-column prop="productCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="productSpec" label="规格型号" />
              <el-table-column prop="productUnit" label="单位" />
              <el-table-column prop="quantity" label="到货数量" />
              <el-table-column prop="qualityQuantity" label="已质检" />
              <el-table-column
                prop="qualifiedQuantity"
                label="质检合格"
                min-width="150"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="
                      'qualityDetailsList.' + $index + '.qualifiedQuantity'
                    "
                    :rules="rules.qualifiedQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.qualifiedQuantity"
                      :precision="2"
                      :controls="false"
                      :min="0"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="disqualificationQuantity"
                label="质检不合格"
                min-width="150"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="
                      'qualityDetailsList.' +
                      $index +
                      '.disqualificationQuantity'
                    "
                    :rules="rules.disqualificationQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.disqualificationQuantity"
                      :precision="2"
                      :controls="false"
                      :min="0"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
const qualityStatusData = [
  {
    label: "未质检",
    value: "0",
  },
  {
    label: "部分质检",
    value: "1",
  },
  {
    label: "已质检",
    value: "2",
  },
];
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  qualifiedQuantity: [
    { required: true, message: "请输入质检合格数量", trigger: "blur" },
  ],
  disqualificationQuantity: [
    { required: true, message: "请输入质检不合格数量", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "质检状态",
    prop: "qualityStatus",
    data: qualityStatusData,
  },
]);
const config = computed(() => {
  return [
    // {
    //   type: "selection",
    //   attrs: {
    //     checkAtt: "isCheck",
    //   },
    // },
    {
      attrs: {
        label: "采购单号",
        prop: "purchaseCode",
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "supplyName",
      },
    },
    {
      attrs: {
        label: "物流/快递公司",
        prop: "logisticsCompanyName",
      },
    },

    {
      attrs: {
        label: "物流/快递单号",
        prop: "logisticsCode",
      },
    },
    {
      attrs: {
        label: "采购员",
        prop: "purchaseUserName",
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "purchaseTime",
      },
    },
    {
      attrs: {
        label: "质检状态",
        prop: "qualityStatus",
      },
      render(status) {
        const current = qualityStatusData.find((x) => x.value == status);
        if (current) return current.label;
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.qualityStatus < 2
            ? {
                attrs: {
                  label: "质检",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  selectDataOne.value = [row];
                  start(10);
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = reactive([
  {
    type: "title",
    title: "到货信息",
  },
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
  },
  {
    type: "input",
    prop: "logisticsCompanyName",
    label: "物流快递信息",
    placeholder: "物流/快递公司",
    itemWidth: 20,
    disabled: true,
  },
  {
    type: "input",
    prop: "logisticsCode",
    label: " ",
    itemWidth: 30,
    placeholder: "物流/快递单号",
    disabled: true,
  },
  {
    type: "title",
    title: "质检明细",
  },
  {
    type: "slot",
    slotName: "products",
  },
]);

const byform = ref(null);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/qualityInfo/page1", sourceList.value.pagination)
    .then((message) => {
      message.rows.forEach((x) => {
        if (x.qualityStatus < 2) {
          x.isCheck = true;
        } else {
          x.isCheck = false;
        }
      });
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.qualityDetailsList;
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (!(e.qualifiedQuantity + e.disqualificationQuantity > 0)) {
        return ElMessage({
          message: "质检数量不能为0！",
          type: "info",
        });
      }
      if (
        e.qualifiedQuantity +
          e.disqualificationQuantity +
          Number(e.qualityQuantity) >
        Number(e.quantity)
      ) {
        return ElMessage({
          message: "质检数量不能大于到货数量！",
          type: "info",
        });
      }
      delete e.id
    }
    submitLoading.value = true;
    proxy.post("/qualityInfo/" + modalType.value, formData.data).then(
      (res) => {
        ElMessage({
          message: "质检成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  dialogVisible.value = true;
  // proxy.post("/productionProcesses/detail", { id: row.id }).then((res) => {
  //   formData.data = res;
  //   dialogVisible.value = true;
  // });
};

getList();
const selectData = ref([]);
const selectDataOne = ref([]);

const selectRow = (data) => {
  selectData.value = data;
};

const start = (type) => {
  modalType.value = "add";
  let ids = [];
  let row = {};
  if (type === 10) {
    row = selectDataOne.value[0];
    ids = selectDataOne.value.map((x) => x.id);
  } else if (type === 20) {
    ids = selectData.value.map((x) => x.id);
    row = selectData.value[0];
  }
  proxy.post("/arrivalStockRecords/detail", { id: ids[0] }).then((res) => {
    formData.data = {
      arrivalStockRecordsId: row.id,
      supplyName: row.supplyName,
      logisticsCompanyName: row.logisticsCompanyName,
      logisticsCode: row.logisticsCode,
      qualityDetailsList: res.arrivalStockRecordsDetailsList.map((x) => ({
        ...x,
        arrivalStockRecordsDetailsId: x.id,
        qualifiedQuantity: 0,
        disqualificationQuantity: 0,
      })),
    };
    dialogVisible.value = true;
  });
};

// watch(selectData, (newVal, oldVal) => {
//   if (newVal.length == 0) {
//     sourceList.value.data.forEach((x) => {
//       if (x.status < 20) {
//         x.isCheck = true;
//       } else {
//         x.isCheck = false;
//       }
//     });
//   } else if (newVal.length == 1) {
//     const current = newVal[0];
//     sourceList.value.data.forEach((x) => {
//       if (x.arrivalId !== current.arrivalId || x.status == 20) {
//         x.isCheck = false;
//       }
//     });
//   }
// });

onMounted(() => {});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}

.el-checkbox {
  display: none;
}
</style>