<template>
  <div>
    <byTable
      :hidePagination="true"
      :source="formData.data.purchasePendingStorageBomList"
      :config="config"
      :loading="loading"
      highlight-current-row
      :action-list="[
        {
          text: '导入到货单',
          action: () => clickUpload(),
        },
        {
          text: '新增采购入库',
          action: () => clickAdd(),
        },
      ]">
      <template #dimension="{ item }">
        <div>{{ item.bomSpecLength }} * {{ item.bomSpecWidth }} * {{ item.bomSpecHeight }}</div>
      </template>
    </byTable>
    <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="导入到货单" v-if="openUpload" v-model="openUpload" width="600">
      <div v-loading="loadingUpload">
        <el-upload :show-file-list="false" action="##" :http-request="uploadServerLog" :before-upload="handleBeforeUpload">
          <el-button style="background: #20b2aa; color: #fff; border: 1px solid #20b2aa">上传</el-button>
        </el-upload>
        <div style="text-align: center; margin: 10px">
          <el-button @click="openUpload = false" size="large">关 闭</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="新增采购入库" v-if="openAdd" v-model="openAdd" width="80%">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formDataTwo.data" :rules="rules" ref="submit">
        <template #purchaseId>
          <div style="width: 100%">
            <el-select v-model="formDataTwo.data.purchaseId" placeholder="采购合同" @change="changePurchase()">
              <el-option v-for="item in purchaseList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
            </el-select>
          </div>
        </template>
        <template #list>
          <div style="width: 100%">
            <el-table :data="formDataTwo.data.list" :row-style="{ height: '35px' }" header-row-class-name="tableHeader">
              <el-table-column label="品号" prop="bomSpecCode" width="140" />
              <el-table-column label="品名" prop="bomSpecName" min-width="220" />
              <el-table-column label="采购数量" prop="purchaseQuantity" width="100" />
              <el-table-column label="可入库数量" prop="canInStorageQuantity" width="100" />
              <el-table-column label="到货数量" width="120">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'list.' + $index + '.arrivalQuantity'" :rules="rules.arrivalQuantity" :inline-message="true" style="width: 100%">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.arrivalQuantity"
                      placeholder="数量"
                      style="width: 100%"
                      :controls="false"
                      :min="0"
                      :max="row.canInStorageQuantity" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" width="60">
                <template #default="{ $index }">
                  <el-button type="danger" @click="clickDelete($index)" text>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <div style="text-align: center; margin: 10px">
        <el-button @click="openAdd = false" size="large">关 闭</el-button>
        <el-button type="primary" @click="submitAddForm()" size="large" v-preReClick>确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import byForm from "/src/components/byForm/index";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const purchaseList = ref([]);
const formData = reactive({
  data: {
    purchaseId: "",
    arrivalCode: "",
    purchasePendingStorageBomList: [],
  },
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "采购合同",
        prop: "purchaseCode",
        width: 160,
      },
    },
    {
      attrs: {
        label: "仓库",
        prop: "warehouseName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "品号",
        prop: "bomSpecCode",
        width: 140,
      },
    },
    {
      attrs: {
        label: "品名",
        prop: "bomSpecName",
      },
    },
    {
      attrs: {
        label: "单品尺寸",
        slot: "dimension",
        width: 160,
      },
    },
    {
      attrs: {
        label: "到货数量",
        prop: "arrivalQuantity",
        width: 140,
      },
    },
    {
      attrs: {
        label: "操作",
        width: 80,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              formData.data.purchasePendingStorageBomList = formData.data.purchasePendingStorageBomList.filter((item) => {
                return item != row;
              });
            },
          },
        ];
      },
    },
  ];
});
const getDemandData = () => {
  proxy.post("/purchase/getPurchaseSelectList", { pageNum: 1, pageSize: 9999, queryType: 1 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      purchaseList.value = purchaseList.value.concat(
        res.rows.map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.code,
          };
        })
      );
    }
  });
};
getDemandData();
const emit = defineEmits(["clickCancel"]);
const clickCancel = () => {
  emit("clickCancel", false);
};
const submitForm = () => {
  if (formData.data.purchasePendingStorageBomList && formData.data.purchasePendingStorageBomList.length > 0) {
    loading.value = true;
    proxy.post("/purchasePendingStorage/add", formData.data).then(() => {
      ElMessage({ message: "提交成功", type: "success" });
      emit("clickCancel", true);
    });
  } else {
    return ElMessage("请添加入库清单");
  }
};
const openUpload = ref(false);
const loadingUpload = ref(false);
const clickUpload = () => {
  loadingUpload.value = false;
  openUpload.value = true;
};
const handleBeforeUpload = () => {
  loadingUpload.value = true;
};
const uploadServerLog = (params) => {
  let file = params.file;
  let formFile = new FormData();
  formFile.append("file", file);
  proxy.postUploadFile("/purchasePendingStorage/purchaseArrivalImport", formFile).then(
    (res) => {
      ElMessage({ message: "导入成功", type: "success" });
      formData.data = res.data;
      loadingUpload.value = false;
      openUpload.value = false;
    },
    (err) => {
      console.log(err);
      loadingUpload.value = false;
    }
  );
};
const formOption = reactive({
  inline: true,
  labelWidth: "120px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "purchaseId",
      slotName: "purchaseId",
      label: "采购合同",
      itemWidth: 50,
    },
    {
      type: "slot",
      slotName: "list",
      label: "",
    },
  ];
});
const rules = ref({
  purchaseId: [{ required: true, message: "请选择采购合同", trigger: "change" }],
  arrivalQuantity: [{ required: true, message: "请输入数量", trigger: "change" }],
});
const openAdd = ref(false);
const formDataTwo = reactive({
  data: {
    purchaseId: "",
    arrivalCode: "",
    list: [],
  },
});
const submit = ref("");
const clickAdd = () => {
  formDataTwo.data = {
    purchaseId: "",
    arrivalCode: "",
    list: [],
  };
  openAdd.value = true;
};
const changePurchase = () => {
  formDataTwo.data.list = [];
  proxy.post("/purchaseReturn/getPurchaseBomPage", { id: formDataTwo.data.purchaseId }).then((res) => {
    formDataTwo.data.list = res;
  });
};
const clickDelete = (index) => {
  formDataTwo.data.list.splice(index, 1);
};
const submitAddForm = () => {
  submit.value.handleSubmit(() => {
    let list = formDataTwo.data.list.filter((item) => item.arrivalQuantity > 0);
    if (list && list.length > 0) {
      formData.data.purchaseId = formDataTwo.data.purchaseId;
      formData.data.purchasePendingStorageBomList = formDataTwo.data.list;
      ElMessage({ message: "添加成功", type: "success" });
      openAdd.value = "";
    } else {
      return ElMessage("请添加入库清单");
    }
  });
};
</script>

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