<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="rules"
        ref="byform"
      >
        <template #products>
          <div style="width: 100%">
            <!-- <el-button
              type="primary"
              @click="clickAdd()"
              style="margin-bottom: 10px"
              v-if="modalType == 'add'"
            >
              添加物品
            </el-button> -->
            <el-table :data="formData.data.jdOrderDetailsList">
              <el-table-column prop="productCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="productSpec" label="规格型号" />
              <el-table-column prop="waitQuantity" label="待出库数量" />
              <el-table-column prop="quantity" label="调仓数量" min-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"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="inQuantity"
                label="接收数量"
                min-width="150"
                v-if="modalType == 'edit'"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'jdOrderDetailsList.' + $index + '.inQuantity'"
                    :rules="rules.inQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.inQuantity"
                      :precision="2"
                      :controls="false"
                      :min="0"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                prop="zip"
                label="操作"
                width="100"
                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>
        <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";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "2",
  },
});
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" }],
});
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: "productDefinition",
      },
      render(definition) {
        return definition == 1 ? "产品" : definition == 2 ? "物料" : "";
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "型号规格",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
      },
      render(unit) {
        return proxy.dictValueLabel(unit, productUnit.value);
      },
    },
    {
      attrs: {
        label: "待出库",
        prop: "quantity",
      },
    },
    {
      attrs: {
        label: "出库状态",
        prop: "status",
      },
      render(status) {
        return status == 0 ? "未出库" : status == 1 ? "部分出库" : "出库完成";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.status < 2
            ? {
                attrs: {
                  label: "出库",
                  type: "primary",
                  text: true,
                  disabled: row.status > 1,
                },
                el: "button",
                click() {
                  outBound(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
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: "6" },
  { label: "京东订单出库", value: "5" },
];
const configData = [
  [
    {
      type: "title",
      title: "待出库信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      required: true,
      disabled: true,
      itemWidth: 100,
      data: businessType,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "单号",
      required: true,
      disabled: true,
      itemWidth: 100,
    },
    {
      type: "input",
      prop: "productName",
      label: "物品名称",
      required: true,
      disabled: true,
      itemWidth: 100,
    },
    {
      type: "input",
      prop: "waitQuantity",
      label: "待出库数量",
      required: true,
      disabled: true,
      itemWidth: 40,
    },
    {
      type: "title",
      title: "本次出库",
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      itemWidth: 100,
      isLoad: {
        url: "/warehouse/page",
        req: {
          pageNum: 1,
          pageSize: 9999,
        },
        labelKey: "name",
        labelVal: "id",
        method: "post",
        resUrl: "rows",
      },
    },
    {
      type: "number",
      prop: "quantity",
      label: "出库数量",
      disabled: false,
      itemWidth: 33,
      precision: 2,
      min: 0,
      controls: false,
    },
  ],
  [
    {
      type: "title",
      title: "调仓信息",
    },
    {
      type: "select",
      prop: "outWarehouseId",
      label: "调出仓库",
      itemWidth: 33,
      disabled: false,
      data: [],
    },
    {
      type: "select",
      prop: "inWarehouseId",
      label: "调入仓库",
      itemWidth: 33,
      disabled: false,
      data: [],
    },
    {
      type: "input",
      prop: "remark",
      label: "调拨说明",
      itemType: "textarea",
      disabled: false,
    },
    {
      type: "title",
      title: "调仓明细",
    },
    {
      type: "slot",
      slotName: "products",
    },
  ],
];
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/stockWaitDetails/page", 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 (modalType.value === "add") {
      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 (modalType.value === "edit") {
      const data = {
        id: formData.data.id,
        businessType: formData.data.businessType,
        warehouseId: formData.data.warehouseId,
        quantity: formData.data.quantity,
        waitQuantity: formData.data.waitQuantity,
      };
      if (!(data.quantity > 0)) {
        return ElMessage({
          message: "出库数量不能为0！",
          type: "info",
        });
      }
      if (data.quantity > data.waitQuantity) {
        return ElMessage({
          message: "出库数量不能大于待出库数量！",
          type: "info",
        });
      }
      submitLoading.value = true;
      proxy.post("/stockWaitDetails/add", data).then(
        (res) => {
          ElMessage({
            message: "操作成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
    }
  });
};

const outBound = (row) => {
  if (row.businessType == 5) {
    modalType.value = "add";
    formConfig.value = configData[1];
    proxy.post("/jdOrder/detail", { id: row.businessId }).then((res) => {
      formData.data = {
        id: row.businessId,
        outWarehouseId: "",
        inWarehouseId: "",
        jdOrderDetailsList: res.jdOrderDetailsList.map((x) => ({
          waitQuantity: row.quantity,
          quantity: row.quantity,
          productId: x.productId,
          id: x.id,
          productCode: x.productCode,
          productName: x.productName,
          productSpec: x.productSpec,
        })),
      };
      dialogVisible.value = true;
    });
  } else if (row.businessType == 6) {
    modalType.value = "edit";
    formConfig.value = configData[0];
    proxy.post("/orderInfo/detail", { id: row.businessId }).then((res) => {
      formData.data = {
        id: row.id,
        warehouseId: "",
        businessType: row.businessType + "",
        businessCode: row.businessCode,
        productName: row.productName,
        waitQuantity: row.quantity,
        quantity: undefined,
      };
      dialogVisible.value = true;
    });
  }
};
const warehouseType = ref([]);

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

const clickAdd = () => {
  if (formData.data.outWarehouseId) {
    openProduct.value = true;
  } else {
    ElMessage("请先选择仓库");
  }
};

const select = (x) => {
  if (
    formData.data.jdOrderDetailsList &&
    formData.data.jdOrderDetailsList.length > 0
  ) {
    let data = formData.data.jdOrderDetailsList.filter(
      (row) => row.bussinessId === x.productId
    );
    if (data && data.length > 0) {
      return ElMessage("请勿重复添加");
    }
  }
  formData.data.jdOrderDetailsList.push({
    goodType: x.goodType,
    productCode: x.productCode,
    productName: x.productName,
    productSpec: x.productSpec,
    productUnit: x.productUnit,
    count: 0,
    price: 0,
    bussinessId: x.productId,
    amount: 0,
  });
  ElMessage({
    message: "添加成功！",
    type: "success",
  });
};
const warehouseList = ref([]);
const warehouseListData = () => {
  proxy
    .post("/warehouse/page", {
      pageNum: 1,
      pageSize: 999,
    })
    .then((message) => {
      warehouseList.value = message.rows;
      configData[1][1].data = message.rows.map((x) => ({
        label: x.name,
        value: x.id,
      }));
      configData[1][2].data = message.rows.map((x) => ({
        label: x.name,
        value: x.id,
      }));
    });
};
warehouseListData();
getList();
const productUnit = ref([]);
const getDict = () => {
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getDict();
onMounted(() => {
  selectConfig[0].data = businessType;
  selectConfig[1].data = outboundType.value;
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>