<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :width="600"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <div class="modal-top" v-if="!isUpdate">
      <span class="font-bold">选择物料</span>
      <a-button type="primary" @click="openModal">选择物料</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 '../../bom/components/SelectModal.vue';
  import { getMaterialListInfo } from '/@/api/erp/material/list';
  import {
    addSupplyMaterial,
    updateSupplyMaterial,
    getSupplyMaterialInfo,
  } from '/@/api/erp/supplier/material';

  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: 'unitName',
      label: '单位',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        readonly: true,
        placeholder: '',
      },
    },
    {
      field: 'price',
      label: '采购单价(元)',
      subTitle: '其他设置',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入采购单价（元）',
      },
    },
    {
      field: 'state',
      label: '状态',
      component: 'Switch',
      colProps: { span: 24 },
    },
  ];
  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const supplierId = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    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;
    supplierId.value = data?.supplierId;
    setFieldsValue({ state: 1 });
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getSupplyMaterialInfo(data.id);
      setFieldsValue({
        ...record,
      });
    }
  });

  const getTitle = computed(() => {
    return !unref(isUpdate) ? '新增供货清单' : '编辑供货清单';
  });

  const handleSubmit = async () => {
    try {
      const values = await validate();
      values.supplierId = supplierId.value;
      setModalProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await addSupplyMaterial(values);
        notification.success({
          message: '新增供货清单',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateSupplyMaterial(values);
        notification.success({
          message: '编辑供货清单',
          description: t('成功'),
        });
      }

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

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