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, Divider, Input, message, Modal, Space } from 'antd';
import {
  add,
  batchAdd,
  deleteUser,
  institutionUserList,
  resetPassword,
  restartUser,
  stopUser,
  update,
} from '@/services/user';
import { useRequest } from '@@/plugin-request/request';
import { useModel } from '@@/plugin-model/useModel';
import { institutionList } from '@/services/institution';
import {
  ModalForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import {
  ROLE_INSTITUTION_ADMIN,
  ROLE_INSTITUTION_SENIOR_USER,
  ROLE_INSTITUTION_USER,
  USER_TYPE_ADMIN,
  USER_TYPE_INSTITUTION,
  USER_TYPE_OTHER,
  USER_TYPE_PLATFORM,
} from '@/services/constants';
import { addTag, tagList } from '@/services/tag';
import { PlusOutlined } from '@ant-design/icons';

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 [showBatchAddUserDialog, setBatchShowAddUserDialog] = useState(false);
  const [inputDepartment, setInputDepartment] = useState('');
  const [inputProfession, setInputProfession] = useState('');

  const [isEdit, setIsEdit] = useState(false);
  const addUserFormRef = useRef<ProFormInstance>();
  const batchAddUserFormRef = useRef<ProFormInstance>();

  const { data: institutions } = useRequest(
    () => {
      return institutionList({ page: 1, size: 100 }, true);
    },
    { throwOnError: false },
  );

  const clickAddTag = (institutionId?: number, categoryId?: number, name?: string) => {
    if (!name) {
      message.error('不能为空');
      return;
    }

    addTag({
      institutionId: institutionId,
      categoryId: categoryId,
      name: name,
    }).then((data) => {
      if (data.code == 200) {
        if (categoryId == 2) {
          setInputDepartment('');
          addUserFormRef?.current?.setFieldsValue({
            departmentRefresh: new Date().getTime(),
          });
        } else {
          setInputProfession('');
          addUserFormRef?.current?.setFieldsValue({
            professionRefresh: new Date().getTime(),
          });
        }
      }
    });
  };

  const handleInstitutions = (institutions?: API.Institution[]) => {
    if (institutions) {
      const newList: {} = {};
      institutions.forEach((item) => {
        if (item.name) {
          newList[item.id!] = { text: item.name };
        }
      });
      return newList;
    } else {
      return {};
    }
  };

  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('institution_admin') > -1) {
      return '管理员';
    } else if (user.roles && user.roles?.indexOf('institution_senior_user') > -1) {
      return '高级用户';
    } else {
      return '普通用户';
    }
  };

  const getUserType = (user: API.UserList) => {
    if (user.roles && user.roles?.indexOf('institution_admin') > -1) {
      return ROLE_INSTITUTION_ADMIN;
    } else if (user.roles && user.roles?.indexOf('institution_senior_user') > -1) {
      return ROLE_INSTITUTION_SENIOR_USER;
    } else {
      return ROLE_INSTITUTION_USER;
    }
  };

  const columns: ProColumns<API.UserList>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '企业',
      dataIndex: 'institutionName',
      valueType: 'select',
      hideInSearch:
        currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
      hideInTable:
        currentUser?.type == USER_TYPE_INSTITUTION || currentUser?.type == USER_TYPE_OTHER,
      valueEnum: handleInstitutions(institutions?.records),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '部门',
      dataIndex: 'department',
      hideInSearch: true,
    },
    {
      title: '职位',
      dataIndex: 'profession',
      hideInSearch: true,
    },
    {
      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,
                  institutionId: record.institutionId,
                  phone: record.phone,
                  name: record.name,
                  password: '********',
                  idCard: record.idCard,
                  departmentId: record.departmentId,
                  professionId: record.professionId,
                  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<{
          institutionId: number;
          file: File;
        }>
          formRef={batchAddUserFormRef}
          title={'批量添加用户'}
          visible={showBatchAddUserDialog}
          modalProps={{
            onCancel: () => setBatchShowAddUserDialog(false),
          }}
          onValuesChange={(changeValues) => {
            if (changeValues.institutionId) {
              // addUserFormRef?.current?.setFieldsValue(
              //   {
              //     departmentId: '',
              //     professionId: ''
              //   }
              // )
            }
          }}
          onFinish={async (values) => {
            let institutionId = values.institutionId;
            if (currentUser?.type == USER_TYPE_INSTITUTION) {
              institutionId = currentUser?.institutionId;
            }
            const data = await batchAdd({ institutionId, file: values.file[0].originFileObj });
            if (data.code == 200) {
              message.success('总计:' + data.data!.total + ' 失败:' + data.data!.failedCount);
              ref.current?.reload();
              setBatchShowAddUserDialog(false);
            } else {
              message.error(data.message);
            }
            batchAddUserFormRef?.current?.resetFields();
          }}
        >
          {(currentUser?.type == USER_TYPE_PLATFORM || currentUser?.type == USER_TYPE_ADMIN) && (
            <ProFormSelect
              name="institutionId"
              label="企业名称"
              valueEnum={handleInstitutions(institutions?.records)}
              rules={[{ required: true }]}
            />
          )}

          <ProFormUploadButton
            name="file"
            label="文件"
            max={1}
            addonAfter={<a href={'/template/user.xls'}>下载模版</a>}
            rules={[{ required: true }]}
            fieldProps={{
              name: 'file',
            }}
          />
        </ModalForm>

        <ModalForm<{
          institution: number;
          phone: string;
          name: string;
          userId: number;
        }>
          formRef={addUserFormRef}
          title={isEdit ? '编辑用户' : '添加用户'}
          visible={showAddUserDialog}
          modalProps={{
            onCancel: () => setShowAddUserDialog(false),
          }}
          onValuesChange={(changeValues) => {
            if (changeValues.institutionId) {
              addUserFormRef?.current?.setFieldsValue({
                departmentId: null,
                professionId: null,
              });
            }
          }}
          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);
                  }
                  addUserFormRef?.current?.resetFields();
                })
                .catch((data) => {
                  console.log(data);
                });
            } else {
              let institutionId = values.institutionId;
              if (currentUser?.type == USER_TYPE_INSTITUTION) {
                institutionId = currentUser?.institutionId;
              }

              add({ ...values, 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="departmentRefresh" hidden={true} />
          <ProFormText name="professionRefresh" hidden={true} />
          {!isEdit &&
            (currentUser?.type == USER_TYPE_PLATFORM || currentUser?.type == USER_TYPE_ADMIN) && (
              <ProFormSelect
                name="institutionId"
                label="企业名称"
                valueEnum={handleInstitutions(institutions?.records)}
                rules={[{ required: true }]}
              />
            )}

          {isEdit && <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="departmentId"
            label="部门"
            dependencies={['departmentRefresh', 'institutionId']}
            fieldProps={{
              dropdownRender: (menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Input
                      placeholder="请输入部门"
                      value={inputDepartment}
                      onChange={(e) => setInputDepartment(e.target.value)}
                    />
                    <Button
                      type="text"
                      icon={<PlusOutlined />}
                      onClick={() => {
                        let institutionId: number = -1;
                        if (currentUser.type == USER_TYPE_INSTITUTION) {
                          institutionId = currentUser.institutionId;
                        } else if (
                          currentUser.type == USER_TYPE_ADMIN ||
                          currentUser.type == USER_TYPE_PLATFORM
                        ) {
                          institutionId = addUserFormRef?.current?.getFieldValue('institutionId');
                        }
                        clickAddTag(institutionId, 2, inputDepartment);
                      }}
                    >
                      添加部门
                    </Button>
                  </Space>
                </>
              ),
            }}
            request={async (params) => {
              console.log(params);
              let institutionId: number = -1;
              if (currentUser.type == USER_TYPE_INSTITUTION) {
                institutionId = currentUser.institutionId;
              } else if (
                currentUser.type == USER_TYPE_ADMIN ||
                currentUser.type == USER_TYPE_PLATFORM
              ) {
                institutionId = params.institutionId;
              }

              if (institutionId < 0) {
                return [];
              }
              const response = await tagList({
                institutionId: institutionId,
                categoryId: 2,
                page: 1,
                size: 100,
              });
              if (response.code === 200) {
                const newList: { value?: number; label?: string }[] = [];
                response?.data?.records?.forEach((item) => {
                  if (item.name) {
                    newList.push({
                      value: item.id,
                      label: item.name,
                    });
                  }
                });
                return newList;
              } else {
                return [];
              }
            }}
          />

          <ProFormSelect
            name="professionId"
            label="职位"
            dependencies={['professionRefresh', 'institutionId']}
            fieldProps={{
              dropdownRender: (menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Input
                      placeholder="请输入职位"
                      value={inputProfession}
                      onChange={(e) => setInputProfession(e.target.value)}
                    />
                    <Button
                      type="text"
                      icon={<PlusOutlined />}
                      onClick={() => {
                        let institutionId: number = -1;
                        if (currentUser.type == USER_TYPE_INSTITUTION) {
                          institutionId = currentUser.institutionId;
                        } else if (
                          currentUser.type == USER_TYPE_ADMIN ||
                          currentUser.type == USER_TYPE_PLATFORM
                        ) {
                          institutionId = addUserFormRef?.current?.getFieldValue('institutionId');
                        }

                        clickAddTag(institutionId, 3, inputProfession);
                      }}
                    >
                      添加职位
                    </Button>
                  </Space>
                </>
              ),
            }}
            request={async (params) => {
              let institutionId: number = -1;
              if (currentUser.type == USER_TYPE_INSTITUTION) {
                institutionId = currentUser.institutionId;
              } else if (
                currentUser.type == USER_TYPE_ADMIN ||
                currentUser.type == USER_TYPE_PLATFORM
              ) {
                institutionId = params.institutionId;
              }

              if (institutionId < 0) {
                return [];
              }

              const response = await tagList({
                institutionId: institutionId,
                categoryId: 3,
                page: 1,
                size: 100,
              });
              if (response.code === 200) {
                const newList: { value?: number; label?: string }[] = [];
                response?.data?.records?.forEach((item) => {
                  if (item.name) {
                    newList.push({
                      value: item.id,
                      label: item.name,
                    });
                  }
                });
                return newList;
              } else {
                return [];
              }
            }}
          />

          <ProFormSelect
            name="type"
            label="用户类型"
            options={[
              {
                value: ROLE_INSTITUTION_ADMIN,
                label: '管理员',
              },
              {
                value: ROLE_INSTITUTION_SENIOR_USER,
                label: '高级用户',
              },
              {
                value: ROLE_INSTITUTION_USER,
                label: '普通用户',
              },
            ]}
            rules={[{ required: true }]}
          />
        </ModalForm>

        <Card>
          <ProTable<API.UserList>
            actionRef={ref}
            columns={columns}
            request={async (params = {}, sort, filter) => {
              let institutionId = currentUser?.institutionId;
              if (institutionId <= 0) {
                institutionId = params.institutionName;
              }
              const response = await institutionUserList({
                institutionId: institutionId,
                name: params.name,
                phone: params.phone,
                page: params.current,
                size: params.pageSize,
                includeSelf: false,
              });
              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>,
              <Button
                type="primary"
                key="primary"
                onClick={() => {
                  setBatchShowAddUserDialog(true);
                }}
              >
                批量添加
              </Button>,
            ]}
          />
        </Card>
      </PageContainer>
    </div>
  );
};
export default UserList;
