<template>
  <div class="pageIndexClass">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
               highlight-current-row :action-list="[
          {
            text: '其他入库',
            action: () => openModal(),
          },
        ]" @get-list="getList">

        <template #pic="{item}">
          <div style="width: 100%">
            <img v-if="item.fileUrl" :src="item.fileUrl" class="pic" @click="openImg(item.fileUrl)" />
          </div>
        </template>

      </byTable>
    </div>

    <el-dialog title="其他入库" v-if="dialogVisible" v-model="dialogVisible" width="1200" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #details>
          <div style="width: 100%">
            <el-button type="primary" @click="openProduct = true" :disabled="['100','103'].includes(formData.data.type)">添加明细</el-button>
            <el-table :data="formData.data.list" style="width: 100%; margin-top: 16px">
              <el-table-column label="图片" width="70" align="center">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <img v-if="row.fileUrl" :src="row.fileUrl" class="pic" @click="handleClickFile(row.fileUrl)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productCode" label="编码" width="160" />
              <el-table-column prop="productName" label="名称" min-width="220" />
              <el-table-column label="尺寸 (cm)" min-width="160">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    {{row.productLength}} * {{row.productWidth}} * {{row.productHeight}}
                  </div>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="productUnit" label="单位" width="100" :formatter="
                  (row) => dictKeyValue(row.productUnit, materialUnitData)
                " /> -->
              <el-table-column label="入库数量" width="140">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    <el-form-item :prop="'list.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true" class="margin-b-0">
                      <el-input-number v-model="row.quantity" placeholder="请输入数量" style="width: 100%" :precision="0" :controls="false" :min="1"
                                       onmousewheel="return false;" :disabled="['100','103'].includes(formData.data.type)" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="80" fixed="right" v-if="!['100','103'].includes(formData.data.type)">
                <template #default="{ row, $index }">
                  <el-button type="primary" link @click="handleDelete($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </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>

    <el-dialog v-if="openProduct" v-model="openProduct" title="物品选择" width="90%" append-to-body>
      <SelectAllGood @selectGood="selectGood"></SelectAllGood>
      <!-- <SelectMaterial @selectMaterial="selectMaterial"></SelectMaterial> -->
    </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";
