<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">
      </byTable>
    </div>

    <el-dialog title="手动出库" v-if="dialogVisible" v-model="dialogVisible" width="1000" 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="clickAdd()">添加明细</el-button>
            <el-table :data="formData.data.list" style="width: 100%; margin-top: 16px">
              <el-table-column prop="productCode" label="产品编码" width="140" />
              <el-table-column prop="productName" label="产品名称" min-width="160" />
              <el-table-column label="尺寸 (cm)" min-width="100">
                <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) => dictValueLabel(row.productUnit, productUnit)
                " /> -->
              <el-table-column prop="stockQuantity" label="库存数量" width="100" />
              <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;" />
                    </el-form-item>
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="80" fixed="right">
                <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-model="openProduct" title="选择商品" width="80%" append-to-body destroy-on-close>
      <InventoryInquiry :selectStatus="true" :warehouseId="formData.data.warehouseId" @selectGood="selectGood" :key="formData.data.warehouseId">
      </InventoryInquiry>
    </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 InventoryInquiry from "@/views/purchaseSales/outAndInWarehouse/inventoryInquiry/index";

const { proxy } = getCurrentInstance();
const warehouseList = ref([]);
const outBoundReason = ref([
  {
    label: "生产出库",
    value: "9",
  },
  {
    label: "生产超领",
    value: "1",
  },
  {
    label: "销售出库",
    value: "2",
  },
  {
    label: "借用出库",
    value: "3",
  },
]);

const produceOrder = ref([]);

const productUnit = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    warehouseId: "",
    type: "2",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "仓库名称",
      prop: "warehouseId",
      data: warehouseList.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "仓库名称",
        prop: "warehouseName",
        width: 220,
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
        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.dictValueLabel(unit, productUnit.value);
      },
    },
    {
      attrs: {
        label: "出库数量",
        prop: "quantity",
        width: 140,
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "opUserName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "createTime",
        width: 160,
      },
    },
  ];
});
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,
      }));
    });

  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
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);
    });
};
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: "select",
      prop: "warehouseId",
      label: "仓库名称",
      required: true,
      data: warehouseList.value,
      fn: () => {
        changeWarehouse();
      },
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "exWarehousePerson",
      label: "领料人",
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "type",
      label: "出库原因",
      required: true,
      data: outBoundReason.value,
      fn: (val) => {
        if (["1", "2", "9"].includes(val)) {
          formData.data.expectRestitutionTime = "";
        } else {
          formData.data.prodOrderId = "";
        }
      },
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "prodOrderId",
      label: "生产订单",
      data: produceOrder.value,
      itemWidth: 50,
      isShow: ["1", "2", "9"].includes(formData.data.type),
    },
    // {
    //   type: "select",
    //   prop: "ssdd",
    //   label: "销售订单",
    //   data: outBoundReason.value,
    //   itemWidth: 50,
    //   isShow: formData.data.aa == "3",
    // },
    {
      type: "date",
      itemType: "date",
      prop: "expectRestitutionTime",
      label: "归还日期",
      itemWidth: 50,
      isShow: formData.data.type == "3",
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "remarks",
      label: "备注",
      itemWidth: 100,
    },
    {
      type: "slot",
      slotName: "details",
      label: "出库明细",
    },
  ];
});
const rules = ref({
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  exWarehousePerson: [
    { required: true, message: "请输入领料人", trigger: "blur" },
  ],
  type: [{ required: true, message: "请选择出库原因", trigger: "change" }],
  prodOrderId: [
    { required: true, message: "请选择生产订单", trigger: "change" },
  ],
  expectRestitutionTime: [
    { required: true, message: "请选择归还日期", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入出库数量", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const openModal = () => {
  formData.data = {
    type: "",
    list: [],
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const clickAdd = () => {
  if (formData.data.warehouseId) {
    openProduct.value = true;
  } else {
    ElMessage("请先选择仓库");
  }
};
const changeWarehouse = () => {
  formData.data.list = [];
};
const select = (item) => {
  if (formData.data.list && formData.data.list.length > 0) {
    let data = formData.data.list.filter(
      (row) => row.productId === item.productId
    );
    if (data && data.length > 0) {
      return ElMessage("请勿重复添加");
    }
  }
  formData.data.list.push({
    productCode: item.productCode,
    productId: item.productId,
    productName: item.productName,
    productSpec: item.productSpec,
    productUnit: item.productUnit,
    stockQuantity: item.quantity,
    quantity: undefined,
  });
  ElMessage({
    message: "添加成功！",
    type: "success",
  });
};

const selectGood = (row) => {
  formData.data.list.push({
    productCode: row.productCustomCode,
    productId: row.productId,
    productName: row.productName,
    productLength: row.productLength,
    productWidth: row.productWidth,
    productHeight: row.productHeight,
    stockQuantity: row.quantity,
    quantity: null,
  });
  proxy.msgTip("选择成功");
};

const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.list && formData.data.list.length > 0) {
      for (let i = 0; i < formData.data.list.length; i++) {
        if (
          formData.data.list[i].stockQuantity < formData.data.list[i].quantity
        ) {
          return ElMessage("出库数量不能大于库存数量");
        }
      }
    } else {
      return ElMessage("请添加出库产品");
    }
    loadingDialog.value = true;
    proxy.post("/stock/edit", 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);
};
</script>

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