<template>
  <el-card class="box-card">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #orderId>
        <div style="width: 100%">
          <el-select-v2
            v-model="formData.data.orderId"
            :options="productionOrder"
            placeholder="请选择订单号"
            @change="changeOrder()"
            style="width: 100%"
            filterable />
        </div>
      </template>
      <template #productionExceedReceiveSkuList>
        <div style="width: 100%">
          <el-table :data="formData.data.productionExceedReceiveSkuList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="SKU品号" prop="code" width="160" />
            <el-table-column label="SKU品名" prop="name" min-width="220" />
            <el-table-column label="丢件SKU" width="200">
              <template #default="{ row, $index }">
                <el-button
                  v-if="!row.exceptionSkuSpecId"
                  type="primary"
                  size="small"
                  @click="handleOpen($index)"
                  style="margin: 5px 0; background-color: #43b214; border-color: #43b214">
                  选择SKU
                </el-button>
                <div style="width: 100%; display: flex; align-items: center" v-else>
                  <el-icon style="font-size: 16px; cursor: pointer" @click="clickRemove($index)"><Remove /></el-icon>
                  <span>{{ row.exceptionSkuSpecCode }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="仓库" width="160">
              <template #default="{ row, $index }">
                <el-form-item :prop="'productionExceedReceiveSkuList.' + $index + '.warehouseId'" style="width: 100%">
                  <el-select v-model="row.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
                    <el-option v-for="item in warehouseList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="订单数量" prop="orderQuantity" width="120" />
            <el-table-column label="超领数量" width="160">
              <template #default="{ row, $index }">
                <el-form-item :prop="'productionExceedReceiveSkuList.' + $index + '.quantity'" :inline-message="true" style="width: 100%" @change="queryBOM">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.quantity"
                    placeholder="超领数量"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="0"
                    :max="row.orderQuantity" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #productionExceedReceiveBomList>
        <div style="width: 100%">
          <el-table :data="formData.data.productionExceedReceiveBomList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
            <el-table-column label="BOM品号" prop="bomSpecCode" width="160" />
            <el-table-column label="BOM品名" prop="bomSpecName" min-width="220" />
            <el-table-column label="仓库" prop="warehouseName" width="160" />
            <el-table-column label="库存数量" prop="inventoryQuantity" width="120" />
            <el-table-column label="出库数量" prop="outQuantity" width="120" />
          </el-table>
        </div>
      </template>
    </byForm>
    <div style="text-align: center; margin: 10px">
      <el-button @click="clickCancel()" size="large">重 置</el-button>
      <el-button type="primary" @click="submitForm()" size="large" v-preReClick>提 交</el-button>
    </div>

    <el-dialog title="选择SKU" v-if="openSKU" v-model="openSKU" width="84%">
      <SelectProduct :selectStatus="true" :type="'null'" @selectProduct="selectProduct"></SelectProduct>
      <template #footer>
        <el-button @click="openSKU = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { ElMessage } from "element-plus";
import SelectProduct from "/src/views/group/product/management/index";

const { proxy } = getCurrentInstance();
const productionOrder = ref([]);
const warehouseList = ref([]);
const typeList = ref([
  {
    dictKey: 1,
    dictValue: "制作损坏",
  },
  {
    dictKey: 2,
    dictValue: "裸垫质量不良",
  },
  {
    dictKey: 3,
    dictValue: "生产错误",
  },
  {
    dictKey: 4,
    dictValue: "丢件",
  },
]);
const getDemandData = () => {
  proxy.post("/productionOrder/page", { pageNum: 1, pageSize: 9999, status: "30" }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      productionOrder.value = productionOrder.value.concat(
        res.rows.map((item) => {
          if (item.wlnCode) {
            return {
              value: item.orderId,
              label: item.code + " （" + item.wlnCode + "）",
            };
          } else {
            return {
              value: item.orderId,
              label: item.code,
            };
          }
        })
      );
    }
  });
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows
        .filter((item) => ["1", "5"].includes(item.type))
        .map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.name,
          };
        });
    }
  });
};
getDemandData();
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: "120px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
});
const formData = reactive({
  data: {
    orderId: "",
    type: 4,
    productionExceedReceiveSkuList: [],
    productionExceedReceiveBomList: [],
  },
});
const formConfig = computed(() => {
  return [
    {
      type: "slot",
      label: "订单号",
      slotName: "orderId",
      prop: "orderId",
      itemWidth: 51,
    },
    {
      type: "select",
      label: "超领原因",
      prop: "type",
      data: typeList.value,
      itemWidth: 51,
      disabled: true,
    },
    {
      type: "input",
      label: "责任人",
      prop: "responsible",
      itemWidth: 51,
    },
    {
      type: "slot",
      slotName: "productionExceedReceiveSkuList",
      label: "订单商品",
    },
    {
      type: "slot",
      slotName: "productionExceedReceiveBomList",
      label: "BOM明细",
    },
  ];
});
const rules = ref({
  orderId: [{ required: true, message: "请选择订单号", trigger: "change" }],
  type: [{ required: true, message: "请选择超领原因", trigger: "change" }],
  responsible: [{ required: true, message: "请输入责任人", trigger: "blur" }],
});
const submitForm = () => {
  submit.value.handleSubmit(() => {
    if (formData.data.productionExceedReceiveSkuList && formData.data.productionExceedReceiveSkuList.length > 0) {
      let list = formData.data.productionExceedReceiveSkuList.filter((item) => item.quantity > 0);
      if (list && list.length > 0) {
        proxy.post("/productionExceedReceive/replenishExceedReceive", formData.data).then(() => {
          ElMessage({ message: "操作完成", type: "success" });
          clickCancel();
        });
      } else {
        return ElMessage("请输入超领数量");
      }
    } else {
      return ElMessage("请添加订单商品");
    }
  });
};
const clickCancel = () => {
  formData.data = {
    type: 4,
    productionExceedReceiveSkuList: [],
    productionExceedReceiveBomList: [],
  };
  submit.value.resetFields();
};
const changeOrder = () => {
  if (formData.data.orderId) {
    proxy.post("/productionExceedReceive/getOrderSkuList", { id: formData.data.orderId }).then((res) => {
      if (res && res.length > 0) {
        formData.data.productionExceedReceiveSkuList = res.map((item) => {
          return {
            name: item.name,
            code: item.code,
            orderQuantity: item.quantity,
            orderSkuId: item.id,
            skuSpecId: item.skuSpecId,
            exceptionSkuSpecId: "",
            exceptionSkuSpecCode: "",
            quantity: 0,
            warehouseId: "",
          };
        });
      } else {
        formData.data.productionExceedReceiveSkuList = [];
      }
    });
  } else {
    formData.data.productionExceedReceiveSkuList = [];
  }
  formData.data.productionExceedReceiveBomList = [];
};
const rowIndex = ref(null);
const openSKU = ref(false);
const handleOpen = (index) => {
  rowIndex.value = index;
  openSKU.value = true;
};
const clickRemove = (index) => {
  formData.data.productionExceedReceiveSkuList[index].exceptionSkuSpecId = "";
  formData.data.productionExceedReceiveSkuList[index].exceptionSkuSpecCode = "";
  queryBOM();
};
const selectProduct = (item) => {
  if (item.id) {
    formData.data.productionExceedReceiveSkuList[rowIndex.value].exceptionSkuSpecId = item.id;
    formData.data.productionExceedReceiveSkuList[rowIndex.value].exceptionSkuSpecCode = item.code;
    ElMessage({ message: "选择完成", type: "success" });
    openSKU.value = false;
    queryBOM();
  }
};
const queryBOM = () => {
  let list = formData.data.productionExceedReceiveSkuList.filter((item) => item.quantity > 0 && item.exceptionSkuSpecId);
  if (list && list.length > 0) {
    proxy
      .post("/productionExceedReceive/getSkuSpecMaterialList", {
        skuSpecList: list.map((item) => {
          return {
            skuSpecId: item.exceptionSkuSpecId,
            quantity: item.quantity,
          };
        }),
      })
      .then(
        (res) => {
          formData.data.productionExceedReceiveBomList = res;
        },
        (err) => {
          console.log(err);
          formData.data.productionExceedReceiveBomList = [];
        }
      );
  } else {
    formData.data.productionExceedReceiveBomList = [];
  }
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
</style>
