import React, {useRef, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Card, message, Modal} from "antd";
import {add, deleteUser, platformUserList, resetPassword, restartUser, stopUser, update} from "@/services/user";
import {useModel} from "@@/plugin-model/useModel";
import {ModalForm, ProFormInstance, ProFormSelect, ProFormText} from '@ant-design/pro-components';
import {ROLE_PLATFORM_ADMIN, ROLE_PLATFORM_USER, ROLE_UNKNOW} from "@/services/constants";

const UserList: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [currentId, setCurrentId] = useState(-1);
    const [showDeleteConfirmDialog, setShowDeleteConfirmDialog] = useState(false);
    const {initialState} = useModel('@@initialState');
    const {currentUser} = initialState;
    const [showAddUserDialog, setShowAddUserDialog] = useState(false);
    const [isEdit, setIsEdit] = useState(false);
    const addUserFormRef = useRef<ProFormInstance>();

    const clickStopUser = (id: number) => {
      stopUser(id).then(data => {
        ref.current?.reload();
      })
    }

    const clickResetPassword = (id: number) => {
      resetPassword(id).then(data => {
        ref.current?.reload();
      })
    }

    const clickEditUser = (id: number) => {
      setIsEdit(true)
      setCurrentId(id)
      setShowAddUserDialog(true)
    }

    const clickDeleteUser = (id: number) => {
      setCurrentId(id)
      setShowDeleteConfirmDialog(true)
    }

    const handleDeleteUser = () => {
      deleteUser(currentId).then(data => {
        setShowDeleteConfirmDialog(false)
        ref.current?.reload();
      })
    }

    const clickRestartUser = (id: number) => {
      restartUser(id).then(data => {
        ref.current?.reload();
      })
    }

    const getUserTypeName = (user: API.UserList) => {
      if (user.roles && user.roles?.indexOf("platform_admin") > -1) {
        return "管理员"
      } else if (user.roles && user.roles?.indexOf("platform_user") > -1) {
        return "普通用户"
      } else {
        return "--"
      }
    }

    const getUserType = (user: API.UserList) => {
      if (user.roles && user.roles?.indexOf("platform_admin") > -1) {
        return ROLE_PLATFORM_ADMIN
      } else if (user.roles && user.roles?.indexOf("platform_user") > -1) {
        return ROLE_PLATFORM_USER
      } else {
        return ROLE_UNKNOW
      }
    }

    const columns: ProColumns<API.UserList>[] = [
      {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
      },
      {
        title: '手机号',
        dataIndex: 'phone',
      },
      {
        title: '姓名',
        dataIndex: 'name',
      },
      {
        title: '用户类型',
        dataIndex: 'roles',
        hideInSearch: true,
        render: (roles, record) => (
          <>
            {getUserTypeName(record)}
          </>
        ),
      },
      {
        title: '注册时间',
        dataIndex: 'createTime',
        hideInSearch: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        hideInSearch: true,
        valueEnum: {
          0: {
            text: '停用',
            status: 'Default'
          },
          1: {
            text: '正常',
            status: 'Success'
          }
        }
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [(
              <a onClick={() => {
                clickEditUser(record.id!)
                setTimeout(() => {
                  addUserFormRef?.current?.setFieldsValue({
                    userId: record.id,
                    phone: record.phone,
                    name: record.name,
                    password: "********",
                    idCard: record.idCard,
                    department: record.department,
                    profession: record.profession,
                    type: getUserType(record)
                  })
                })
              }}>编辑</a>
            ),
              (<a onClick={() => clickResetPassword(record.id!)}>重置密码</a>),
              record.status === 1 ? (<a onClick={() => clickStopUser(record.id!)}>停用</a>) : null,
              record.status === 0 ? (<a onClick={() => clickRestartUser(record.id!)}>启用</a>) : null,
              (<a onClick={() => clickDeleteUser(record.id!)}>删除</a>),
            ]
          );
        }
      },
    ]
    return (
      <div>
        <PageContainer>
          <Modal title="" visible={showDeleteConfirmDialog} onOk={handleDeleteUser}
                 onCancel={() => setShowDeleteConfirmDialog(false)}>
            <p>删除该用户</p>
          </Modal>


          <ModalForm<{
            phone: string;
            name: string;
            permission: string;
            userId: number;
          }>
            formRef={addUserFormRef}
            title={isEdit ? "编辑用户" : "添加用户"}
            visible={showAddUserDialog}
            modalProps={{
              onCancel: () => setShowAddUserDialog(false),
            }}
            onFinish={async (values) => {
              if (values.userId) {
                update({
                  ...values
                }).then(data => {
                  if (data.code == 200) {
                    message.success("设置成功");
                    ref.current?.reload();
                    setShowAddUserDialog(false)
                  } else {
                    message.error(data.message)
                  }
                }).catch(data => {
                  console.log(data)
                })
              } else {
                add({...values, institutionId: currentUser.institutionId}).then(data => {
                  if (data.code == 200) {
                    message.success("添加成功");
                    ref.current?.reload();
                    setShowAddUserDialog(false)
                  } else {
                    message.error(data.message)
                  }
                  addUserFormRef?.current?.resetFields()
                })
              }
            }}
          >
            <ProFormText name="userId" hidden={true}/>
            <ProFormText name="institutionId" hidden={true}/>
            <ProFormText name="phone" label="手机号" required={true} rules={[{required: true}, {
              pattern: /^1\d{10}$/,
              message: ("手机号格式错误！"),
            },]} disabled={isEdit}/>
            <ProFormText.Password name="password" label="密码" required={true}
                                  rules={[{required: true}, {max: 16}, {min: 8}]}
                                  disabled={isEdit}/>
            <ProFormText name="name" label="名字"/>
            <ProFormText name="idCard" label="身份证号" rules={[{max: 18}, {min: 18}]}/>
            <ProFormSelect
              name="type"
              label="用户类型"
              options={[
                {
                  value: ROLE_PLATFORM_ADMIN,
                  label: '管理员',
                },
                {
                  value: ROLE_PLATFORM_USER,
                  label: '普通用户',
                },
              ]}
              rules={[{required: true,}]}
            />

          </ModalForm>

          <Card>
            <ProTable<API.UserList>
              actionRef={ref}
              columns={columns}
              request={async (params = {}, sort, filter) => {
                const response = await platformUserList({
                  name: params.name,
                  phone: params.phone,
                  page: params.current,
                  size: params.pageSize,
                });
                if (response.code === 200) {
                  return {
                    data: response.data!.records,
                    success: true,
                    total: response.data!.total,
                  };
                } else {
                  message.error(response.message)
                  return {}
                }
              }}
              editable={{
                type: 'multiple',
              }}
              rowKey="id"
              search={{
                labelWidth: 'auto',
              }}
              pagination={{
                pageSize: 5,
              }}
              dateFormatter="string"
              headerTitle="用户列表"
              toolBarRender={() => [
                <Button type="primary" key="primary" onClick={() => {
                  addUserFormRef?.current?.resetFields()
                  setShowAddUserDialog(true)
                  setIsEdit(false)
                }}>
                  添加用户
                </Button>,]}
            />
          </Card>
        </PageContainer>
      </div>
    );
  }
;

export default UserList
