<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="800"
      v-loading="submitLoading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="submitType == 5 ? rulesOne : submitType == 4 ? rulesTwo : rules"
        ref="byform"
      >
        <template #countryId>
          <div>
            <el-select
              v-model="formData.data.countryId"
              placeholder="国家"
              @change="(val) => getCityData(val, '20', true)"
              :disabled="submitType == 4"
            >
              <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"
              :disabled="submitType == 4"
            >
            </selectCity>
          </div>
        </template>

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

        <template #products>
          <div style="width: 100%">
            <el-table :data="formData.data.jdOrderDetailsList">
              <el-table-column prop="productCustomCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <!-- <el-table-column
                prop="productSpec"
                label="规格型号"
                v-if="submitType == 5"
              /> -->
              <el-table-column prop="waitQuantity" label="应出库" />
              <el-table-column
                prop="receiptQuantity"
                label="已出库"
                v-if="submitType != 5"
              />
              <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-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>
      </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="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 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"] },
  ],
  warehouseId: [
    { required: true, message: "请选择仓库名称", trigger: "change" },
  ],
  outWarehouseId: [
    { required: true, message: "请选择调出仓库", trigger: "change" },
  ],
  inWarehouseId: [
    { required: true, message: "请选择调入仓库", trigger: "change" },
  ],
  quantity: [{ 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",
      },
      render(type) {
        const current = businessType.find((x) => x.value == type);
        if (current) {
          return current.label;
        }
      },
    },
    {
      attrs: {
        label: "关联单号",
        prop: "businessCode",
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "operatorName",
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "出库状态",
        prop: "status",
      },
      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: 60,
      placeholder: "联系电话",
      disabled: true,
      style: {
        width: "46%",
      },
    },
    {
      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: "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: "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;
  modalType.value = "add";
  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",
          });
        }
      }
      submitLoading.value = true;
      proxy.post("/jdOrder/outbound", 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) {
    modalType.value = "other";
    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: undefined,
      }));
      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) {
    modalType.value = "add";
    formConfig.value = configData.value[2];
    proxy.post("/jdOrder/detail", { id: row.businessId }).then((res) => {
      res.jdOrderDetailsList = res.jdOrderDetailsList.map((x) => ({
        waitQuantity: x.quantity,
        quantity: undefined,
        productId: x.productId,
        id: x.id,
        productCustomCode: x.productCustomCode,
        productName: x.productName,
        productSpec: x.productSpec,
      }));
      formData.data = {
        id: row.businessId,
        outWarehouseId: "",
        inWarehouseId: "",
        jdOrderDetailsList: res.jdOrderDetailsList,
      };
      dialogVisible.value = true;
    });
  } else if (row.businessType == 6) {
    modalType.value = "edit";
    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: undefined,
      }));
      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;
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>