<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="[]" @get-list="getList">
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
    </div>
    <el-dialog title="出库" v-model="dialogVisible" width="1000" v-loading="submitLoading" destroy-on-close>
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="submitType == 4 ?rulesTwo :rulesOne " ref="byform">
        <template #countryId>
          <div style="width:100%">
            <el-select v-model="formData.data.countryId" placeholder="国家" style="width:100%" @change="(val) => getCityData(val, '20', true)"
                       :disabled="submitType == 4 ||submitType == 5 ">
              <el-option v-for="item in countryData" :label="item.chineseName" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </template>

        <template #provinceId>
          <div style="width:100%">
            <selectCity placeholder="省/洲" @change="(val) => getCityData(val, '30', true)" addressId="provinceId" addressName="provinceName"
                        v-model="formData.data" :data="provinceData" :disabled="submitType == 4 ||submitType == 5 ">
            </selectCity>
          </div>
        </template>

        <template #cityId>
          <div style="width:100%">
            <selectCity placeholder="城市" addressId="cityId" addressName="cityName" v-model="formData.data" :data="cityData"
                        :disabled="submitType == 4 ||submitType == 5 ">
            </selectCity>
          </div>
        </template>

        <template #products>
          <div style="width: 100%">
            <el-button type="primary" plain @click="handleShortcut"> 快捷填写</el-button>
            <el-button type="primary" @click="openExcel = true"> Excel导入</el-button>
            <el-table :data="formData.data.jdOrderDetailsList" show-summary :summary-method="getSummaries" style="margin-top:16px">
              <el-table-column prop="productCustomCode" label="物品编码" width="150" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="productSpec" label="规格" width="130" />
              <el-table-column prop="waitQuantity" label="应出库" width="100" />
              <el-table-column prop="receiptQuantity" label="已出库" width="100" />
              <el-table-column prop="quantity" label="本次出库" width="150">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'jdOrderDetailsList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                    <el-input-number v-model="row.quantity" :precision="2" :controls="false" :min="0" onmousewheel="return false;" />
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="quantity" label="调仓数量" min-width="150" v-if="submitType == 5">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'jdOrderDetailsList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true">
                    <el-input-number v-model="row.quantity" :precision="2" :controls="false" :min="0" onmousewheel="return false;" />
                  </el-form-item>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </template>
        <template #statisticsSlot>
          <div style="width: 100%; display: flex">
            <div style="margin-right: 20px">
              应出库：{{ statistics("waitQuantity") }}
            </div>
            <div style="margin-right: 20px">
              已出库：{{ statistics("receiptQuantity") }}
            </div>
            <div style="margin-right: 10px">
              本次出库：{{ statistics("quantity") }}
            </div>
          </div>
        </template>
      </byForm>
      <template #footer>
        <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="openExcel" title="excel导入" width="30%" append-to-body>
      <div v-loading="excelLoading">
        <div style="margin: 15px 0">
          <el-button @click="downloadTemplate" type="primary">Excel模板下载</el-button>
        </div>
        <el-upload :action="actionUrl + '/stockWait/issueExcelImport'" :headers="headers" :before-upload="useImportExcelStore().updateRequestHeaders"
                   :on-success="handleSuccess" :on-progress="handleProgress" :show-file-list="false" :on-error="handleError" accept=".xls, .xlsx">
          <el-button type="primary" plain>点击导入</el-button>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="openExcel = false" size="large">取 消</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="openProduct" title="选择产品" width="70%" append-to-body>
      <InventoryInquiry :selectStatus="true" :warehouseId="formData.data.outWarehouseId" @cancel="openProduct = false" @select="select"
                        :key="formData.data.outWarehouseId"></InventoryInquiry>

      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="openProduct = false">取消</el-button>
        </span>
      </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";
