import React from 'react';
import KCModal from '@/components/KCModal';
import KCProSelect from '@/components/KCProSelect';
import { roleManageModelState, Dispatch, useModel } from 'umi';

import { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getHospList, getShareHospList } from '@/service/hospList';
import { AddUsersDataType, getUserRelaSeletData, getYoushuUsers } from '@/service/user';

import { TableActType } from '..';
import { Form } from 'antd';
import MenuEditer from '@/pages/platform/components/menuEditer/menu';
import UserEditer from '@/pages/platform/components/usersEditer';
import { getSysParamsByCode } from '@/service';
import { KcimCenterSysId } from '@/constant';
import { getDictByDictTypeAndSysid } from '@/service/dictionary';

interface ActModalProps extends roleManageModelState {
  dispatch: Dispatch | undefined;
}

export function checkRoleTagsIsObjArr(roleTags: any[]) {
  // 如果数组为空，直接返回 true
  if (roleTags.length === 0) {
    return true;
  }

  // 如果数组非空，则判断第一个元素是否为“非空且非数组的对象”
  if (typeof roleTags[0] === 'object' && roleTags[0] !== null && !Array.isArray(roleTags[0])) {
    return true;
  }

  return false;
}

const ActModal: React.FC<ActModalProps> = ({ dispatch, isShowModal, tableAct, currentEdit, hospId }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  // const temp = {...currentEdit,roleTags:[{labelCode:'001',labelName:'后勤'}]}
  const setInitialValues = () => {
    if (tableAct === TableActType.EDIT) {
      return { ...currentEdit, dataPermission: currentEdit?.dataPermissionCode ?? null, roleTags: currentEdit?.roleTags?.map((a) => a.labelCode) ?? [] };
    }
    if (tableAct === TableActType.ADD) {
      return { hospId: hospId };
    }
    if (tableAct === TableActType.EDITMENU || tableAct === TableActType.EDITRELAUSER) {
      return { ...currentEdit };
    }
  };

  const initialValues = setInitialValues(); // 在表单渲染之前设置初始值

  const onVisibleChangeHandle = (bool: boolean) => {
    if (!bool) {
      dispatch &&
        dispatch({
          type: 'roleManageModel/cancelTableAct',
        });
    }
  };

  const onFinishHandle = (data: any & AddUsersDataType) => {
    try {
      if (tableAct === TableActType.ADD) {
        const { dataPermission, ...rest } = data;
        dispatch &&
          dispatch({
            type: 'roleManageModel/postAddData',
            payload: {
              ...rest,
              dataPermissionCode: data.dataPermission?.value ?? '',
              dataPermissionName: data.dataPermission?.label ?? '',
              roleTags: data.roleTags?.map((a: any) => ({ labelCode: a.value, labelName: a.label })),
            }, // 使用合并后的数据
          });
      }

      if (tableAct === TableActType.EDIT || tableAct === TableActType.EDITMENU || tableAct === TableActType.EDITRELAUSER) {
        const { dataPermission, roleTags, ...rest } = data;
        dispatch &&
          dispatch({
            type: 'roleManageModel/postEditData',
            payload:
              tableAct === TableActType.EDIT
                ? {
                    ...rest,
                    dataPermissionCode: dataPermission && typeof dataPermission == 'string' ? data.dataPermissionCode : dataPermission?.value ?? '',
                    dataPermissionName: dataPermission && typeof dataPermission == 'string' ? data.dataPermissionName : dataPermission?.label ?? '',
                    roleTags: checkRoleTagsIsObjArr(roleTags) ? data.roleTags.map((a: any) => ({ labelCode: a.value, labelName: a.label })) : currentEdit?.roleTags,
                  }
                : {
                    ...rest,
                  },
          });
      }

      return true;
    } catch (error) {
      console.log('add or edit error', error);
    }
  };

  const setModalTitle = () => {
    if (tableAct === TableActType.EDIT) {
      return '编辑角色';
    }
    if (tableAct === TableActType.ADD) {
      return '新增角色';
    }
    if (tableAct === TableActType.EDITMENU) {
      return `绑定菜单(${currentEdit?.roleName})`;
    }
    if (tableAct === TableActType.EDITRELAUSER) {
      return `绑定人员(${currentEdit?.roleName})`;
    }
  };

  return (
    <KCModal
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout="horizontal"
      width={500}
      initialValues={initialValues}
      title={setModalTitle()}
      labelCol={{
        span: 5,
      }}
      onFinish={async (data) => onFinishHandle({ ...currentEdit, ...data })}
    >
      {tableAct === TableActType.EDITMENU && (
        <Form.Item name="bindMenuIds">
          <MenuEditer noAction={true} hospId={currentEdit?.hospId} />
        </Form.Item>
      )}

      {tableAct === TableActType.EDITRELAUSER && (
        <Form.Item name="bindUserIds">
          <UserEditer total={currentEdit ? currentEdit.allUsers : []} noAction={true} />
        </Form.Item>
      )}

      {(tableAct === TableActType.ADD || tableAct === TableActType.EDIT) && (
        <>
          <KCProSelect
            label={initialState?.customerType == '2' ? '选择园区' : '选择院区'}
            width="md"
            name="hospId"
            disabled
            fieldProps={{ size: 'small' }}
            request={async () => {
              const hospList = await getShareHospList();
              if (hospList) {
                return hospList.map((t) => ({
                  label: t.name,
                  value: t.id,
                }));
              }
              return [];
            }}
          />
          <ProFormText
            width="md"
            name="roleName"
            label="角色名称"
            placeholder="请输入"
            rules={[
              {
                required: true,
                message: '请输入角色名称!',
              },
            ]}
          />
          <ProFormText
            width="md"
            name="roleCode"
            label="角色编码"
            placeholder="请输入"
            rules={[
              {
                required: true,
                message: '请输入角色编码!',
              },
            ]}
          />

          <KCProSelect
            label="关联有数账号"
            width="md"
            fieldProps={{ size: 'small' }}
            name="youshuUserId"
            request={async () => {
              const resp = await getYoushuUsers();
              if (resp) {
                return resp.map((t) => ({
                  label: t.name,
                  value: t.id,
                }));
              }
              return [];
            }}
          />
          <KCProSelect
            label="数据权限"
            width="md"
            name="dataPermission"
            fieldProps={{
              size: 'small',
              labelInValue: true,
            }}
            request={async () => {
              // const resp = await getYoushuUsers();
              const resp = await getDictByDictTypeAndSysid(KcimCenterSysId, 'ROLE_DATA_PERMISSIONS_DIC');
              if (resp) {
                return resp.dataVoList.map((t: any) => ({
                  label: t.name,
                  value: t.code,
                }));
              }
              return [];
            }}
          />
          <KCProSelect
            label="角色标签"
            width="md"
            name="roleTags"
            fieldProps={{
              size: 'small',
              labelInValue: true,
              mode: 'tags',
            }}
            request={async () => {
              const resp = await getDictByDictTypeAndSysid(KcimCenterSysId, 'ROLE_LABEL_DIC');
              if (resp) {
                return resp.dataVoList.map((t: any) => ({
                  label: t.name,
                  value: t.code,
                }));
              }
              return [];
            }}
          />

          <ProFormTextArea name="remark" label="备注" placeholder="请输入名称" width="md" fieldProps={{}} />
        </>
      )}
    </KCModal>
  );
};

export default ActModal;
