<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">
            {{ item.businessCode }}
          </div>
        </template>
        <template #logistics="{ item }">
          {{ item.logisticsCompanyName }} (
          <span style="cursor: pointer; color: #409eff"> {{ item.code }} </span>
          )
        </template>
      </byTable>
    </div>
    <el-dialog
      title="入库"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #detail>
          <div style="width: 100%">
            <el-table :data="formData.data.stockWaitDetailsList">
              <el-table-column prop="productCustomCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="purchaseQuantity" label="采购数量" />
              <el-table-column prop="arrivalQuantity" label="本次发货" />
              <el-table-column prop="receiptQuantity" label="已入库" />
              <el-table-column prop="quantity" label="本次入库" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'stockWaitDetailsList.' + $index + '.quantity'"
                    :rules="rules.quantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.quantity"
                      :precision="0"
                      :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>
  </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 { computed, defineComponent, ref } from "vue";
import useUserStore from "@/store/modules/user";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: 1,
  },
});
let dialogVisible = ref(false);
let roomDialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  type: [
    { required: true, message: "请选择仓库类型", trigger: ["blur", "change"] },
  ],
  warehouseId: [
    { required: true, message: "请选择仓库名称", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入入库数量", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "入库状态",
    prop: "status",
    data: [],
  },
]);
const inboundType = ref([
  {
    label: "未入库",
    value: "0",
  },
  {
    label: "部分入库",
    value: "1",
  },
  {
    label: "入库完成",
    value: "2",
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
      },
      render(type) {
        return businessType.find((x) => x.value == type).label;
      },
    },
    {
      attrs: {
        label: "单号",
        prop: "code",
        slot: "code",
      },
    },

    {
      attrs: {
        label: "物流/快递信息",
        prop: "logisticsCompanyName",
        slot: "logistics",
      },
    },
    {
      attrs: {
        label: "仓库名称",
        prop: "receiptWarehouseName",
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "operatorName",
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "入库状态",
        prop: "status",
      },
      render(status) {
        return status == 0 ? "未入库" : status == 1 ? "部分入库" : "入库完成";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "140",
        align: "center",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          row.status < 2
            ? {
                attrs: {
                  label: "入库",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  getDtl(row);
                },
              }
            : {},
          {
            attrs: {
              label: "结束入库",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("您确定结束入库吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                // 删除
                proxy
                  .post("/stockWait/endInStock", {
                    id: row.id,
                  })
                  .then((res) => {
                    ElMessage({
                      message: "操作成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeData = ref([]);
const formConfig = reactive([
  {
    type: "title",
    title: "基础信息",
  },
  {
    type: "select",
    prop: "businessType",
    label: "入库类型",
    required: true,
    disabled: true,
    itemWidth: 100,
    data: [],
  },
  {
    type: "select",
    prop: "warehouseId",
    label: "仓库名称",
    itemWidth: 33,
    isLoad: {
      url: "/warehouse/page",
      req: {
        pageNum: 1,
        pageSize: 9999,
      },
      labelKey: "name",
      labelVal: "id",
      method: "post",
      resUrl: "rows",
    },
  },
  {
    type: "input",
    prop: "code",
    label: "物流信息",
    disabled: true,
    itemWidth: 33,
  },
  {
    type: "slot",
    slotName: "detail",
    label: "入库明细",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/stockWait/pageByWdly", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
      }));
      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) => {
    const list = formData.data.stockWaitDetailsList;
    const total = list.reduce((total, x) => (total += Number(x.quantity)), 0);
    if (!(total > 0)) {
      return ElMessage({
        message: `本次入库不能为0！`,
        type: "info",
      });
    }
    // for (let i = 0; i < list.length; i++) {
    //   const e = list[i];
    //   if (Number(e.receiptQuantity) + e.quantity > Number(e.arrivalQuantity)) {
    //     return ElMessage({
    //       message: "本次入库加已入库数量不可大于发货数量！",
    //       type: "info",
    //     });
    //   }
    // }
    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)
    );
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/stockWait/detailByWdly", { id: row.id }).then((res) => {
    const json = res.victoriatouristJson
      ? JSON.parse(res.victoriatouristJson)
      : {};
    formData.data = {
      id: row.id,
      type: "1",
      businessType: res.businessType + "",
      warehouseId: "",
      code: json.code ? json.code : "",
      stockWaitDetailsList: res.stockWaitDetailsList.map((x) => ({
        ...x,
        arrivalQuantity: x.quantity,
        quantity: undefined,
      })),
    };
    dialogVisible.value = true;
  });
};
const warehouseType = ref([]);
const getDict = () => {
  // // 币种数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: useUserStore().user.tenantId,
      dictCode: "warehouse_type",
    })
    .then((res) => {
      warehouseType.value = res.rows;
    });
};

const businessType = [
  { label: "线边回仓", value: "1" },
  { label: "完工入库", value: "2" },
  { label: "采购到货", value: "3" },
  { label: "退货出库", value: "4" },
];

getList();
getDict();
onMounted(() => {
  selectConfig[0].data = inboundType.value;
  formConfig[1].data = businessType.map((x) => ({
    label: x.label,
    value: x.value,
  }));
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>