<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :width="600"
    wrapClassName="custom-modal-box"
    @ok="handleSubmit"
  >
    <div class="modal-top">
      <NodeHead nodeName="选择物料" />
      <a-button type="primary" @click="openModal(true, { shouldVerify: true })">选择物料</a-button>
    </div>
    <BasicForm @register="registerForm" />
    <SelectModal @register="registerSelectModal" @success="handleSuccess" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import SelectModal from './SelectModal.vue';
  import { getMaterialListInfo } from '/@/api/erp/material/list';
  import { getBomInfo, addBomMaterial, updateBomMaterial } from '/@/api/erp/bom/product';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '物料编号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'name',
      label: '物料名称',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'model',
      label: '规格型号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'typeName',
      label: '物料类别',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'unitName',
      label: '单位',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'propertyName',
      label: '物料属性',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
  ];

  const FormCountSchema: FormSchema[] = [
    {
      field: 'count',
      label: '数量',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const parentId = ref('');
  const emit = defineEmits(['success', 'register']);
  const schemas = computed(() => {
    return parentId.value ? [...FormSchema, ...FormCountSchema] : FormSchema;
  });
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas,
    layout: 'vertical',
    rowProps: { gutter: 32 },
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerSelectModal, { openModal }] = useModal();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    parentId.value = data?.parentId;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getBomInfo({ id: data.id });
      setFieldsValue({
        ...record[0],
      });
    }
  });

  const getTitle = computed(() => {
    const first = !unref(isUpdate) ? '新增' : '编辑';
    let last = '';
    if (!unref(isUpdate)) {
      last = !unref(parentId) ? '1级BOM' : '子级物料';
    } else {
      last = !unref(parentId) ? '当前物料信息' : '子级物料信息';
    }
    return first + last;
  });

  const handleSubmit = async () => {
    try {
      const values = await validate();
      if (unref(parentId)) {
        values.parentId = parentId.value;
      }
      setModalProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await addBomMaterial(values);
        notification.success({
          message: '新增物料',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateBomMaterial(values);
        notification.success({
          message: '编辑物料',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };

  const handleSuccess = async (id) => {
    const data = await getMaterialListInfo(id);
    setFieldsValue(data);
  };
</script>
<style lang="less" scoped>
  .modal-top {
    margin: 0 0 10px 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
