<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: 'Excel导入',
            action: () => openExcel(),
            disabled: false,
          },
        ]"
        @get-list="getList"
      >
        <template #code="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickCode(item)"
          >
            {{ item.code }}
          </div>
        </template>
        <template #address="{ item }">
          <div>
            {{ item.countryName }}, {{ item.provinceName }} ,
            {{ item.cityName }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '京东订单接收' : '调仓接收'"
      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 #distributionCenter>
          <div>
            <el-autocomplete
              v-model="formData.data.distributionCenter"
              :fetch-suggestions="querySearchPerson"
              clearable
              class="inline-input w-50"
              placeholder="请输入"
              :disabled="true"
            >
            </el-autocomplete>
          </div>
        </template>
        <template #countryId>
          <div>
            <el-select
              v-model="formData.data.countryId"
              placeholder="国家"
              @change="(val) => getCityData(val, '20', true)"
            >
              <el-option
                v-for="item in countryData"
                :label="item.chineseName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </template>

        <template #provinceId>
          <div>
            <selectCity
              placeholder="省/洲"
              @change="(val) => getCityData(val, '30', true)"
              addressId="provinceId"
              addressName="provinceName"
              v-model="formData.data"
              :data="provinceData"
            >
            </selectCity>
          </div>
        </template>

        <template #cityId>
          <div>
            <selectCity
              placeholder="城市"
              addressId="cityId"
              addressName="cityName"
              v-model="formData.data"
              :data="cityData"
            >
            </selectCity>
          </div>
        </template>
        <template #products>
          <div style="width: 100%">
            <el-table
              :data="formData.data.stockTransferDetailsList"
              show-summary
              :summary-method="getSummaries"
            >
              <el-table-column prop="productCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="productSpec" label="规格" />
              <el-table-column prop="quantity" label="调仓数量" />
              <el-table-column prop="alQuantity" label="已接收数量" />
              <el-table-column
                prop="inQuantity"
                label="接收数量"
                min-width="150"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'stockTransferDetailsList.' + $index + '.inQuantity'"
                    :rules="rules.inQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.inQuantity"
                      :precision="4"
                      :controls="false"
                      :min="0"
                      onmousewheel="return false;"
                    />
                  </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('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="openDetails"
      title="订单详情"
      width="40%"
      append-to-body
    >
      <OrderDetails
        :orderData="formData.orderData"
        :key="formData.orderData.id"
      ></OrderDetails>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openDetails = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="Excel导入"
      v-model="openExcelDialog"
      width="400"
      v-loading="excelLoading"
    >
      <el-upload
        :action="actionUrl + '/jdOrder/receiveExcelImport'"
        :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">点击导入</el-button>
      </el-upload>
      <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 OrderDetails from "@/components/WDLY/order/details";
import selectCity from "@/components/selectCity/index.vue";
import { getToken } from "@/utils/auth";
import useImportExcelStore from "@/store/modules/importExcel";
const headers = computed(() => useImportExcelStore().requestHeaders);
const actionUrl = import.meta.env.VITE_APP_BASE_API;
const openExcelDialog = ref(false);
const excelLoading = ref(false);

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let openDetails = ref(false);
let modalType = ref("add");
let rules = ref({
  inQuantity: [
    {
      required: true,
      message: "请输入接收数量",
      trigger: "blur",
    },
  ],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "接收状态",
    prop: "inStatus",
    data: [
      {
        label: "未接收",
        value: "0",
      },
      {
        label: "部分接收",
        value: "1",
      },
      {
        label: "已接收",
        value: "2",
      },
    ],
  },
]);

const config = computed(() => {
  return [
    {
      attrs: {
        label: "订单编号",
        prop: "code",
        slot: "code",
      },
    },
    {
      attrs: {
        label: "配送中心",
        prop: "distributionCenter",
      },
    },
    {
      attrs: {
        label: "所在城市",
        prop: "address",
        slot: "address",
        width: "150",
      },
    },
    {
      attrs: {
        label: "详细地址",
        prop: "detailedAddress",
        width: "300",
      },
    },
    {
      attrs: {
        label: "收货负责人",
        prop: "contactPerson",
      },
    },
    {
      attrs: {
        label: "收货电话",
        prop: "contactNumber",
        width: "180",
      },
    },

    {
      attrs: {
        label: "接收人",
        prop: "inUserName",
      },
    },
    {
      attrs: {
        label: "接收时间",
        prop: "inTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "接收状态",
        prop: "inStatus",
      },
      render(inStatus) {
        return inStatus == 0 ? "未接收" : inStatus == 1 ? "部分接收" : "已接收";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.inStatus < 2
            ? {
                attrs: {
                  label: "接收",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
  treeData: [],
  orderData: {},
});
const formOption = reactive({
  disabled: false,
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeData = ref([]);
const formConfig = reactive([
  {
    type: "title",
    title: "订单信息",
  },
  {
    type: "select",
    prop: "customerId",
    label: "客户名称",
    isLoad: {
      url: "/customer/page",
      req: {
        pageNum: 1,
        pageSize: 9999,
      },
      labelKey: "name",
      labelVal: "id",
      method: "post",
      resUrl: "rows",
    },
    itemWidth: 30,
    disabled: true,
  },
  {
    type: "input",
    prop: "code",
    label: "订单编号",
    itemWidth: 20,
    disabled: true,
  },
  {
    type: "slot",
    prop: "distributionCenter",
    label: "配送中心",
    slotName: "distributionCenter",
    disabled: true,
  },
  {
    type: "input",
    prop: "contactPerson",
    label: "收货信息",
    itemWidth: 20,
    placeholder: "收货负责人",
    disabled: true,
  },
  {
    type: "input",
    prop: "contactNumber",
    label: " ",
    itemWidth: 80,
    placeholder: "收货电话",
    disabled: true,
    style: {
      width: "30%",
    },
  },
  {
    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: "detailedAddress",
  },
  {
    type: "title",
    title: "调仓明细",
  },
  {
    type: "slot",
    slotName: "products",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/jdOrder/receivePage", 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 = {
    stockTransferDetailsList: [{}],
    countryId: "44",
  };
  getCityData(formData.data.countryId, "20");
};

const getDtl = (row) => {
  proxy.post("/jdOrder/detail", { id: row.id }).then((res) => {
    getCityData(res.countryId, "20");
    getCityData(res.provinceId, "30");
    proxy
      .post("/stockTransfer/detail", { id: row.stockTransferId })
      .then((resOne) => {
        formData.data = {
          ...res,
          id: row.stockTransferId,
          stockTransferDetailsList: resOne.stockTransferDetailsList.map(
            (x) => ({
              inQuantity: undefined,
              quantity: x.outQuantity,
              alQuantity: x.inQuantity,
              productId: x.productId,
              id: x.id,
              productCode: x.productCode,
              productName: x.productName,
              productSpec: x.productSpec,
            })
          ),
        };
        dialogVisible.value = true;
      });
  });
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.stockTransferDetailsList;
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (!(e.inQuantity > 0)) {
        return ElMessage({
          message: "接收数量不能为0！",
          type: "info",
        });
      }
      if (e.inQuantity + e.alQuantity > e.quantity) {
        return ElMessage({
          message: "接收数量加已接收数量不能大于调仓数量！",
          type: "info",
        });
      }
    }
    submitLoading.value = true;
    const submitData = {
      id: formData.data.id,
      stockTransferDetailsList: formData.data.stockTransferDetailsList,
    };
    proxy.post("/jdOrder/receive", submitData).then(
      (res) => {
        ElMessage({
          message: "接收成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  });
};

const salesType = ref([]);
const getDict = () => {
  proxy.getDictOne(["order_sales_type"]).then((res) => {
    salesType.value = res["order_sales_type"];
    formConfig[1].data = salesType.value.map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
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;
    }
  });
};

const openExcel = () => {
  openExcelDialog.value = true;
};
const handleProgress = () => {
  excelLoading.value = true;
};
const handleSuccess = (res) => {
  if (res.code != 200) {
    return ElMessage({
      message: `${res.msg}，请重试！`,
      type: "info",
    });
  } else {
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    openExcelDialog.value = false;
    excelLoading.value = false;
    getList();
  }
};

const handleError = (err) => {
  ElMessage({
    message: `${err}，请重试！`,
    type: "info",
  });
  openExcelDialog.value = false;
  excelLoading.value = false;
};

getCityData("0");
getList();
getDict();

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

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 === "quantity" ||
      column.property === "alQuantity" ||
      column.property === "inQuantity"
    ) {
      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;
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>