<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="loading"
    >
      <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="productCode" 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="2"
                      :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>
  </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: "type",
    data: [],
  },
]);
const inboundType = ref([
  {
    label: "未入库",
    value: "0",
  },
  {
    label: "部分入库",
    value: "1",
  },
  {
    label: "入库完成",
    value: "2",
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
      },
      // render(type) {
      //   return proxy.dictDataEcho(type, warehouseType.value);
      // },
    },
    {
      attrs: {
        label: "单号",
        prop: "code",
      },
    },

    {
      attrs: {
        label: "物流/快递公司",
        prop: "logisticsCompanyName",
      },
    },
    {
      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: "100",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "入库",
              type: "primary",
              text: true,
              disabled: row.status > 1,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
        ];
      },
    },
  ];
});

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: "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.purchaseQuantity)) {
        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 = JSON.parse(res.victoriatouristJson);
    formData.data = {
      type: "1",
      businessType: res.businessType,
      warehouseId: "",
      code: json.code,
      stockWaitDetailsList: res.stockWaitDetailsList.map((x) => ({
        ...x,
        arrivalQuantity: x.quantity,
        quantity: 0,
      })),
    };
    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;
      formConfig[0].data = res.rows.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
};
getList();
getDict();
onMounted(() => {
  selectConfig[0].data = inboundType.value;
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>