import SelectAllGood from "@/components/product/SelectAllGood";
// import SelectMaterial from "@/components/product/SelectMaterial.vue";
const { proxy } = getCurrentInstance();
const warehouseList = ref([]);
const warehouseListOne = ref([]);
const materialUnitData = computed(
  () => proxy.useUserStore().allDict["material_unit"]
);
const inBoundReason = ref([
  {
    label: "借用归还",
    value: "100",
  },
  {
    label: "退料入库",
    value: "101",
  },
  {
    label: "废料入库",
    value: "102",
  },
  {
    label: "丢件寻回",
    value: "103",
  },
  {
    label: "超领归还",
    value: "108",
  },
  {
    label: "错领归还",
    value: "109",
  },
  {
    label: "其他入库",
    value: "110",
  },
]);
const produceOrder = ref([]);
const lendData = ref([]);
const lendDataOne = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    warehouseId: "",
    type: "",
    opType: "1",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "业务公司",
      prop: "companyId",
      data: proxy.useUserStore().allDict["list_company_data"],
    },
    {
      label: "仓库名称",
      prop: "warehouseId",
      data: warehouseList.value,
    },
    {
      label: "入库原因",
      prop: "type",
      data: inBoundReason.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "业务公司",
        prop: "companyName",
        width: 110,
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
        width: 160,
        fixed: "left",
      },
    },
    {
      attrs: {
        label: "单号",
        prop: "code",
        width: 120,
        fixed: "left",
      },
    },
    {
      attrs: {
        label: "入库原因",
        prop: "type",
        width: 110,
      },
      render(val) {
        return proxy.dictValueLabel(val, inBoundReason.value);
      },
    },
    {
      attrs: {
        label: "仓库名称",
        prop: "warehouseName",
        width: 150,
      },
    },
    {
      attrs: {
        label: "图片",
        slot: "pic",
        align: "center",
        width: 80,
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCustomCode",
        width: 160,
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
        "min-width": 220,
      },
    },
    // {
    //   attrs: {
    //     label: "规格型号",
    //     prop: "productSpec",
    //     width: 160,
    //   },
    // },
    // {
    //   attrs: {
    //     label: "单位",
    //     prop: "productUnit",
    //     width: 120,
    //   },
    //   render(unit) {
    //     return proxy.dictKeyValue(unit, materialUnitData.value);
    //   },
    // },
    {
      attrs: {
        label: "关联生产订单",
        prop: "prodOrderCode",
        width: 150,
      },
      render(val) {
        if (val) {
          return val;
        }
        return "-";
      },
    },
    {
      attrs: {
        label: "入库数量",
        prop: "quantity",
        width: 140,
      },
    },
    {
      attrs: {
        label: "申请入库人",
        prop: "exWarehousePerson",
        width: 110,
      },
    },
    {
      attrs: {
        label: "备注",
        prop: "remarks",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "opUserName",
        width: 110,
      },
    },
  ];
});
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,
        };
      });
    }
  });

  proxy
    .post("produceOrder/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      produceOrder.value = res.rows.map((x) => ({
        label: x.code,
        value: x.id,
      }));
      produceOrder.value.unshift({
        label: "无",
        value: -1,
      });
    });

  proxy
    .post("/stockJournal/page", {
      pageNum: 1,
      pageSize: 9999,
      isRestitution: 0,
      type: "3",
    })
    .then((res) => {
      lendData.value = res.rows.map((x) => ({
        label:
          x.code +
          " " +
          x.expectRestitutionTime.slice(0, 10) +
          " " +
          x.exWarehousePerson +
          " " +
          x.remarks,
        value: x.id,
      }));
    });

  proxy
    .post("/reportLossesDetails/page", {
      pageNum: 1,
      pageSize: 9999,
      type: "2",
    })
    .then((res) => {
      lendDataOne.value = res.rows.map((x) => ({
        ...x,
        label:
          // x.code +
          // " " +
          x.repoTime.slice(0, 10) + " " + x.respUserName + " 数量" + x.quantity,
        value: x.id,
      }));
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/stockJournalDetails/page", sourceList.value.pagination)
    .then((res) => {
      sourceList.value.data = res.rows;
      sourceList.value.pagination.total = res.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);

      const productIdList = res.rows.map((x) => x.productId);
      // 请求文件数据并回显
      if (productIdList.length > 0) {
        proxy.getFileData({
          businessIdList: productIdList,
          data: sourceList.value.data,
          att: "productId",
          businessType: "0",
          fileAtt: "fileList",
          filePathAtt: "fileUrl",
        });
      }
    });
};
getDict();
getList();
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const openProduct = ref(false);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "基本信息",
    },
    {
      type: "treeSelect",
      prop: "companyId",
      label: "业务公司",
      data: proxy.useUserStore().allDict["tree_company_data"],
      propsTreeLabel: "deptName",
      propsTreeValue: "deptId",
      itemWidth: 50,
      fn: (val) => {
        proxy
          .post("/warehouse/page", {
            pageNum: 1,
            pageSize: 999,
            companyId: val,
          })
          .then((res) => {
            if (res.rows && res.rows.length > 0) {
              warehouseListOne.value = res.rows.map((item) => {
                return {
                  label: item.name,
                  value: item.id,
                };
              });
            }
          });
      },
    },
    {
      type: "select",
      prop: "warehouseId",
      label: "仓库名称",
      required: true,
      data: warehouseListOne.value,
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "exWarehousePerson",
      label: "申请入库人",
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "type",
      label: "入库原因",
      required: true,
      data: inBoundReason.value,
      fn: (val) => {
        formData.data.list = [];
        if (["101", "102", "108", "109", "110"].includes(val)) {
          formData.data.borrowId = "";
          formData.data.loseId = "";
        } else if (val == "103") {
          formData.data.borrowId = "";
          formData.data.prodOrderId = "";
        } else {
          formData.data.loseId = "";
          formData.data.prodOrderId = "";
        }
      },
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "prodOrderId",
      label: "生产订单",
      data: produceOrder.value,
      filterable: true,
      itemWidth: 50,
      isShow: ["101", "102", "108", "109", "110"].includes(formData.data.type),
    },
    {
      type: "select",
      prop: "borrowId",
      label: "借出单",
      data: lendData.value,
      filterable: true,
      itemWidth: 50,
      isShow: formData.data.type == "100",
      fn: (val) => {
        if (val) {
          proxy.post("/stockJournal/detail", { id: val }).then((res) => {
            if (res.list && res.list.length < 1) {
              return;
            }
            let ids = res.list.map((x) => x.productId);
            formData.data.list = res.list.map((x) => ({
              fileUrl: "",
              productCode: x.productCode,
              productId: x.productId,
              productName: x.productName,
              productLength: x.productLength,
              productWidth: x.productWidth,
              productHeight: x.productHeight,
              quantity: x.quantity,
            }));
            proxy.getFileData({
              businessIdList: ids,
              data: formData.data.list,
              att: "productId",
              businessType: "0",
              fileAtt: "fileList",
              filePathAtt: "fileUrl",
            });
          });
        }
      },
    },
    {
      type: "select",
      prop: "loseId",
      label: "丢件单",
      data: lendDataOne.value,
      filterable: true,
      itemWidth: 50,
      isShow: formData.data.type == "103",
      fn: (val) => {
        const current = lendDataOne.value.find((x) => x.value == val);
        if (current && current.materialId) {
          let ids = [current.materialId];
          formData.data.list = [
            {
              fileUrl: "",
              productCode: current.materialCode,
              productId: current.materialId,
              productName: current.materialName,
              productLength: current.materialLength,
              productWidth: current.materialWidth,
              productHeight: current.materialHeight,
              quantity: current.quantity,
            },
          ];
          proxy.getFileData({
            businessIdList: ids,
            data: formData.data.list,
            att: "productId",
            businessType: "0",
            fileAtt: "fileList",
            filePathAtt: "fileUrl",
          });
        }
      },
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "remarks",
      label: "备注",
      itemWidth: 100,
    },
    {
      type: "slot",
      slotName: "details",
      label: "入库明细",
    },
  ];
});
const rules = ref({
  companyId: [{ required: true, message: "请选择业务公司", trigger: "change" }],
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  exWarehousePerson: [
    { required: true, message: "请输入领料人", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择入库原因", trigger: "change" }],
  prodOrderId: [
    { required: true, message: "请选择生产订单", trigger: "change" },
  ],
  borrowId: [
    { required: true, message: "请选择借用出库单", trigger: "change" },
  ],
  loseId: [{ required: true, message: "请选择丢件单", trigger: "change" }],
  quantity: [{ required: true, message: "请输入入库数量", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const openModal = () => {
  getDict();
  formData.data = {
    type: "",
    list: [],
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const pushGoods = (goods) => {
  if (goods && goods.length > 0) {
    let afterFiltering = [];
    if (formData.data.list && formData.data.list.length > 0) {
      afterFiltering = goods.filter((item) => {
        let data = formData.data.list.filter(
          (itemProduct) => itemProduct.productId === item.id
        );
        if (data && data.length > 0) {
          return false;
        }
        return true;
      });
    } else {
      afterFiltering = goods;
    }
    formData.data.list = formData.data.list.concat(
      afterFiltering.map((item) => {
        return {
          productCode: item.code,
          productId: item.id,
          productName: item.name,
          productSpec: item.spec,
          productUnit: item.unit,
          quantity: undefined,
        };
      })
    );
    ElMessage({
      message: "添加成功！",
      type: "success",
    });
    openProduct.value = false;
  } else {
    ElMessage("请选择至少一件产品");
  }
};
const selectMaterial = (row) => {
  let flag = formData.data.list.some((x) => x.productId == row.id);
  if (!flag) {
    formData.data.list.push({
      productCode: row.customCode,
      productId: row.id,
      productName: row.name,
      productSpec: row.spec,
      productUnit: row.unit,
      quantity: null,
    });
    proxy.msgTip("选择成功");
  } else {
    proxy.msgTip("该物料已选择", 2);
  }
};

const selectGood = (row) => {
  let fileUrl = "";
  if (row.fileList && row.fileList.length > 0) {
    fileUrl = row.fileList[0].fileUrl;
  }
  formData.data.list.push({
    fileUrl: fileUrl,
    productCode: row.customCode,
    productId: row.id,
    productName: row.name,
    productLength: row["length"],
    productWidth: row.width,
    productHeight: row.height,
    quantity: null,
  });
  proxy.msgTip("选择成功");
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    proxy.post("/stock/add", formData.data).then(
      () => {
        ElMessage({
          message: "提交成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        loadingDialog.value = false;
      }
    );
  });
};
const handleDelete = (index) => {
  formData.data.list.splice(index, 1);
};
const acquireSelectList = () => {
  let data = [];
  if (formData.data.list && formData.data.list.length > 0) {
    data = formData.data.list.map((item) => {
      return {
        id: item.productId,
        name: item.productName,
      };
    });
  }
  return data;
};

const handleClickFile = (fileUrl) => {
  window.open(fileUrl, "_blank");
};
</script>

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