<template>
  <div class="pageIndexClass">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
               highlight-current-row @get-list="getList">

        <template #businessType="{ item }">
          <div style="width: 100%">
            <span :class="item.businessType==4||item.businessType==5?'tag-active':''">
              {{ dictValueLabel(item.businessType, businessType) }}</span>
          </div>
        </template>

        <template #expand="{item}">
          <div style="width:100%;padding:0 50px">
            <el-table :data="item.stockWaitDetailsList" class="bom-table" border>
              <el-table-column label="物品图片" width="100" align="center">
                <template #default="{ row }">
                  <div v-if="row.fileUrl">
                    <img :src="row.fileUrl" class="pic" @click="openImg(row.fileUrl)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productCode" label="物品编码" width="200" />
              <el-table-column prop="productName" label="物品名称" min-width="130" />
              <el-table-column label="尺寸 (cm)" width="140">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    {{row.productLength}} * {{row.productWidth}} * {{row.productHeight}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="需出库数量" prop="quantity" width="100" />
              <el-table-column label="待出库数量" prop="waitQuantity" width="100" />
              <el-table-column label="已出库数量" prop="receiptQuantity" width="100" />
            </el-table>
          </div>
        </template>

      </byTable>
    </div>

    <el-dialog title="出库" v-if="dialogVisible" v-model="dialogVisible" width="1200">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit" v-loading="loadingDialog">
        <template #detail>
          <div style="width:100%">
            <div style="width:100%;padding:0 15px">
              <el-table :data="formData.data.stockWaitDetailsList">
                <el-table-column label="物品图片" width="80">
                  <template #default="{ row }">
                    <div v-if="row.fileUrl">
                      <img :src="row.fileUrl" class="pic" @click="openImg(row.fileUrl)" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="productCode" label="物品编码" width="160" />
                <el-table-column prop="productName" label="物品名称" min-width="130" />
                <el-table-column label="尺寸 (cm)" width="140">
                  <template #default="{ row, $index }">
                    <div style="width: 100%">
                      {{row.productLength}} * {{row.productWidth}} * {{row.productHeight}}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column label="可用库存" prop="availableQuantity" width="100" />
                <el-table-column label="需出库数量" prop="needQuantity" width="100" />
                <el-table-column label="待出库数量" prop="waitQuantity" width="100" />
                <el-table-column label="已出库数量" prop="receiptQuantity" width="100" />
                <el-table-column prop="quantity" label="出库数量" width="130">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="'stockWaitDetailsList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true"
                                  class="margin-b-0">
                      <el-input-number onmousewheel="return false;" v-model="row.quantity" placeholder="请输入" style="width: 100%" :precision="0"
                                       :controls="false" :min="0" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="default">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const warehouseList = ref([]);
const productType = ref([]);
const materialUnitData = computed(
  () => proxy.useUserStore().allDict["material_unit"]
);
const status = ref([
  {
    label: "待出库",
    value: 0,
  },
  {
    label: "部分出库",
    value: 1,
  },
  {
    label: "出库完成",
    value: 2,
  },
]);
const businessType = ref([
  {
    label: "生产打样",
    value: "0",
  },
  {
    label: "生产超领",
    value: "1",
  },
  {
    label: "销售出库",
    value: "2",
  },
  {
    label: "借用出库",
    value: "3",
  },
  {
    label: "报损超领",
    value: "4",
  },
  {
    label: "丢件超领",
    value: "5",
  },
  {
    label: "采购退货",
    value: "6",
  },
  {
    label: "调拨出库",
    value: "7",
  },
  {
    label: "盘亏出库",
    value: "8",
  },
  {
    label: "生产出库",
    value: "9",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    type: 2,
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "业务公司",
      prop: "companyId",
      data: proxy.useUserStore().allDict["list_company_data"],
    },
    {
      label: "出库状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "数据来源",
      prop: "businessType",
      data: businessType.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      type: "expand",
      attrs: {
        slot: "expand",
        width: 50,
        align: "center",
      },
    },
    {
      attrs: {
        label: "业务公司",
        prop: "companyName",
        width: 110,
      },
    },
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
        slot: "businessType",
        // width: 120,
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, businessType.value);
      // },
    },
    {
      attrs: {
        label: "单号",
        prop: "businessCode",
        // width: 160,
      },
    },
    // {
    //   attrs: {
    //     label: "物品类型",
    //     prop: "productType",
    //     width: 120,
    //   },
    //   render(type) {
    //     return proxy.dictValueLabel(type, productType.value);
    //   },
    // },
    // {
    //   attrs: {
    //     label: "图片",
    //     slot: "pic",
    //     align: "center",
    //     width: 80,
    //   },
    // },
    // {
    //   attrs: {
    //     label: "物品编码",
    //     prop: "productCustomCode",
    //     width: 140,
    //   },
    // },
    // {
    //   attrs: {
    //     label: "物品名称",
    //     prop: "productName",
    //     "min-width": 200,
    //   },
    // },
    // {
    //   attrs: {
    //     label: "规格型号",
    //     prop: "productSpec",
    //     width: 140,
    //   },
    // },
    // {
    //   attrs: {
    //     label: "单位",
    //     prop: "productUnit",
    //     width: 120,
    //   },
    //   render(unit) {
    //     return proxy.dictKeyValue(unit, materialUnitData.value);
    //   },
    // },
    // {
    //   attrs: {
    //     label: "待出库数量",
    //     prop: "quantity",
    //     width: 120,
    //   },
    // },
    {
      attrs: {
        label: "出库状态",
        prop: "status",
        // width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, status.value);
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        // width: 160,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "80",
        align: "center",
      },
      renderHTML(row) {
        return [
          row.status !== 2
            ? {
                attrs: {
                  label: "出库",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickOperation(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getDict = () => {
  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,
        };
      });
    }
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/stockWait/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    let productIds = [];
    for (let i = 0; i < res.rows.length; i++) {
      for (let j = 0; j < res.rows[i].stockWaitDetailsList.length; j++) {
        let ele = res.rows[i].stockWaitDetailsList[j];
        ele.waitQuantity = Number(ele.quantity) - Number(ele.receiptQuantity);
        productIds.push(ele.productId);
      }
    }
    if (productIds && productIds.length > 0) {
      proxy
        .getFileData({
          businessIdList: Array.from(new Set(productIds)),
          getAll: true,
        })
        .then((res) => {
          for (let i = 0; i < sourceList.value.data.length; i++) {
            for (
              let j = 0;
              j < sourceList.value.data[i].stockWaitDetailsList.length;
              j++
            ) {
              let ele = sourceList.value.data[i].stockWaitDetailsList[j];
              for (const key in res) {
                if (ele.productId == key && res[key]) {
                  let list = res[key].filter((x) => x.businessType == "0");
                  ele.fileUrl = list && list.length > 0 ? list[0].fileUrl : "";
                  break;
                }
              }
            }
          }
        });
    }
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "待出库信息",
    },
    {
      type: "select",
      prop: "businessType",
      label: "数据来源",
      disabled: true,
      data: businessType.value,
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "businessCode",
      label: "单号",
      itemType: "text",
      disabled: true,
      itemWidth: 50,
    },
    {
      type: "treeSelect",
      prop: "companyId",
      label: "业务公司",
      data: proxy.useUserStore().allDict["tree_company_data"],
      propsTreeLabel: "deptName",
      propsTreeValue: "deptId",
      itemWidth: 50,
      disabled: true,
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      required: true,
      data: warehouseList.value,
      itemWidth: 50,
    },
    {
      type: "upload",
      listType: "text",
      accept: "",
      prop: "fileList",
      label: "上传凭证",
      itemWidth: 100,
      required: true,
    },
    {
      type: "title1",
      title: "出库明细",
    },
    {
      type: "slot",
      slotName: "detail",
      label: "",
    },
  ];
});
const rules = ref({
  companyId: [{ required: true, message: "请选择业务公司", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  quantity: [{ required: true, message: "请输入出库数量", trigger: "blur" }],
  fileList: [
    { required: true, message: "请上传凭证", trigger: ["blur", "change"] },
  ],
});
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (!(formData.data.fileList && formData.data.fileList.length > 0)) {
      return proxy.msgTip("请上传附件", 2);
    }
    for (let i = 0; i < formData.data.stockWaitDetailsList.length; i++) {
      const ele = formData.data.stockWaitDetailsList[i];
      if (Number(ele.quantity) > Number(ele.waitQuantity)) {
        return proxy.msgTip("出库数量不可大于待出库数量", 2);
      }
    }
    loadingDialog.value = true;
    proxy.post("/stockWait/add", formData.data).then(
      () => {
        proxy.msgTip("提交成功", 1);
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        loadingDialog.value = false;
      }
    );
  });
};
const clickOperation = (row) => {
  formData.data = {
    id: row.id,
    companyId: row.companyId,
    businessType: row.businessType + "",
    businessCode: row.businessCode,
    warehouseId: "",
    stockWaitDetailsList: row.stockWaitDetailsList.map((x) => ({
      ...x,
      availableQuantity: x.availableQuantity || 0,
      needQuantity: x.quantity,
      quantity: null,
    })),
    fileList: [],
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.bom-table .el-table__body-wrapper .el-table__body .el-table__row) {
  background: #f4f4f5 !important;
}
</style>
