import { Button, Form, Input, notification, Select } from 'antd';
import { stringify } from 'qs';
import type React from 'react';
import { useImperativeHandle, useState } from 'react';
import ModalPlugin from '@/components/ModalPlugin';
import { statusOptions } from '@/configs/adminConfig';
import { AdminDepartmentServices } from '@/services/AdminDepartmentServices';
import { AdminGroupServices } from '@/services/AdminGroupServices';
import { AdminServices } from '@/services/AdminServices';
import { toArray } from '@/utils/common';
import type { IOption, IRef } from '@/utils/type';
import { useRequest } from '@/utils/useRequest';

interface IProps extends IRef {
  onCallback?: () => void;
}

export type IAdminEditModalType = {
  show: (data?: any) => void;
};

export const AdminEditModal: React.FC<IProps> = (props) => {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const [form] = Form.useForm();
  const [data, setData] = useState<any>(null);
  const [department, setDepartment] = useState<IOption[]>([]);
  const [group, setGroup] = useState<IOption[]>([]);

  const { request: getAdminDepartmentAjaxListRequest } = useRequest(
    AdminDepartmentServices.getAdminDepartmentAjaxList,
    {
      onSuccessCodeZero: (res) => {
        setDepartment(toArray(res.data).map((el) => ({ value: el.department_id, label: el.department_name })));
      },
    },
  );

  const { request: getAdminGroupAjaxListRequest } = useRequest(AdminGroupServices.getAdminGroupAjaxList, {
    onSuccessCodeZero: (res) => {
      setGroup(toArray(res.data).map((el) => ({ value: el.group_id, label: el.name })));
    },
  });

  // 请求成功回调
  const success = (res: any) => {
    if (res.err_code === 0) {
      notification.success({ message: '保存成功' });
      props.onCallback?.();
      setOpen(false);
      form.resetFields(); // 提交成功重置表单
    }
  };

  const { loading: addLoading, request: addRequest } = useRequest(AdminServices.add, { onSuccess: success });
  const { loading: editLoading, request: editRequest } = useRequest(AdminServices.edit, { onSuccess: success });

  const save = async () => {
    try {
      const values = await form.validateFields();
      //values.group_id = values.group_id?.join(',') ?? '';
      // 编辑场景带上主键
      if (data?.admin_id) {
        values.admin_id = data.admin_id;
        editRequest(stringify(values));
      } else {
        addRequest(stringify(values));
      }
    } catch (error) {
      console.log('表单验证未通过', error);
    }
  };

  useImperativeHandle(props.ref, () => ({
    show: async (data?: any) => {
      setTitle(data ? `${data.username} 编辑` : '新增');
      setOpen(true);
      setData(data);

      await getAdminDepartmentAjaxListRequest();
      await getAdminGroupAjaxListRequest();

      if (data) {
        console.log(data.group_id);
        console.log(data.group_id.split(','));
        console.log(data.group_id.split(',').map(Number));

        // 编辑场景初始化表单
        form.setFieldsValue({
          username: data.username,
          mobile: data.mobile,
          email: data.email,
          nickname: data.nickname,
          password: '', // 密码编辑可选
          status: String(data.status),
          department_id: data.department_id,
          group_id: data.group_id ? data.group_id.split(',').map(Number) : [],
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          status: '1',
          group_id: [],
        });
      }
    },
  }));

  return (
    <ModalPlugin
      open={open}
      onCancel={() => setOpen(false)}
      title={title}
      footer={[
        <Button key='cancel' onClick={() => setOpen(false)}>
          取消
        </Button>,
        <Button key='save' type='primary' loading={addLoading || editLoading} onClick={save}>
          保存
        </Button>,
      ]}
    >
      <Form form={form} labelCol={{ style: { width: window?.dfConfig?.language === 'zh-cn' ? 80 : 120 } }}>
        <Form.Item label='岗位角色' name='group_id' required rules={[{ required: true, message: '请选择岗位角色' }]}>
          <Select options={group} mode='multiple' allowClear placeholder='请选择岗位角色' />
        </Form.Item>
        <Form.Item
          label='组织架构'
          name='department_id'
          required
          rules={[{ required: true, message: '请选择组织架构' }]}
        >
          <Select options={department} allowClear placeholder='请选择组织架构' />
        </Form.Item>

        <Form.Item
          label='用户名'
          name='username'
          required
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 2, message: '最少2字符' },
            { max: 20, message: '最多20字符' },
          ]}
        >
          <Input allowClear placeholder='请填写用户名' maxLength={20} showCount />
        </Form.Item>

        <Form.Item
          label='昵称'
          name='nickname'
          required
          rules={[
            { required: true, message: '请输入昵称' },
            { min: 2, message: '最少2字符' },
            { max: 20, message: '最多20字符' },
          ]}
        >
          <Input allowClear placeholder='请填写昵称' maxLength={20} showCount />
        </Form.Item>

        <Form.Item
          label='手机号'
          name='mobile'
          required
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
          ]}
        >
          <Input allowClear placeholder='请填写手机号' maxLength={11} showCount />
        </Form.Item>

        <Form.Item label='邮箱' name='email' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
          <Input allowClear placeholder='请填写邮箱' />
        </Form.Item>

        <Form.Item
          label='密码'
          name='password'
          tooltip={data ? undefined : '不填写则系统自动生成初始密码'}
          //help={<div style={{ marginBottom: 6, fontSize: 12, color: '#999' }}>不填写则系统自动生成初始密码</div>}
          rules={[{ min: 6, max: 18, message: '密码需6~18位' }]}
        >
          <Input.Password allowClear placeholder={data ? '不修改请留空' : '请填写密码'} />
        </Form.Item>

        <Form.Item label={'状态'} name='status'>
          <Select options={statusOptions} placeholder='请选择状态' />
        </Form.Item>
      </Form>
    </ModalPlugin>
  );
};
