<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 #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 #address>
          <el-row style="width: 100%">
            <el-col :span="8">
              <el-form-item prop="countryId">
                <el-select
                  v-model="formData.data.countryId"
                  placeholder="国家"
                  @change="(val) => getCityData(val, '20', true)"
                  :disabled="true"
                >
                  <el-option
                    v-for="item in countryData"
                    :label="item.chineseName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="provinceId">
                <el-select
                  v-model="formData.data.provinceId"
                  placeholder="省/洲"
                  @change="(val) => getCityData(val, '30', true)"
                  :disabled="true"
                >
                  <el-option
                    v-for="item in provinceData"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="cityId">
                <el-select
                  v-model="formData.data.cityId"
                  placeholder="城市"
                  :disabled="true"
                >
                  <el-option
                    v-for="item in cityData"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px; width: 100%">
            <el-col :span="24">
              <el-form-item prop="detailedAddress">
                <el-input
                  v-model="formData.data.detailedAddress"
                  type="textarea"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template #products>
          <div style="width: 100%">
            <el-table :data="formData.data.stockTransferDetailsList">
              <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"
                    />
                  </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>
  </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";

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({
  // customerId: [
  //   {
  //     required: true,
  //     message: "请选择客户",
  //     trigger: "change",
  //   },
  // ],
  // type: [
  //   {
  //     required: true,
  //     message: "请选择订单类型",
  //     trigger: "change",
  //   },
  // ],
  // countryId: [
  //   {
  //     required: true,
  //     message: "请选择国家",
  //     trigger: "change",
  //   },
  // ],
  // provinceId: [
  //   {
  //     required: true,
  //     message: "请选择省/洲",
  //     trigger: "change",
  //   },
  // ],
  // cityId: [
  //   {
  //     required: true,
  //     message: "请选择城市",
  //     trigger: "change",
  //   },
  // ],
  // code: [
  //   {
  //     required: true,
  //     message: "请输入订单编号",
  //     trigger: "blur",
  //   },
  // ],
  // contactPerson: [
  //   {
  //     required: true,
  //     message: "请输入收货负责人",
  //     trigger: "blur",
  //   },
  // ],
  // contactNumber: [
  //   {
  //     required: true,
  //     message: "请输入收货电话",
  //     trigger: "blur",
  //   },
  // ],
  // detailedAddress: [
  //   {
  //     required: true,
  //     message: "请输入详细地址",
  //     trigger: "blur",
  //   },
  // ],
  // price: [
  //   {
  //     required: true,
  //     message: "请输入单价",
  //     trigger: "blur",
  //   },
  // ],
  inQuantity: [
    {
      required: true,
      message: "请输入接收数量",
      trigger: "blur",
    },
  ],
  // distributionCenter: [
  //   {
  //     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: 30,
    placeholder: "收货电话",
    disabled: true,
  },
  {
    type: "slot",
    slotName: "address",
    prop: "countryId",
    label: "详细地址",
    required: true,
    disabled: true,
  },
  {
    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: "China",
  };
  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 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,
    }));
  });
};
const countryData = ref([]);
const provinceData = ref([]);
const cityData = ref([]);

const getCityData = (id, type, isChange) => {
  proxy.post("/areaInfo/list", { parentId: id }).then((res) => {
    if (type === "20") {
      provinceData.value = res;
      if (isChange) {
        formData.data.provinceId = "";
        formData.data.cityId = "";
      }
    } else if (type === "30") {
      cityData.value = res;
      if (isChange) {
        formData.data.cityId = "";
      }
    } else {
      countryData.value = res;
    }
  });
};
getCityData("0");
getList();
// getDict();

const handleClickCode = (row) => {
  // formData.orderData = row;
  // openDetails.value = true;
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>