import {
  CreatedAccount,
  getRole,
  getUserMessage,
  postDeleteUser,
  postResetUser,
  postEditUser,
  postExcelFile,
  postDowload,
} from '@/services/chatGLM/api';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {
  Button,
  Col,
  Divider,
  Form,
  Input,
  Modal,
  Radio,
  Row,
  Switch,
  message,
  Upload,
  Spin,
} from 'antd';

import classNames from 'classnames';
import { isEmpty } from 'lodash';
import React, { useRef, useState, useEffect } from 'react';
import styles from './index.less';

import { Exclamtion } from '@/components/Icons/Icons';
import { LoadingOutlined } from '@ant-design/icons';
import UserModal from './userModal';

interface IUserResult {
  userName: string;
  role: string;
  state: string;
  phone: string;
  failureReason: string;
}
export interface ICreateUserResult {
  results: IUserResult[];
  failNum: number;
  successNum: number;
}

const { Item } = Form;
const { Password } = Input;
const antIcon = <LoadingOutlined style={{ fontSize: 20 }} spin />;
const Loading: React.FC = () => <Spin indicator={antIcon} />;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};
const resetLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const UserManage = () => {
  const actionRef = useRef<ActionType>();
  const [isModalAccountOpen, setIsModalAccountOpen] = useState(false);
  const [isModalDeleteAccountOpen, setIsModalDeleteAccountOpen] = useState(false);
  const [editMessage, setEditMessage] = useState({
    id: '',
  });
  const [deleteMessage, setDeleteMessage] = useState({
    name: '',
    id: ' ',
  });
  const [isModalResetPassword, setIsModalResetPassword] = useState(false);
  const [resetPassword, setResetPassword] = useState({
    id: '',
  });
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [ressetLoading, setResetLoading] = useState(false);
  const [accountModalName, setAccountModalName] = useState('新建账号');
  const [uploadButtonDisable, setUploadButtonDisable] = useState(false);
  const [accountForm] = Form.useForm();
  const [resetPasswordForm] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [users, setUsers] = useState<ICreateUserResult>();

  useEffect(() => {
    getRole().then((res) => {
      if (!isEmpty(res)) {
        setRoles(res);
      }
    });
  }, []);

  const showModal = () => {
    if (!isEmpty(roles)) {
      setIsModalAccountOpen(true);
    }
  };

  const columns: any[] = [
    {
      title: '用户姓名',
      dataIndex: 'name',
      ellipsis: true,
      width: '20%',
    },
    {
      title: '登录账号',
      dataIndex: 'userName',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '账号状态',
      dataIndex: 'isActive',
      valueType: 'select',
      valueEnum: {
        true: {
          text: '启用',
          status: 'Success',
        },
        false: {
          text: '禁用',
          status: 'Error',
        },
      },
      render(_text, record) {
        return (
          <div className={styles.isActive}>
            <span className={classNames(styles.dot, record.isActive ? styles.green : styles.red)} />
            <div>{record.isActive ? '启用' : '禁用'}</div>
          </div>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'creationTime',
      hideInSearch: true,
      valueType: 'datetime',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: '20%',
      render: (_text, record, _, _action) => (
        <>
          <Button
            size="small"
            type="link"
            key="edit"
            onClick={() => {
              setAccountModalName('编辑账号');
              setEditMessage({ id: record.id });
              const data = {
                id: record.id,
                Name: record.name,
                UserName: record.userName,
                Role: record.roles,
                isActive: record.isActive,
              };
              accountForm.setFieldsValue(data);
              showModal();
            }}
          >
            编辑
          </Button>
          <Button
            size="small"
            type="link"
            onClick={() => {
              setResetPassword({
                id: record.id,
              });
              setIsModalResetPassword(true);
            }}
            key="reset"
          >
            重置
          </Button>
          <Button
            size="small"
            type="link"
            danger
            key="remove"
            onClick={() => {
              setDeleteMessage(record);
              setIsModalDeleteAccountOpen(true);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  const handleOk = () => {
    setIsModalAccountOpen(false);
  };

  const handleModalCancel = () => {
    accountForm.resetFields();
    setIsModalAccountOpen(false);
  };

  const createdAccount = (values: any) => {
    setLoading(true);
    CreatedAccount(values)
      .then(() => {
        setLoading(false);
        setIsModalAccountOpen(false);
        accountForm.resetFields();
        actionRef.current?.reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const editAccountFinish = (values: any) => {
    setLoading(true);
    const data = {
      ...values,
      id: editMessage.id,
    };
    postEditUser(data)
      .then(() => {
        setLoading(false);
        setIsModalAccountOpen(false);
        message.success('编辑成功');
        accountForm.resetFields();
        actionRef.current?.reload();
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const onHandleClickAccountFinish = (values: any) => {
    if (accountModalName === '添加账号') {
      createdAccount(values);
    }
    if (accountModalName === '编辑账号') {
      editAccountFinish(values);
    }
  };

  const validatePhoneNumber = (_, value: any) => {
    const phoneNumberRegex = /^1[3456789]\d{9}$/;
    if (!value || phoneNumberRegex.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('请输入有效的手机号码'));
  };

  const validatePassword = (_, value: any) => {
    const regex =
      /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d!@#$%^&*()_+}{":?><,./;'\[\]\\=-]{8,16}$/;
    if (regex.test(value)) {
      return Promise.resolve();
    }
    return Promise.reject(new Error('密码必须包含数字、大小写字母且长度为8-16位'));
  };

  const handleClickOpenModalDelete = () => {
    postDeleteUser({
      id: deleteMessage.id,
    })
      .then(() => {
        setIsModalDeleteAccountOpen(false);
        actionRef.current?.reload();
        message.success('删除成功');
      })
      .catch(() => {
        setIsModalDeleteAccountOpen(false);
      });
  };

  const handleClickOpenModalReset = (values: any) => {
    setResetLoading(true);
    const data = {
      id: resetPassword.id,
      Password: values?.newPassword,
    };
    postResetUser(data)
      .then(() => {
        setResetLoading(false);
        setIsModalResetPassword(false);
        actionRef.current?.reload();
        resetPasswordForm.resetFields();
        message.success('重置成功');
      })
      .catch(() => {
        setResetLoading(false);
      });
  };

  const handleUpload = (file) => {
    setUploadButtonDisable(true);
    postExcelFile(file).then((data) => {
      setUploadButtonDisable(false);
      setUsers(data);
      setTimeout(() => {
        setIsModalOpen(true);
      }, 100);
    });
  };

  const downloadExcelTemplate = () => {
    postDowload();
  };

  return (
    <PageContainer>
      <Modal
        title="删除账号"
        destroyOnClose={true}
        open={isModalDeleteAccountOpen}
        onOk={handleClickOpenModalDelete}
        onCancel={() => {
          setIsModalDeleteAccountOpen(false);
        }}
      >
        <div className={styles.deleteTitle}>
          <Exclamtion /> 确定要删除 {deleteMessage.name} 的账号吗？
        </div>
        <div className={styles.deleteContent}>
          一旦删除账号，则无法再使用且该账号下所有信息会被清除，请谨慎操作。
        </div>
      </Modal>
      <Modal
        closable={true}
        title="重置密码"
        destroyOnClose={true}
        open={isModalResetPassword}
        onCancel={() => {
          setIsModalResetPassword(false);
        }}
        footer={null}
      >
        <Form
          form={resetPasswordForm}
          {...resetLayout}
          onFinish={handleClickOpenModalReset}
          name="resetPassword"
        >
          <Item
            name={'newPassword'}
            label={'新密码'}
            rules={[{ required: true, message: '请输入密码' }, { validator: validatePassword }]}
          >
            <Password placeholder="请输入6-12位的数字或者字母" />
          </Item>
          <Item
            name={'confirmNewPassword'}
            label={'确认新密码'}
            rules={[
              {
                required: true,
                message: '请确认你的密码',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次密码输入不一致'));
                },
              }),
            ]}
          >
            <Password placeholder="请确认你的新密码" />
          </Item>
          <Divider />
          <Row justify={'center'}>
            <Col>
              <Item key={'saveButton'} noStyle={true}>
                <Button key="submit" type="primary" loading={ressetLoading} htmlType="submit">
                  重置
                </Button>
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      <Modal
        title={`${accountModalName}`}
        open={isModalAccountOpen}
        onOk={handleOk}
        onCancel={handleModalCancel}
        footer={null}
        maskClosable={false}
        destroyOnClose={true}
      >
        <Form
          {...layout}
          form={accountForm}
          onFinish={onHandleClickAccountFinish}
          name="accountSetting"
        >
          {accountModalName === '添加账号' && (
            <>
              <Item
                name={'UserName'}
                label="用户账号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { validator: validatePhoneNumber },
                ]}
              >
                <Input />
              </Item>
              <Item
                name={'Password'}
                label="密码"
                rules={[{ required: true, message: '请输入密码' }, { validator: validatePassword }]}
              >
                <Password />
              </Item>
            </>
          )}
          <Item name={'Role'} label="角色" rules={[{ required: true, message: '请选择你的角色' }]}>
            <Radio.Group>
              {roles.map((item) => {
                return (
                  <Radio key={item} value={`${item}`}>
                    {item}
                  </Radio>
                );
              })}
            </Radio.Group>
          </Item>
          <Item name={'Name'} label="姓名" rules={[{ required: true, message: '请输入你的姓名' }]}>
            <Input placeholder="" />
          </Item>
          <Item label="是否启用" name={'isActive'} valuePropName="checked">
            <Switch checked />
          </Item>
          <Divider />
          <Row justify={'end'} gutter={8}>
            <Col>
              <Item key={'cancelButton'} noStyle={true}>
                <Button key="back" onClick={handleModalCancel}>
                  取消
                </Button>
              </Item>
            </Col>
            <Col>
              <Item key={'saveButton'} noStyle={true}>
                <Button key="submit" type="primary" loading={loading} htmlType="submit">
                  保存
                </Button>
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      <ProTable
        request={async (params = { pageSize: 10, current: 0 }, sort, filter) => {
          console.log(sort, filter, params);
          const defaultParams = {
            Name: !isEmpty(params?.name) ? params?.name : null,
            Enabled: !isEmpty(params?.isActive) ? params?.isActive : null,
            PageSize: params.pageSize,
            PageIndex: params?.current - 1,
          };
          const response = await getUserMessage(defaultParams);
          return {
            data: response.items,
            total: response.totalCount,
            success: !isEmpty(response),
          };
        }}
        actionRef={actionRef}
        columns={columns}
        cardBordered
        rowKey="id"
        pagination={{
          pageSize: 10,
        }}
        options={false}
        headerTitle="账号列表"
        toolBarRender={() => [
          <Button>
            <a href="https://baibaomen.oss-cn-hangzhou.aliyuncs.com/zhensheng/excelTemplate.xlsx">
              批量添加账号Excel模板
            </a>
          </Button>,
          <Upload beforeUpload={handleUpload} disabled={uploadButtonDisable} showUploadList={false}>
            {uploadButtonDisable ? (
              <Button color="white">
                <Loading />
              </Button>
            ) : (
              <div>
                <Button icon={<UploadOutlined />}>Excel表格添加账号</Button>
              </div>
            )}
          </Upload>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setAccountModalName('添加账号');
              showModal();
            }}
            type="primary"
          >
            添加账号
          </Button>,
        ]}
      />
      <UserModal
        isModalOpen={isModalOpen}
        data={users}
        onClose={() => {
          setIsModalOpen(false);
        }}
      ></UserModal>
    </PageContainer>
  );
};

export default UserManage;
