<template>
  <div>
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #materiel>
        <div style="width: 100%">
          <div style="margin-bottom: 10px">
            <el-button type="primary" @click="clickMateriel()" v-preReClick>选择物料</el-button>
          </div>
          <el-table :data="formData.data.applyBuyBomList" :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="bomSpecColour" width="160" />
            <el-table-column label="尺寸（长宽高，cm）" prop="name" width="160">
              <template #default="{ row }">
                <div>{{ row.bomSpecLength }} * {{ row.bomSpecWidth }} * {{ row.bomSpecHeight }}</div>
              </template>
            </el-table-column>
            <el-table-column label="申购数量" width="160">
              <template #default="{ row, $index }">
                <el-form-item :prop="'applyBuyBomList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true" style="width: 100%">
                  <el-input-number
                    onmousewheel="return false;"
                    v-model="row.quantity"
                    placeholder="申购数量"
                    style="width: 100%"
                    :controls="false"
                    :min="0"
                    :precision="0" />
                </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>

    <el-dialog title="选择物料" v-if="openMateriel" v-model="openMateriel" width="90%">
      <SelectBOM :selectStatus="true" @selectBOM="selectMateriel"></SelectBOM>
      <template #footer>
        <el-button @click="openMateriel = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byForm from "/src/components/byForm/index";
import { useRoute } from "vue-router";
import moment from "moment";
import SelectBOM from "/src/views/group/BOM/management/index";
import { ElMessage } from "element-plus";
import subscribeStore from "/src/store/modules/subscribe";

const route = useRoute();
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
const { proxy } = getCurrentInstance();
const formData = reactive({
  data: {
    applyName: proxy.useUserStore().user.nickName,
    applyTime: moment().format("yyyy-MM-DD HH:mm:ss"),
    remark: "",
    applyBuyBomList: [],
  },
});
const judgeStatus = () => {
  if (route.query.processType == 20 || route.query.processType == 10) {
    return true;
  }
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter((item) => item.status === 2 && item.nodeType !== 1);
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const formOption = reactive({
  inline: true,
  labelWidth: "120px",
  itemWidth: 100,
  rules: [],
  labelPosition: "right",
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "申购单",
      label: "",
    },
    {
      type: "input",
      prop: "applyName",
      label: "申购人",
      itemType: "text",
      itemWidth: 51,
    },
    {
      type: "date",
      prop: "applyTime",
      label: "申购时间",
      format: "YYYY-MM-DD HH:mm:ss",
      itemType: "datetime",
      itemWidth: 51,
    },
    {
      type: "input",
      prop: "remark",
      label: "申购说明",
      itemType: "textarea",
      itemWidth: 51,
    },
    {
      type: "title",
      title: "申购清单",
      label: "",
    },
    {
      type: "slot",
      slotName: "materiel",
    },
  ];
});
const rules = ref({
  applyName: [{ required: true, message: "请输入申购人", trigger: "blur" }],
  applyTime: [{ required: true, message: "请选择申购时间", trigger: "change" }],
  quantity: [{ required: true, message: "请输入申购数量", trigger: "blur" }],
});
const openMateriel = ref(false);
const clickMateriel = () => {
  openMateriel.value = true;
};
const selectMateriel = (row) => {
  if (formData.data.applyBuyBomList && formData.data.applyBuyBomList.length > 0) {
    let list = formData.data.applyBuyBomList.filter((item) => item.bomSpecId === row.id);
    if (list && list.length > 0) {
      return ElMessage("请勿重复添加!");
    }
  }
  formData.data.applyBuyBomList.push({
    bomSpecId: row.id,
    bomSpecCode: row.code,
    bomSpecName: row.name,
    bomSpecColour: row.colour,
    bomSpecLength: row.length,
    bomSpecWidth: row.width,
    bomSpecHeight: row.height,
    quantity: undefined,
  });
  ElMessage({ message: "选择完成", type: "success" });
};
const clickDelete = (index) => {
  formData.data.applyBuyBomList.splice(index, 1);
};
const handleSubmit = async (flag) => {
  if (flag) {
    return true;
  } else {
    let status = await proxy.$refs.submit.handleSubmit(() => {});
    if (status) {
      if (!(formData.data.applyBuyBomList && formData.data.applyBuyBomList.length > 0)) {
        ElMessage("请添加物料");
        return false;
      }
      return true;
    } else {
      setTimeout(() => {
        const errorDiv = document.getElementsByClassName("is-error");
        errorDiv[0].scrollIntoView();
      }, 0);
    }
    return false;
  }
};
const getFormData = () => {
  return proxy.deepClone(formData.data);
};
watch(
  () => props.queryData,
  (newValue) => {
    formOption.disabled = judgeStatus();
    if (props.queryData && ["10", "20", "30", "40"].includes(route.query.processType)) {
      formData.data = proxy.deepClone(newValue);
    }
  },
  {
    deep: true,
  }
);
onMounted(() => {
  if (route.query.subscribeStatus) {
    if (subscribeStore().subscribe.list && subscribeStore().subscribe.list.length > 0) {
      formData.data.applyBuyBomList = subscribeStore().subscribe.list.map((item) => {
        return {
          bomSpecId: item.bomSpecId,
          bomSpecCode: item.bomSpecCode,
          bomSpecName: item.bomSpecName,
          bomSpecColour: item.colour,
          bomSpecLength: item.length,
          bomSpecWidth: item.width,
          bomSpecHeight: item.height,
          quantity: undefined,
        };
      });
    }
  }
});
// 向父组件暴露
defineExpose({ getFormData, handleSubmit });
</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>
