<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: select,
        }"
        :action-list="[
          {
            text: '质检',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #code="{ item }">
          <div style="cursor: pointer; color: #409eff" @click="getDtl(item)">
            {{ item.code }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '京东退货质检' : '质检详情'"
      v-model="dialogVisible"
      width="70%"
      v-loading="loading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #products>
          <div style="width: 100%">
            <el-button
              type="primary"
              @click="handleOpen"
              style="margin-bottom: 10px"
              v-if="modalType == 'add'"
            >
              选择产品
            </el-button>
            <el-button
              type="primary"
              @click="openExcel"
              style="margin-bottom: 10px"
              v-if="modalType == 'add'"
            >
              导入Excel
            </el-button>
            <el-table :data="formData.data.list">
              <el-table-column
                prop="productType"
                label="物品类型"
                :formatter="
                  (row) => (row.productType == '1' ? '成品' : '半成品')
                "
              />
              <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="待质检数量"
                v-if="modalType == 'add'"
              />
              <el-table-column
                prop="qualifiedQuantity"
                label="质检合格"
                min-width="150"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'list.' + $index + '.qualifiedQuantity'"
                    :rules="rules.qualifiedQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.qualifiedQuantity"
                      :precision="4"
                      :controls="false"
                      :min="0"
                      onmousewheel="return false;"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="disqualificationQuantity"
                label="质检不合格"
                min-width="150"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'list.' + $index + '.disqualificationQuantity'"
                    :rules="rules.disqualificationQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.disqualificationQuantity"
                      :precision="4"
                      :controls="false"
                      :min="0"
                      onmousewheel="return false;"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                prop="zip"
                label="操作"
                width="60"
                fixed="right"
                align="center"
                v-if="modalType == 'add'"
              >
                <template #default="{ $index }">
                  <el-button type="primary" link @click="handleRemove($index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer v-if="modalType == 'add'">
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="openProduct"
      title="选择产品"
      width="70%"
      append-to-body
    >
      <div>
        <el-button type="primary" @click="handleExcel"> 导出Excel </el-button>
      </div>
      <byTable
        :hideSearch="true"
        :source="sourceList.dataOne"
        :pagination="sourceList.paginationOne"
        :config="configOne"
        highlight-current-row
        :selectConfig="[]"
        :table-events="{}"
        :action-list="[]"
      >
      </byTable>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openProduct = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="Excel导入"
      v-model="openExcelDialog"
      width="400"
      v-loading="excelLoading"
      destroy-on-close
    >
      <div>
        <el-upload
          :action="actionUrl + '/jdBackQualityWait/importExcel'"
          :headers="headers"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :show-file-list="false"
          :on-error="handleError"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">点击导入</el-button>
        </el-upload>
      </div>

      <template #footer>
        <el-button @click="openExcelDialog = false" size="large"
          >取 消</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, defineComponent, ref } from "vue";
import useUserStore from "@/store/modules/user";
import SelectProduct from "@/components/WDLY/product/SelectProduct";
import OrderDetails from "@/components/WDLY/order/details";
import { getToken } from "@/utils/auth";
const headers = ref({ Authorization: "Bearer " + getToken() });
const actionUrl = import.meta.env.VITE_APP_BASE_API;

let openExcelDialog = ref(false);
let excelLoading = ref(false);
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  dataOne: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
  paginationOne: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let openProduct = ref(false);
let openDetails = ref(false);

let roomDialogVisible = 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([]);

const config = computed(() => {
  return [
    {
      attrs: {
        label: "质检单号",
        prop: "code",
        slot: "code",
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
      },
    },
    {
      attrs: {
        label: "合格数量",
        prop: "qualifiedQuantity",
      },
    },
    {
      attrs: {
        label: "不合格数量",
        prop: "disqualificationQuantity",
      },
    },
    {
      attrs: {
        label: "质检人员",
        prop: "qualityUserName",
      },
    },
    {
      attrs: {
        label: "质检日期",
        prop: "createTime",
      },
    },
  ];
});
const configOne = computed(() => {
  return [
    {
      attrs: {
        label: "物品类型",
        prop: "productType",
      },
      render(type) {
        return type == 1 ? "成品" : "半成品";
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
      },
    },
    {
      attrs: {
        label: "待质检数量",
        prop: "quantity",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "选择",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleSelect(row);
            },
          },
        ];
      },
    },
  ];
});
let formData = reactive({
  data: {},
  treeData: [],
  orderData: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeData = ref([]);
const formConfig = reactive([
  {
    type: "title",
    title: "质检明细",
  },
  {
    type: "slot",
    slotName: "products",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/jdBackQualityDetails/page", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    list: [],
  };
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.list;
    if (!list.length > 0)
      return ElMessage({
        message: `请添加质检明细！`,
        type: "info",
      });
    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.quantity)
      ) {
        return ElMessage({
          message: `质检合格数量加不合格数量不能大于待质检数量！`,
          type: "info",
        });
      }
    }
    submitLoading.value = true;
    proxy
      .post("/jdBackQualityDetails/" + modalType.value, formData.data.list)
      .then(
        (res) => {
          ElMessage({
            message: modalType.value == "add" ? "添加成功" : "编辑成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
  });
};

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

const warehouseList = ref([]);
const salesType = ref([]);

const getDict = () => {
  proxy.getDict(["order_sales_type"]).then((res) => {
    salesType.value = res["order_sales_type"];
    formConfig[1].data = salesType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    selectConfig[0].data = salesType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);

getList();
getDict();

const totalAmount = () => {
  let sum = 0;
  for (let i = 0; i < formData.data.list.length; i++) {
    const e = formData.data.list[i];
    e.total = (e.qualifiedQuantity * 1000000 * e.quantity) / 1000000;
    sum += e.total;
  }
  formData.data.amountMoney = sum;
};

const handleSelect = (row) => {
  const flag = formData.data.list.some((x) => x.productId === row.productId);
  if (flag)
    return ElMessage({
      message: "该物品已选择",
      type: "info",
    });
  formData.data.list.push({
    productId: row.productId,
    productName: row.productName,
    productCode: row.productCode,
    productSpec: row.productSpec,
    productUnit: row.productUnit,
    quantity: row.quantity,
    qualifiedQuantity: null,
    disqualificationQuantity: null,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

const handleRemove = (index) => {
  formData.data.list.splice(index, 1);
  totalAmount();
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};

const handleClickCode = (row) => {
  formData.orderData = row;
  openDetails.value = true;
};

const handleOpen = () => {
  proxy
    .post("/jdBackQualityWait/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      sourceList.value.dataOne = res.rows;
      sourceList.value.paginationOne.total = res.total;
      openProduct.value = true;
    });
};

const handleExcel = () => {
  ElMessage({
    message: "请稍后",
    type: "success",
  });
  let xhr = new XMLHttpRequest();
  //域名是华为云的
  xhr.open("GET", `${actionUrl}/jdBackQualityWait/exportExcel`, true);
  xhr.responseType = "blob";
  xhr.setRequestHeader("Authorization", `Bearer ${getToken()}`);
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let url = window.URL.createObjectURL(xhr.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = "待质检列表.xlsx"; // 下载后文件名
      a.style.display = "none";
      document.body.appendChild(a);
      a.click(); // 点击下载
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a); // 下载完成移除元素
    }
  };
};

const openExcel = () => {
  openExcelDialog.value = true;
};
const handleProgress = () => {
  excelLoading.value = true;
};
const handleError = (err) => {
  console.log(res);
  ElMessage({
    message: `${err}，请重试！`,
    type: "info",
  });
  openExcelDialog.value = false;
  excelLoading.value = false;
};
const handleSuccess = (res) => {
  if (res.code != 200) {
    return ElMessage({
      message: `${res.msg}，请重试！`,
      type: "info",
    });
  } else {
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    formData.data.list = res.data;
    openExcelDialog.value = false;
    excelLoading.value = false;
  }
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>