import {Button, Divider, Input, message, Modal, Radio} from 'antd';
import React, {useRef, useState} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
import {SorterResult} from 'antd/es/table/interface';
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons/lib";
import {TableListItem} from './data.d';
import service from './service';


/**
 *  删除节点
 * @param fields
 */
const handleRemove = async (fields: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    const res = await service.delete(fields);
    if (res.success) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败，请重试');
    }
    hide();
    return res.success;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    const res = await service.register({...fields});
    hide();
    if (res.success) {
      message.success('添加成功');
      return true;
    }
    message.error('添加失败请重试！');
    return false;

  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在配置');
  try {
    const res = await service.update(fields);
    hide();
    if (res.success) {
      message.success('配置成功');
      return true;
    }
    message.error('配置失败请重试！');
    return false;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};


const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [modelVisible, setModalVisible] = useState<boolean>(false);

  const [formValues, setFormValues] = useState({});
  const actionRef = useRef<ActionType>();

  // 重置表单
  const [resetVisible, setResetVisible] = useState<boolean>(false);
  const [resetLoading, setResetLoading] = useState<boolean>(false);
  const [newPassword, setNewPassword] = useState<string>('');

  const {confirm} = Modal;

  const deleteMemory = async (record: any) => {
    await handleRemove(record);
    if (actionRef.current) {
      actionRef.current.reload();
    }

  };

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 100,
      hideInSearch: false,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 50,
      hideInSearch: true,
      renderFormItem: () => {
        return (
          <Radio.Group>
            <Radio value="0">女</Radio>
            <Radio value='1'>男</Radio>
          </Radio.Group>
        );
      },
      valueEnum: {
        '0': {text: '女'},
        '1': {text: '男'}
      },
    },
    {
      title: '年龄',
      dataIndex: 'age',
      width: 50,
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
    },
    {
      title: '角色',
      dataIndex: 'roleId',
      width: 80,
      renderFormItem: () => {
        return (
          <Radio.Group>
            <Radio value={1}>管理员</Radio>
            <Radio value={2}>普通用户</Radio>
          </Radio.Group>
        );
      },
      valueEnum: {
        1: {text: '管理员'},
        2: {text: '普通用户'}
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: 150,
      valueType: 'option',
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      render: (_, record, index, action) => (
        <>
          <a
            onClick={() => {
              setFormValues(record);
              setModalVisible(true);
            }}
          >
            修改
          </a>
          <Divider type="vertical"/>
          <a
            onClick={async () => {
              confirm({
                title: '确定删除吗?',
                icon: <ExclamationCircleOutlined/>,
                content: '删除后无法恢复',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  deleteMemory(record);
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
          >
            删除
          </a>
          <Divider type="vertical"/>
          <a
            onClick={() => {
              setFormValues(record);
              setResetVisible(true);
            }}
          >
            重置密码
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false}>
      <ProTable<TableListItem>
        // search={false}
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}

        pagination={{
          defaultPageSize: 10,
        }}
        params={{
          sorter,
        }}
        request={async (params = {}) => {
          const res = await service.queryList(params);
          return {
            data: res.data.list,
            page: params.current,
            success: true,
            total: res.data.total,
          };
        }}
        columns={columns}
        rowSelection={{}}
      />

      <Modal
        title="重置密码"
        visible={resetVisible}
        onOk={ async ()=>{
          setResetLoading(true);
          let res = await service.forceUpdatePassword({user_Id: formValues['id'], newPassword: newPassword});
          if (res.success) {
            message.success("修改成功");
            setResetVisible(false);
          } else {
            message.error("修改失败");
          }
          setResetLoading(false);
        }}
        confirmLoading={resetLoading}
        onCancel={()=>{setResetVisible(false)}}
      >
        <Input placeholder="新密码" value={newPassword} onChange={(e)=>setNewPassword(e.target.value)} />
      </Modal>

      <Modal
        destroyOnClose
        title={'id' in formValues ? '编辑' : '新建'}
        visible={modelVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            let success = false;
            if ('id' in formValues) {
              value['id'] = formValues['id']
              success = await handleUpdate(value);
            } else {
              success = await handleAdd(value);
            }
            if (success) {
              setModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
          rowSelection={{}}
          form={{initialValues: formValues}}
        />
      </Modal>

    </PageHeaderWrapper>
  );
};

export default TableList;
