<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="45%"
    @ok="handleSubmit"
    ><div class="pt-4">
      <BasicForm @register="registerForm">
        <template #user="{ model, field, schema }">
          <SelectUser
            v-model:value="model[field]"
            suffix="ant-design:setting-outlined"
            :placeholder="`请选择${schema.label}`"
            :multiple="field === 'departmentLeaders' || field === 'chargeOfLeaders'"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    addDepartment,
    getDepartmentTree,
    updateDepartment,
    getDepartment,
  } from '/@/api/system/department';
  import { useI18n } from '/@/hooks/web/useI18n';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import { getDicDetailList } from '/@/api/system/dic';

  const deptTypeChange = (e) => {
    if (typeof e !== 'object') return;
    resetSchema(
      e?.target?.value ? [...schema, ...companySchema] : [...schema, ...departmentSchema],
    );
    setFieldsValue({
      departmentNature: undefined,
    });
  };

  const { t } = useI18n();

  const schema: FormSchema[] = [
    {
      title: '基础信息',
      field: 'parentId',
      label: t('上级组织'),
      component: 'TreeSelect',
      componentProps: {
        placeholder: '请选择上级组织',
        fieldNames: {
          label: 'name',
          key: 'id',
          value: 'id',
        },
        getPopupContainer: () => document.body,
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'name',
      label: t('组织名称'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入组织名称',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'code',
      label: t('组织编码'),
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请输入组织编码',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'shortName',
      label: '组织简称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司简称',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'RadioButtonGroup',
      defaultValue: 1,
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('禁用'), value: 0 },
        ],
      },
      required: true,
    },
    {
      field: 'departmentType',
      label: '类别',
      component: 'RadioButtonGroup',
      defaultValue: 1,
      componentProps: {
        options: [
          { label: '公司', value: 1 },
          { label: '部门', value: 0 },
        ],
        onChange: deptTypeChange,
      },
      required: true,
    },
  ];

  const companySchema: FormSchema[] = [
    {
      field: 'departmentNature',
      label: '公司性质',
      component: 'DicSelect',
      colProps: { lg: 12, md: 12 },
      componentProps: {
        placeholder: '请选择公司性质',
        itemId: '1739082093065338882',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'industry',
      label: '所属行业',
      component: 'DicSelect',
      colProps: { lg: 12, md: 12 },
      componentProps: {
        placeholder: '请选择所属行业',
        itemId: '1739822366946906113',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'establishedTime',
      label: '成立时间',
      component: 'DatePicker',
      colProps: { lg: 12, md: 12 },
      componentProps: {
        format: 'YYYY-MM-DD',
        placeholder: '请选择成立时间',
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'mobile',
      label: '公司电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司电话',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'facsimile',
      label: '公司传真',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司传真',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'website',
      label: '公司主页',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司主页',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'address',
      label: '公司地址',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司地址',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'sortCode',
      label: '排序',
      component: 'InputNumber',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入排序',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        placeholder: '请输入备注',
      },
    },
    {
      title: '经营信息',
      field: 'corporateLegalPerson',
      label: '公司法人',
      component: 'Input',
      componentProps: {
        placeholder: '请输入公司法人',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'contactNumber',
      label: '联系电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系电话',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'phoneNumber',
      label: '联系手机',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系手机',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'email',
      label: '联系邮箱',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系邮箱',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'depositBank',
      label: '开户银行',
      component: 'Input',
      componentProps: {
        placeholder: '请输入开户银行',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'bankAccount',
      label: '银行账户',
      component: 'Input',
      componentProps: {
        placeholder: '请输入银行账户',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'businessScope',
      label: '经营范围',
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        placeholder: '请输入经营范围',
      },
    },
  ];
  const departmentSchema: FormSchema[] = [
    {
      field: 'departmentNature',
      label: '部门性质',
      component: 'ApiSelect',
      colProps: { lg: 12, md: 12 },
      componentProps: {
        placeholder: '请选择部门性质',
        api: getDicDetailList,
        labelField: 'name',
        valueField: 'id',
        showSearch: true,
        params: {
          itemId: '1739893799685373953',
        },
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'custodian',
      label: '负责人',
      component: 'Input',
      slot: 'user',
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'mobile',
      label: '电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入电话号码',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'extensionNumber',
      label: '分机号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入分机号',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'facsimile',
      label: '传真',
      component: 'Input',
      componentProps: {
        placeholder: '请输入传真',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'sortCode',
      label: '排序',
      component: 'InputNumber',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入排序',
      },
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'remark',
      label: t('备注'),
      component: 'InputTextArea',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        placeholder: '请输入备注',
      },
    },
    {
      title: '人事信息',
      field: 'administrativeLeader',
      label: '行政正职领导',
      component: 'Input',
      slot: 'user',
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'partyCommitteeLeader',
      label: '党委正职领导',
      component: 'Input',
      slot: 'user',
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'departmentLeaders',
      label: '部门领导',
      component: 'Input',
      slot: 'user',
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'chargeOfLeaders',
      label: '上级分管领导',
      component: 'Input',
      slot: 'user',
      colProps: { lg: 12, md: 12 },
    },
    {
      field: 'departmentLabel',
      label: '部门标签',
      component: 'DicSelect',
      colProps: { lg: 12, md: 12 },
      componentProps: {
        placeholder: '请选择部门标签',
        itemId: '1739082886220808194',
        mode: 'multiple',
        isShowAdd: false,
        getPopupContainer: () => document.body,
      },
    },
  ];

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const { notification } = useMessage();
  const rowId = ref('');

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, resetSchema }] =
    useForm({
      schemas: [...schema, ...companySchema],
      showActionButtonGroup: false,
      baseColProps: { lg: 12, md: 24 },
      layout: 'vertical',
      rowProps: {
        gutter: 32,
      },
    });
  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });
    isUpdate.value = !!data?.isUpdate;

    const treeData = await getDepartmentTree();

    updateSchema({
      field: 'parentId',
      componentProps: { treeData },
    });
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const info = await getDepartment(rowId.value);
      info.departmentLabel = info.departmentLabel?.split(',');
      resetSchema(
        info.departmentType ? [...schema, ...companySchema] : [...schema, ...departmentSchema],
      );
      setFieldsValue({
        ...info,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增组织') : t('编辑组织')));

  async function handleSubmit() {
    try {
      const values = await validate();
      if (values.departmentLabel) {
        values.departmentLabel = values.departmentLabel.toString();
      }
      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addDepartment(values);
        notification.success({
          message: t('提示'),
          description: t('新增成功'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await updateDepartment(values);
        notification.success({
          message: t('提示'),
          description: t('编辑成功'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-modal-body) {
    padding-right: 10px;
  }
</style>