import InventoryInquiry from "@/views/purchaseSales/outAndInWarehouse/inventoryInquiry/index";
import { computed } from "vue";
import selectCity from "@/components/selectCity/index.vue";
const actionUrl = import.meta.env.VITE_APP_BASE_API;
import useImportExcelStore from "@/store/modules/importExcel";
const headers = computed(() => useImportExcelStore().requestHeaders);
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "2",
  },
});
const productUnit = ref([]);
const warehouseList = ref([]);
const logisticsData = ref([]);
let openProduct = ref(false);
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  type: [
    { required: true, message: "请选择仓库类型", trigger: ["blur", "change"] },
  ],
  warehouseId: [
    { required: true, message: "请选择仓库名称", trigger: "change" },
  ],
  outWarehouseId: [
    { required: true, message: "请选择调出仓库", trigger: "change" },
  ],
  inWarehouseId: [
    { required: true, message: "请选择调入仓库", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  logisticsCompanyCode: [
    { required: true, message: "请选择物流/快递公司", trigger: "change" },
  ],
  logisticsCode: [
    { required: true, message: "请输入物流/快递单号", trigger: "blur" },
  ],
  countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  contacts: [{ required: true, message: "请输入收件人", trigger: "blur" }],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
});
let rulesTwo = ref({
  type: [
    { required: true, message: "请选择仓库类型", trigger: ["blur", "change"] },
  ],
  warehouseId: [
    { required: true, message: "请选择仓库名称", trigger: "change" },
  ],
  outWarehouseId: [
    { required: true, message: "请选择调出仓库", trigger: "change" },
  ],
  inWarehouseId: [
    { required: true, message: "请选择调入仓库", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  logisticsCompanyCode: [
    { required: true, message: "请选择物流/快递公司", trigger: "change" },
  ],
  logisticsCode: [
    { required: true, message: "请输入物流/快递单号", trigger: "blur" },
  ],
  // countryId: [{ required: true, message: "请选择国家", trigger: "change" }],
  // contacts: [{ required: true, message: "请输入收件人", trigger: "blur" }],
  // phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
});
let rulesOne = ref({
  type: [
    { required: true, message: "请选择仓库类型", trigger: ["blur", "change"] },
  ],
  deliveryTime: [
    { required: true, message: "请选择预计送达时间", trigger: "change" },
  ],
  warehouseId: [
    { required: true, message: "请选择仓库名称", trigger: "change" },
  ],
  outWarehouseId: [
    { required: true, message: "请选择调出仓库", trigger: "change" },
  ],
  inWarehouseId: [
    { required: true, message: "请选择调入仓库", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
  // logisticsCompanyCode: [
  //   { required: true, message: "请选择物流/快递公司", trigger: "change" },
  // ],
  // logisticsCode: [
  //   { required: true, message: "请输入物流/快递单号", trigger: "blur" },
  // ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "数据来源",
    prop: "businessType",
    data: [],
  },
  {
    label: "出库状态",
    prop: "status",
    data: [],
  },
]);
const outboundType = ref([
  {
    label: "未出库",
    value: "0",
  },
  {
    label: "部分出库",
    value: "1",
  },
  {
    label: "出库完成",
    value: "2",
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
        width: 110,
      },
      render(type) {
        const current = businessType.find((x) => x.value == type);
        if (current) {
          return current.label;
        }
      },
    },
    {
      attrs: {
        label: "关联单号",
        prop: "businessCode",
        width: 220,
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "operatorName",
        width: 110,
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "详细地址",
        prop: "detailedAddress",
      },
    },

    {
      attrs: {
        label: "出库状态",
        prop: "status",
        width: 100,
      },
      render(status) {
        return status == 0 ? "未出库" : status == 1 ? "部分出库" : "出库完成";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
        fixed: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.status < 2
            ? {
                attrs: {
                  label: "出库",
                  type: "primary",
                  text: true,
                  disabled: row.status > 1,
                },
                el: "button",
                click() {
                  outBound(row);
                },
              }
            : {},
          {
            attrs: {
              label: "结束",
              type: "primary",
              text: true,
              disabled: false,
            },
            el: "button",
            click() {
              ElMessageBox.confirm(`您确定执行此操作吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                // 删除
                proxy
                  .post("/stockWait/edit", {
                    ...row,
                    status: 3,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "操作成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
let formConfig = ref([]);
const businessType = [
  { label: "生产任务出库", value: "7" },
  { label: "销售订单出库", value: "6" },
  { label: "京东订单出库", value: "5" },
  { label: "采购退货出库", value: "4" },
];
const configData = computed(() => [
  [
    {
      type: "title",
      title: "基础信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      required: true,
      disabled: true,
      itemWidth: 25,
      data: businessType,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "关联单号",
      required: true,
      disabled: true,
      itemWidth: 30,
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      itemWidth: 100,
      data: warehouseList.value,
      style: {
        width: "53%",
      },
    },
    {
      type: "select",
      prop: "logisticsCompanyCode",
      label: "物流/快递信息",
      placeholder: "物流/快递公司",
      itemWidth: 25,
      style: {
        width: "100%",
      },
      data: logisticsData.value,
      filterable: true,
    },
    {
      type: "input",
      prop: "logisticsCode",
      label: " ",
      placeholder: "物流/快递单号",
      itemWidth: 60,
      style: {
        width: "46%",
      },
    },
    {
      type: "input",
      prop: "contacts",
      label: "收件人",
      itemWidth: 25,
      placeholder: "收件人",
      disabled: true,
    },
    {
      type: "input",
      prop: "phone",
      label: "联系电话",
      itemWidth: 75,
      placeholder: "联系电话",
      disabled: true,
      style: {
        width: "100%",
      },
    },
    {
      type: "slot",
      slotName: "countryId",
      prop: "countryId",
      label: "收货信息",
      itemWidth: 33.33,
      disabled: true,
    },
    {
      type: "slot",
      slotName: "provinceId",
      label: " ",
      itemWidth: 33.33,
      disabled: true,
    },
    {
      type: "slot",
      slotName: "cityId",
      prop: "cityId",
      label: " ",
      itemWidth: 33.33,
      disabled: true,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "areaDetail",
      disabled: true,
    },
    {
      type: "title",
      title: "出库明细",
    },
    {
      type: "slot",
      slotName: "products",
    },
    // {
    //   type: "title",
    //   title: "出库统计",
    // },
    // {
    //   type: "slot",
    //   slotName: "statisticsSlot",
    //   label: "",
    // },
  ],
  [
    {
      type: "title",
      title: "基础信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      required: true,
      disabled: true,
      itemWidth: 25,
      data: businessType,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "关联单号",
      required: true,
      disabled: true,
      itemWidth: 30,
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      itemWidth: 100,
      data: warehouseList.value,
      style: {
        width: "53%",
      },
    },
    {
      type: "select",
      prop: "logisticsCompanyCode",
      label: "物流/快递信息",
      placeholder: "物流/快递公司",
      itemWidth: 25,
      style: {
        width: "100%",
      },
      data: logisticsData.value,
      filterable: true,
    },
    {
      type: "input",
      prop: "logisticsCode",
      label: " ",
      placeholder: "物流/快递单号",
      itemWidth: 60,
      style: {
        width: "46%",
      },
    },
    {
      type: "slot",
      slotName: "countryId",
      prop: "countryId",
      label: "收货信息",
      itemWidth: 33.33,
    },
    {
      type: "slot",
      slotName: "provinceId",
      label: " ",
      itemWidth: 33.33,
    },
    {
      type: "slot",
      slotName: "cityId",
      prop: "cityId",
      label: " ",
      itemWidth: 33.33,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "areaDetail",
    },
    {
      type: "title",
      title: "出库明细",
    },
    {
      type: "slot",
      slotName: "products",
    },
    // {
    //   type: "title",
    //   title: "出库统计",
    // },
    // {
    //   type: "slot",
    //   slotName: "statisticsSlot",
    //   label: "",
    // },
  ],
  [
    {
      type: "title",
      title: "基础信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      required: true,
      disabled: true,
      itemWidth: 25,
      data: businessType,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "关联单号",
      required: true,
      disabled: true,
      itemWidth: 30,
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      itemWidth: 100,
      data: warehouseList.value,
      style: {
        width: "53%",
      },
    },
    {
      type: "date",
      itemType: "datetime",
      prop: "deliveryTime",
      label: "预计送达时间",
      itemWidth: 100,
      disabled: false,
      style: {
        width: "53%",
      },
    },
    {
      type: "select",
      prop: "logisticsCompanyCode",
      label: "物流/快递信息",
      placeholder: "物流/快递公司",
      itemWidth: 25,
      style: {
        width: "100%",
      },
      data: logisticsData.value,
      filterable: true,
    },
    {
      type: "input",
      prop: "logisticsCode",
      label: " ",
      placeholder: "物流/快递单号",
      itemWidth: 60,
      style: {
        width: "46%",
      },
    },
    {
      type: "input",
      prop: "contacts",
      label: "收件人",
      itemWidth: 25,
      placeholder: "收件人",
      disabled: true,
    },
    {
      type: "input",
      prop: "phone",
      label: "联系电话",
      itemWidth: 75,
      placeholder: "联系电话",
      disabled: true,
      style: {
        width: "100%",
      },
    },
    // {
    //   type: "slot",
    //   slotName: "countryId",
    //   prop: "countryId",
    //   label: "收货信息",
    //   itemWidth: 33.33,
    //   disabled: true,
    // },
    // {
    //   type: "slot",
    //   slotName: "provinceId",
    //   label: " ",
    //   itemWidth: 33.33,
    //   disabled: true,
    // },
    // {
    //   type: "slot",
    //   slotName: "cityId",
    //   prop: "cityId",
    //   label: " ",
    //   itemWidth: 33.33,
    //   disabled: true,
    // },
    {
      type: "input",
      label: "详细地址",
      itemType: "textarea",
      prop: "areaDetail",
      disabled: true,
    },
    {
      type: "title",
      title: "出库明细",
    },
    {
      type: "slot",
      slotName: "products",
    },
    // {
    //   type: "title",
    //   title: "出库统计",
    // },
    // {
    //   type: "slot",
    //   slotName: "statisticsSlot",
    //   label: "",
    // },
  ],
  [
    {
      type: "title",
      title: "调仓信息",
    },
    {
      type: "select",
      prop: "outWarehouseId",
      label: "调出仓库",
      itemWidth: 33,
      disabled: false,
      data: warehouseList.value,
    },
    {
      type: "select",
      prop: "inWarehouseId",
      label: "调入仓库",
      itemWidth: 33,
      disabled: false,
      data: warehouseList.value,
    },
    {
      type: "input",
      label: "预约号",
      prop: "reservationCode",
      placeholder: "请输入",
      itemWidth: 33,
    },
    {
      type: "input",
      prop: "remark",
      label: "调拨说明",
      itemType: "textarea",
      disabled: false,
    },
    {
      type: "select",
      prop: "logisticsCompanyCode",
      itemWidth: 50,
      label: "物流/快递信息",
      placeholder: "物流/快递公司",
      style: {
        width: "100%",
      },
      data: logisticsData.value,
      filterable: true,
    },
    {
      type: "input",
      prop: "logisticsCode",
      label: " ",
      placeholder: "物流/快递单号",
      itemWidth: 50,
    },
    {
      type: "title",
      title: "调仓明细",
    },
    {
      type: "slot",
      slotName: "products",
    },
  ],
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/stockWait/pageByWdly", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
        quantity: Number(x.quantity) - Number(x.receiptQuantity),
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const openModal = () => {
  dialogVisible.value = true;
  formData.data = {};
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    if (submitType.value == 4) {
      const list = formData.data.jdOrderDetailsList;
      const total = list.reduce((total, x) => (total += Number(x.quantity)), 0);
      if (total > 0) {
        const data = {
          id: formData.data.id,
          businessType: formData.data.businessType,
          warehouseId: formData.data.warehouseId,
          logisticsCompanyCode: formData.data.logisticsCompanyCode,
          logisticsCode: formData.data.logisticsCode,
          countryId: formData.data.countryId,
          provinceId: formData.data.provinceId,
          cityId: formData.data.cityId,
          areaDetail: formData.data.areaDetail,
          stockWaitDetailsList: list.map((x) => ({
            id: x.id,
            quantity: x.quantity,
            productId: x.productId,
          })),
        };
        submitLoading.value = true;
        proxy.post("/purchaseBack/backOuts", data).then(
          (res) => {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            dialogVisible.value = false;
            submitLoading.value = false;
            getList();
          },
          (err) => (submitLoading.value = false)
        );
      } else {
        return ElMessage({
          message: "出库数量不能为0！",
          type: "info",
        });
      }
    } else if (submitType.value == 5) {
      // if (formData.data.inWarehouseId === formData.data.outWarehouseId) {
      //   return ElMessage({
      //     message: "调出和调入仓库不可一致",
      //     type: "info",
      //   });
      // }
      const list = formData.data.jdOrderDetailsList;
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (!(e.quantity > 0)) {
          return ElMessage({
            message: "出库数量不能为0！",
            type: "info",
          });
        }
        if (e.quantity > e.waitQuantity) {
          return ElMessage({
            message: "出库数量不能大于应出库数量！",
            type: "info",
          });
        }
      }
      formData.data.jdOrderDetailsList = formData.data.jdOrderDetailsList.map(
        (x) => ({ ...x, originalNum: x.quantity })
      );
      formData.data.stockWaitDetailsList = formData.data.jdOrderDetailsList.map(
        (x) => ({
          id: x.id,
          businessDetailsId: x.businessDetailsId,
          quantity: x.quantity,
          originalNum: x.originalNum,
          productId: x.productId,
        })
      );
      submitLoading.value = true;
      proxy.post("/stockWait/addByWdly", formData.data).then(
        (res) => {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
    } else if (submitType.value == 6) {
      const list = formData.data.jdOrderDetailsList;
      const total = list.reduce((total, x) => (total += Number(x.quantity)), 0);
      if (total > 0) {
        const data = {
          id: formData.data.id,
          businessId: formData.data.businessId,
          businessType: formData.data.businessType,
          warehouseId: formData.data.warehouseId,
          logisticsCompanyCode: formData.data.logisticsCompanyCode,
          logisticsCode: formData.data.logisticsCode,
          countryId: formData.data.countryId,
          provinceId: formData.data.provinceId,
          cityId: formData.data.cityId,
          areaDetail: formData.data.areaDetail,
          type: "2", //2是出库
          stockWaitDetailsList: list.map((x) => ({
            id: x.id,
            quantity: x.quantity,
            productId: x.productId,
          })),
        };
        submitLoading.value = true;
        proxy.post("/stockWait/addByWdly", data).then(
          (res) => {
            ElMessage({
              message: "操作成功",
              type: "success",
            });
            dialogVisible.value = false;
            submitLoading.value = false;
            getList();
          },
          (err) => (submitLoading.value = false)
        );
      } else {
        return ElMessage({
          message: "出库数量不能为0！",
          type: "info",
        });
      }
    }
  });
};
const submitType = ref("-1");
const outBound = (row) => {
  submitType.value = row.businessType;
  if (row.businessType == 4) {
    formConfig.value = configData.value[0];
    proxy.post("/stockWait/detailByWdly", { id: row.id }).then((res) => {
      res.jdOrderDetailsList = res.stockWaitDetailsList.map((x) => ({
        ...x,
        waitQuantity: x.quantity,
        quantity: null,
      }));
      res.businessType = res.businessType + "";
      if (res.purchaseBackInfo) {
        res.contacts = res.purchaseBackInfo.contacts
          ? res.purchaseBackInfo.contacts
          : "";
        res.phone = res.purchaseBackInfo.phone
          ? res.purchaseBackInfo.phone
          : "";
        res.countryId = res.purchaseBackInfo.countryId
          ? res.purchaseBackInfo.countryId
          : "44";
        res.provinceId = res.purchaseBackInfo.provinceId
          ? res.purchaseBackInfo.provinceId
          : "";
        res.cityId = res.purchaseBackInfo.cityId
          ? res.purchaseBackInfo.cityId
          : "";
        res.areaDetail = res.purchaseBackInfo.detailedAddress
          ? res.purchaseBackInfo.detailedAddress
          : "";
      }
      formData.data = res;
      getCityData(formData.data.countryId, "20");
      if (res.provinceId) {
        getCityData(formData.data.provinceId, "30");
      }
      dialogVisible.value = true;
    });
  } else if (row.businessType == 5) {
    formConfig.value = configData.value[2];
    proxy.post("/jdOrder/detail", { id: row.businessId }).then((res) => {
      // res.jdOrderDetailsList = res.jdOrderDetailsList.map((x) => ({
      //   waitQuantity: x.originalNum,
      //   quantity: null,
      //   productId: x.productId,
      //   id: x.id,
      //   productCustomCode: x.productCustomCode,
      //   productName: x.productName,
      //   productSpec: x.productSpec,
      //   businessDetailsId: x.id,
      // }));
      proxy.post("/stockWait/detailByWdly", { id: row.id }).then((resOne) => {
        let jdOrderDetailsList = resOne.stockWaitDetailsList.map((x) => ({
          ...x,
          waitQuantity: x.quantity,
          quantity: null,
          businessDetailsId: x.id,
          id: x.id,
        }));
        formData.data = {
          id: row.id,
          type: 2,
          warehouseId: "",
          businessId: res.id,
          businessType: row.businessType + "",
          businessCode: row.businessCode,
          contacts: res.receiverName,
          phone: res.warehousePhone,
          areaDetail: res.address,
          jdOrderDetailsList: jdOrderDetailsList,
        };
        dialogVisible.value = true;
      });
    });
  } else if (row.businessType == 6) {
    formConfig.value = configData.value[1];
    proxy.post("/stockWait/detailByWdly", { id: row.id }).then((res) => {
      res.jdOrderDetailsList = res.stockWaitDetailsList.map((x) => ({
        ...x,
        waitQuantity: x.quantity,
        quantity: null,
      }));
      res.businessType = res.businessType + "";
      formData.data = res;
      dialogVisible.value = true;
      proxy
        .post("/orderInfo/detail", {
          id: row.businessId,
        })
        .then((res) => {
          formData.data.countryId = res.countryId ? res.countryId : "44";
          getCityData(formData.data.countryId, "20");
          formData.data.provinceId = res.provinceId ? res.provinceId : "";
          formData.data.cityId = res.cityId ? res.cityId : "";
          formData.data.areaDetail = res.detailedAddress
            ? res.detailedAddress
            : "";
          if (formData.data.provinceId) {
            getCityData(formData.data.provinceId, "30");
          }
        });
    });
  }
};
const warehouseType = ref([]);
const handleRemove = (index) => {
  formData.data.jdOrderDetailsList.splice(index, 1);
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};

getList();

const getDict = () => {
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
  proxy.post("/companyInfo/list", { pageNum: 1, pageSize: 999 }).then((res) => {
    logisticsData.value = res.reverse();
    logisticsData.value = logisticsData.value.map((x) => ({
      label: x.name,
      value: x.code,
    }));
  });
};
getDict();

const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);

const getCityData = (id, type, flag) => {
  proxy.post("/customizeArea/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (flag) {
        formData.data.provinceId = "";
        formData.data.provinceName = "";
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (flag) {
        formData.data.cityId = "";
        formData.data.cityName = "";
      }
    } else {
      countryData.value = res;
    }
  });
};

getCityData("0");

onMounted(() => {
  selectConfig[0].data = businessType;
  selectConfig[1].data = outboundType.value;
});

const statistics = (att) => {
  if (formData.data.jdOrderDetailsList.length > 0) {
    const total = formData.data.jdOrderDetailsList.reduce(
      (val, x) => (val += Number(x[att])),
      0
    );
    if (total) {
      return parseFloat(total).toFixed(2);
    } else {
      return 0;
    }
  }
};

const getSummaries = (param) => {
  const { columns, data } = param; //columns是每列的信息，data是每行的信息
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计"; //此处是在index=0的这一列显示为“合计”
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (
      column.property === "waitQuantity" ||
      column.property === "receiptQuantity" ||
      column.property === "quantity"
    ) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return Number(parseFloat(prev + curr).toFixed(4));
        } else {
          return prev;
        }
      }, 0);
      sums[index];
    }
  });
  return sums;
};

const handleShortcut = () => {
  for (let i = 0; i < formData.data.jdOrderDetailsList.length; i++) {
    const row = formData.data.jdOrderDetailsList[i];
    row.quantity = Number(
      parseFloat(
        Number(row.waitQuantity) - Number(row.receiptQuantity)
      ).toFixed(2)
    );
  }
};

const excelLoading = ref(false);
const openExcel = ref(false);
const downloadTemplate = () => {
  fetch("/static/WaitOutBoundImportTemplate.xlsx")
    .then((res) => res.blob())
    .then((res) => {
      const url = window.URL.createObjectURL(res);
      let filename = "待出库导入模板.xlsx";
      const link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
    });
};
const handleProgress = () => {
  excelLoading.value = true;
};
const handleSuccess = (res) => {
  if (res.code != 200) {
    excelLoading.value = false;
    return ElMessage({
      message: `${res.msg}，请重试！`,
      type: "info",
    });
  } else {
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    if (res && res.data && res.data.length > 0) {
      for (let i = 0; i < formData.data.jdOrderDetailsList.length; i++) {
        const row = formData.data.jdOrderDetailsList[i];
        for (let j = 0; j < res.data.length; j++) {
          const data = res.data[j];
          if (row.productId == data.productId) {
            row.quantity = Number(data.count);
            break;
          }
        }
      }
    }
    openExcel.value = false;
    excelLoading.value = false;
  }
};

const handleError = (err) => {
  ElMessage({
    message: `${err}，请重试！`,
    type: "info",
  });
  openExcel.value = false;
  excelLoading.value = false;
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>