<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :width="1200"
    wrapClassName="custom-modal-box"
  >
    <div class="custom-modal-padding-box">
      <NodeHead nodeName="单据信息" class="title" />
      <BasicForm @register="registerForm">
        <template #user="{ model }">
          <SelectUser
            v-model:value="model.personIds"
            suffix="ant-design:setting-outlined"
            placeholder="请选择经手人员"
          />
        </template>
        <template #relation="{ model }">
          <a-input
            v-model:value="relationKeyName"
            placeholder="请选择关联单据"
            :disabled="isNil(model.type)"
            @click="handleRelationChange"
          >
            <template #suffix>
              <Icon icon="ant-design:ellipsis-outlined" />
            </template>
          </a-input>
        </template>
      </BasicForm>
      <div class="row-title-box">
        <NodeHead nodeName="产品列表" class="title" />
        <a-button type="primary" @click="openModal(true, { type: 'checkbox' })" class="custom-btn">
          +添加
        </a-button>
      </div>
      <BasicTable @register="registerTable">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'count'">
            <a-input-number v-model:value="record.count" />
          </template>
          <template v-if="column.dataIndex == 'action'">
            <TableAction
              :actions="[
                {
                  label: '删除',
                  color: 'error',
                  onClick: handleDelete.bind(null, record),
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
      <SelectModal @register="registerSelectModal" @success="handleSuccess" />
      <RelationModal
        :type="relationType"
        :id="relationKeyId"
        @register="registerRelationModal"
        @success="handleRelationSuccess"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable, BasicColumn, TableAction, FormSchema } from '/@/components/Table';
  import SelectModal from '../../bom/components/SelectModal.vue';
  import RelationModal from './RelationModal.vue';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import {
    getStoreManagementInfo,
    addStoreManagement,
    updateStoreManagement,
  } from '/@/api/erp/store/management';
  import { Icon } from '/@/components/Icon';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isNil } from 'lodash-es';
  import { NodeHead } from '/@/components/ModalPanel/index';
  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '单据编号',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入单据编号',
      },
    },
    {
      field: 'name',
      label: '单据名称',
      component: 'Input',
      required: true,
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入单据名称',
      },
    },
    {
      field: 'type',
      label: '单据类型',
      component: 'Select',
      required: true,
      colProps: { span: 12 },
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请选择单据类型',
          allowClear: false,
          options: [
            { label: '入库单', value: 1 },
            { label: '出库单', value: 0 },
          ],
          onChange: () => {
            formModel.relationKeyId = '';
            relationKeyName.value = '';
          },
        };
      },
    },
    {
      field: 'relationKeyId',
      label: '关联单据',
      component: 'Input',
      slot: 'relation',
      required: true,
      colProps: { span: 12 },
    },
    {
      field: 'personIds',
      label: '经手人员',
      component: 'Input',
      slot: 'user',
      required: true,
      colProps: { span: 12 },
    },
    {
      field: 'remark',
      label: '备注',
      component: 'InputTextArea',
      colProps: { span: 12 },
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '产品编号',
      dataIndex: 'code',
      width: 100,
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      width: 100,
    },
    {
      title: '产品单位',
      dataIndex: 'unitName',
      width: 100,
    },
    {
      title: '数量',
      dataIndex: 'count',
      width: 100,
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const relationType = ref();
  const relationKeyId = ref();

  const relationKeyName = ref('');
  const emit = defineEmits(['success']);

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    schemas: FormSchema,
    layout: 'vertical',
    rowProps: { gutter: 32 },
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerTable, { setTableData, getDataSource }] = useTable({
    title: '产品列表',
    columns,
    striped: false,
    bordered: false,
    pagination: false,
    actionColumn: {
      width: 50,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const [registerSelectModal, { openModal }] = useModal();
  const [registerRelationModal, { openModal: openRelationModal }] = useModal();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getStoreManagementInfo(data.id);
      relationType.value = record.type;
      relationKeyId.value = record.relationKeyId;
      setFieldsValue({
        ...record,
      });
      setTableData(record.caseErpStoreReceiptDetailList || []);
    } else {
      relationType.value = null;
      relationKeyId.value = '';
      relationKeyName.value = '';
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增单据' : '编辑单据'));

  const handleRelationChange = () => {
    openRelationModal(true, {
      type: getFieldsValue().type,
    });
  };

  const handleSuccess = async (data) => {
    data.map((x) => (x.id = ''));
    setTableData([...getDataSource(), ...data]);
  };
  const handleRelationSuccess = async (data) => {
    relationKeyName.value = data.theme;
    setFieldsValue({ relationKeyId: data.id });
  };

  const handleDelete = (record) => {
    const datasource = getDataSource().filter((x) => x.id !== record.id);
    setTableData(datasource);
  };

  const handleSubmit = async () => {
    try {
      const values = await validate();
      values.addCaseErpStoreReceiptDetailDtoList = getDataSource() || [];
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addStoreManagement(values);
        notification.success({
          message: '新增单据',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateStoreManagement(values);
        notification.success({
          message: '编辑单据',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
<style lang="less" scoped>
  .sub-title {
    padding-left: 7px;
    border-left: 8px solid #5e95ff;
    font-size: 16px;
    margin-bottom: 10px;
  }

  .custom-modal-padding-box {
    height: 100%;
    padding: 16px 0;

    .title {
      padding: 0 16px 16px;
    }

    .row-title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .custom-btn {
      width: 82px;
      height: 32px;
      background: #1c8dff;
      border-radius: 4px;
      margin-right: 16px;
      font-weight: 400;
      font-size: 14px;
      color: #fff;
    }
  }
</style>
