import React, { useEffect, useState } from 'react';
import {
  sexTag,
  accountStatusByUser,
  sexOption
} from '@/components/OptionCollect';
import PremissBtn from '@/utils/btnPermissions';
import PremissBtnMore from '@/utils/moreBtnPermissions';
import PageHeader from '@/components/PageHeader';
import CueBubble from '@/components/Popconfirm';
import DeptChange from './component/DeptChange';
import RoleChange from './component/RoleChange';
import SearchTable from '@/components/SearchTable';
import { USER_MANAGE_LIST_DEL, USER_MANAGE_PAGE_GET } from '@/services/Urls';
import type { DataNode } from 'antd/es/tree';
import {
  getDeptTree,
  getRole,
  switchUser,
  userManageAdd,
  userManageEdit,
  resetUserPassword,
  userOwnerDeptChange,
  userOwnerRoleChange,
  userNameSameVerify,
  userEditDetails,
} from '@/services/common/userCenter';
import { PlusOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import type { TreeProps } from 'antd/es/tree';
import {
  Button,
  // Card,
  Empty,
  Col,
  Modal,
  Popconfirm,
  Tooltip,
  Tag,
  Row,
  Space,
  Tree,
  message,
  Switch,
  Affix,
  Input,
  Spin
} from 'antd';
import AddOrEditForm from './component/AddOrEditForm';
import './style.less';
import { smallPopup } from '@/utils/constant';
type TableListItem = {
  [key: string]: any;
};
const { DirectoryTree } = Tree;
const UserManage: React.FC = () => {
  const t = useIntl();
  //备份页（无部门项）
  const currentPath = window.location.pathname;
  const backupPage = currentPath?.includes('userOrganization');
  const userAccessBtn = backupPage ? 'userOrganization' : 'userManage';
  //
  const [submitDept, setSubmitDept] = useState<number>(0);
  const [submitRole, setSubmitRole] = useState<number>(0);
  const [roleOptionData, setRoleOptionData] = useState<any>([]);
  const [addOrEdit, setAddOrEdit] = useState<string>('add');
  const [onFormSubmit, setOnFormSubmit] = useState<number>(0);
  const [reloadNum, setReloadNum] = useState<number>(0);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [editDataInitValue, setEditDataInitValue] = useState<TableListItem>({});
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [listId, setListId] = useState<number>();
  const [listDetails, setListDetails] = useState<any>();
  const [treeCheckedId, setTreeCheckedId] = useState<any>();
  const [containDeptChild, setContainDeptChild] = useState<any>(0);
  const [deptName, setDeptName] = useState<any>();
  const [modalDeptVisible, setModalDeptVisible] = useState<boolean>(false);
  const [modalRoleVisible, setModalRoleVisible] = useState<boolean>(false);
  const [disableEnable, setDisableEnable] = useState<any>();
  const [deptTreeData, setDeptTreeData] = useState<any>([]);
  const [searchParams, setSearchParams] = useState<any>({});
  const [treeSpinLoading, setTreeSpinLoading] = useState<boolean>(false);
  //部门查询开关
  //（开-查询所有部门/关-查询当前部门）
  const onSwitchChange = (checked: boolean) => {
    if (checked) {
      setContainDeptChild(0);
      setReloadNum(reloadNum + 1);
    } else {
      setContainDeptChild(1);
      setReloadNum(reloadNum + 1);
    }
  };

  // 将tree数据递归重赋
  const convertTreeData = (treeData: any) => {
    return treeData.map((node: any) => {
      const { deptName, deptId, ...rest } = node;
      return {
        title: deptName,
        key: deptId,
        ...rest,
        children: node.children ? convertTreeData(node.children) : null,
      };
    });
  };

  // 获取部门信息
  const requestCompanyOption: any = async () => {
    setTreeSpinLoading(true);
    const res = await getDeptTree();
    if (res.code === '0000') {
      const data = convertTreeData(res.data);
      setTreeData(data);
      setDeptTreeData(res.data); 
    }
    setTreeSpinLoading(false);
  };

  //更改部门
  const changeDeptFunc = (data: any) => {
    userOwnerDeptChange([{ userId: listId, deptId: data?.deptId }]).then(() => {
      setModalDeptVisible(false);
      setReloadNum(reloadNum + 1);
      setSubmitDept(0);
    });
  };

  // 更改角色
  const onChangeRole = (value: any) => {
    userOwnerRoleChange({ userId: listId, roleIds: value?.roleIds }).then(() => {
      setModalRoleVisible(false);
      setReloadNum(reloadNum + 1);
      setSubmitRole(0);
    });
  };

  // 获取详情数据
  const getDetailsMsg = async (id: number | string) => {
    const res = await userEditDetails({ userId: id });
    if (res.code === '0000') {
      setEditDataInitValue(res.data);
      setDrawerVisible(true);
    }
  };

  //失焦校验用户名重复
  const inputTenantChange = async (e: number | string) => {
    const res = await userNameSameVerify({ userName: e });
    if (res.code === '0000') {
      if (res.data) {
        message.error(t.formatMessage({
          id: 'userMange.info.hasUserName',
          defaultMessage: '用户名已经存在',
        }));
        return res.data;
      }
    }
    return false;
  };

  // 添加/编辑用户
  const onFinish = async (data: any) => {
    const afterSubmit = () => {
      setDrawerVisible(false);
      setEditDataInitValue({});
      setOnFormSubmit(0);
      setReloadNum(reloadNum + 1);
    };
    if (addOrEdit === 'add') {
      //提交时校验用户名重复
      const isSame = await inputTenantChange(data?.userName);
      if (isSame) {
        return;
      }
      //用户未选择性别，默认为保密 
      userManageAdd({ ...data, deptId: treeCheckedId, sex: data.sex ?? 2 }).then(() => {
        afterSubmit();
      });
    } else {
      userManageEdit({
        ...data,
        userId: editDataInitValue?.userId,
        version: editDataInitValue?.version
      }).then(() => {
        afterSubmit();
      });
    }
  };

  // 树选择
  const onTreeSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    if (selectedKeys.length > 0) {
      setTreeCheckedId(selectedKeys[0]);
      setDeptName(info?.node?.title);
      setReloadNum(() => reloadNum + 1);
    } else {
      setTreeCheckedId('');
      setReloadNum(() => reloadNum + 1);
    }
  };

  // 搜索框值改变
  const onSearchKeyChange = (e: any) => {
    const searchObj = e.target.value !== '' ? { key: e.target.value } : {};
    setSearchParams(searchObj);
  };

  // 重置输入框
  const onResetSearch = () => {
    setSearchParams({});
  };
  
  useEffect(() => {
    // 获取部门
    requestCompanyOption();
  }, []);

  //操作
  const columns: ProColumns<TableListItem>[] = [
    {
      title: t.formatMessage({
        id: 'userManag.columns.key',
        defaultMessage: '关键词',
      }),
      dataIndex: 'userId',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <Input
            style={{ width: 350 }}
            allowClear
            onChange={onSearchKeyChange}
            placeholder={t.formatMessage({
              id: 'form.info.text.entrt',
              defaultMessage: '请输入',
            })}
          />
        );
      },
    },
    {
      title: t.formatMessage({
        id: 'userMange.columns.UserNameNew',
        defaultMessage: '登录名',
      }),
      dataIndex: 'userName',
      hideInSearch: true,
      ellipsis: true,

    },
    {
      title: t.formatMessage({
        id: 'userMange.columns.nickNameNew',
        defaultMessage: '姓名',
      }),
      dataIndex: 'nickName',
      hideInSearch: true,
      ellipsis: true,
      render: (_, record) => {
        return <div>{record?.nickName}{' '}{sexTag(record?.sex)}</div>;
      },
    },

    {
      title: t.formatMessage({
        id: 'userMange.columns.phone',
        defaultMessage: '手机号码',
      }),
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: t.formatMessage({
        id: 'userMange.columns.email',
        defaultMessage: '邮箱',
      }),

      dataIndex: 'email',
      hideInSearch: true,
    },
    {
      title: t.formatMessage({
        id: 'userMange.columns.status',
        defaultMessage: '账号状态',
      }),

      hideInSearch: true,
      dataIndex: 'status',
      render: (_, record) => accountStatusByUser(record.status),
    },
    {
      title: t.formatMessage({
        id: 'userMange.columns.RoleName',
        defaultMessage: '角色名',
      }),
      hideInSearch: true,
      dataIndex: 'roleName',
      render: (_, record) => {
        const roles = record.roleName?.split(',') || [];
        const displayedRoles = roles.length <= 3 ? roles : roles.slice(0, 3);
        return (
          <>
            {
              roles.length ?
                <Tooltip key="toolTip"
                  placement="topRight" title={roles.map((item: any) => <><span>{item}</span><br /></>)} >
                  {displayedRoles.map((item: any, index: any) => (
                    <Tag key={index}>{item}</Tag>
                  ))}
                  {roles.length > 3 && <Tag>...</Tag>}
                </Tooltip>
                :
                '-'
            }
          </>
        );
      }
    },
    {
      title: t.formatMessage({
        id: 'columns.title.option',
        defaultMessage: '操作',
      }),
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <PremissBtnMore
          key={'more'}
          btnGroups={[
            {
              buttonRender: (
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  onClick={() => {
                    setAddOrEdit('edit');
                    getDetailsMsg(record.userId);

                    setListId(record.userId);
                  }}
                >
                  {t.formatMessage({
                    id: 'columns.handel.edit',
                    defaultMessage: '编辑',
                  })}
                </Button>
              ),
              buttonKey: `${userAccessBtn}Edit`,
            },
            {
              buttonRender: (
                <CueBubble
                  url={USER_MANAGE_LIST_DEL}
                  idObj={{ userId: record.userId }}
                  onSave={() => {
                    setReloadNum((reloadNum) => reloadNum + 1);
                  }}
                  key={'del'}
                  delTypeTitle={`${record.userName}`}
                />
              ),
              buttonKey: `${userAccessBtn}Del`,
            },
            {
              buttonRender: (
                <Popconfirm
                  title={
                    record.status === 0
                      ? t.formatMessage({
                        id: 'columns.handel.disabled',
                      })
                      : t.formatMessage({
                        id: 'columns.handel.enable',
                      })
                  }
                  description={
                    record.status === 0
                      ? t.formatMessage({
                        id: 'form.info.disableAccount',
                      }, { text: record.userName })
                      : t.formatMessage({
                        id: 'form.info.enableAccount',
                      }, { text: record.userName })
                  }
                  onConfirm={() => {
                    userEditDetails({ userId: record.userId }).then((res: any) => {
                      const num = {
                        status: record.status === 0 ? 1 : record.status === 1 ? 0 : record.status ? 0 : 1,
                        userId: record.userId,
                        version: res.data?.version,
                      };
                      switchUser(num).then(() => {
                        setDisableEnable({
                          id: record.userId,
                          status: record.status === 1 ? true : false,
                        });
                      });
                    });

                  }}
                >
                  <Button
                    key="disable"
                    type="link"
                    size="small"
                  >
                    {t.formatMessage({
                      id: !record.status ? 'columns.handel.disabled' : 'columns.handel.enable',
                    })}
                  </Button>
                </Popconfirm>
              ),
              buttonKey: `${userAccessBtn}Disable/${userAccessBtn}Enable`,
            },
            {
              buttonRender: (
                <Popconfirm
                  title={t.formatMessage({
                    id: 'userMange.title.resetPass',
                  })}
                  description={t.formatMessage({
                    id: 'form.info.resetPassWord',
                  }, { text: record.userName })}
                  onConfirm={() => {
                    userEditDetails({ userId: record.userId }).then((res: any) => {
                      const num = {
                        userId: record.userId,
                        version: res.data?.version,
                      };
                      resetUserPassword(num).then(() => {
                        setReloadNum(reloadNum + 1);
                      });
                    });
                  }}
                >
                  <Button key="reset" size="small" type="link">
                    {t.formatMessage({
                      id: 'userMange.handel.resetPassword',
                    })}
                  </Button>
                </Popconfirm>
              ),
              buttonKey: `${userAccessBtn}Reset`,
            },
            !backupPage && {
              buttonRender: (
                <Button key="dept" type="link" size="small" onClick={() => {
                  setListId(record.userId);
                  setModalDeptVisible(true);
                  setListDetails(record);
                }
                }>
                  {t.formatMessage({
                    id: 'userMange.handel.ChangeDept',
                    defaultMessage: '更改部门',
                  })}
                </Button>
              ),
              buttonKey: `${userAccessBtn}ChangeDept`,
            },
            {
              buttonRender: (
                <Button key="Role" type="link" size="small" onClick={() => {
                  setListId(record.userId);
                  setListDetails(record);
                  getRole({ userId: record.userId }).then((res: any) => {
                    const roleData = res.data?.map((item: any) => {
                      return {
                        label: item?.roleName,
                        value: item?.roleId
                      };
                    });
                    setRoleOptionData(roleData);
                    setModalRoleVisible(true);
                  });
                }
                }>
                  {t.formatMessage({
                    id: 'userMange.handel.ChangeRole',
                    defaultMessage: '配置角色',
                  })}
                </Button>
              ),
              buttonKey: `${userAccessBtn}ChangeRole`,
            },
          ].filter(Boolean)}
        />,
      ],
    },
  ];

  return (
    <>
      <PageHeader />
      <Row className="row-container">
        {/* 左侧部门树*/}
        {!backupPage
          &&
          <Col span={4} className="left-tree">
            <div className="pro-form-container">
              <Affix offsetTop={136}>
              <Spin spinning={treeSpinLoading}>
                {treeData.length > 0 ? (
                  <>
                    <Switch defaultChecked  onChange={onSwitchChange}
                      checkedChildren={t.formatMessage({ id: 'userMange.form.viewCurrent' })}
                      // unCheckedChildren={t.formatMessage({ id: 'userMange.form.viewAll' })}
                      unCheckedChildren={t.formatMessage({ id: 'userMange.form.viewCurrent' })}
                      className="switch-item"
                    />
                    <div className="trees-container">
                      <DirectoryTree
                        className="trees"
                        onSelect={onTreeSelect}
                        treeData={treeData}
                        // height={700}
                        blockNode
                        showIcon={false}
                      />
                    </div>
                  </>
                ) 
                : 
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                }
                 </Spin>
              </Affix>
            </div>
          </Col>
        }
        {/* 右侧表格 */}
        <Col span={!backupPage ? 20 : 24}>
          <SearchTable
            headerTitle={t.formatMessage({ id: 'columns.title.header' })}
            disableEnable={disableEnable}
            reload={reloadNum}
            isSerial={true}
            columns={columns}
            otherParams={{ deptId: treeCheckedId, containDeptChild: containDeptChild }}
            searchParams={searchParams}
            onResetSearch={onResetSearch}
            rowKey={'userId'}
            toolbar={{
              title: (
                <span>
                  {t.formatMessage({
                    id: 'columns.title.header'
                  })}
                </span>
              ),
            }}
            toolBarRender={() => [
              <PremissBtn
                key="addBtn"
                buttonKey={`${userAccessBtn}Add`}
                buttonRender={
                  <Button
                    type="primary"
                    onClick={() => {
                      setAddOrEdit('add');
                      setDrawerVisible(true);
                      setEditDataInitValue({});
                    }}
                  >
                    <PlusOutlined className="margin-r-s" />
                    <FormattedMessage
                      id="columns.handel.add"
                      defaultMessage="添加"
                    />
                  </Button>
                }
              />
            ]}
            initAPI={USER_MANAGE_PAGE_GET}
          />
          <Modal
            open={modalDeptVisible}
            className="user-mange-modal"
            title={t.formatMessage({
              id: 'userMange.handel.ChangeDept',
              defaultMessage: '更改部门',
            })}
            onCancel={() => {
              setModalDeptVisible(false);
            }}
            onOk={() => setSubmitDept(submitDept + 1)}
            destroyOnClose
            width={smallPopup}
          >
            <DeptChange
              onSave={changeDeptFunc}
              initialValues={{ deptId: listDetails?.deptId || '' }}
              submitDept={submitDept}
              treeData={deptTreeData}
            />
          </Modal>
          <Modal
            open={modalRoleVisible}
            className="user-mange-modal"
            title={t.formatMessage({
              id: 'userMange.handel.ChangeRole',
              defaultMessage: '更改角色',
            })}
            onCancel={() => {
              setModalRoleVisible(false);
            }}
            onOk={() => setSubmitRole(submitDept + 1)}
            destroyOnClose
            width={smallPopup}
          >
            <RoleChange
              onSave={onChangeRole}
              initialValues={{ roleIds: listDetails?.roleIdList || [] }}
              submitRole={submitRole}
              option={roleOptionData}
            />
          </Modal>
          <Modal
            title={
              addOrEdit === 'edit'
                ? t.formatMessage({
                  id: 'userManage.edit.user',
                  defaultMessage: '编辑',
                })
                : t.formatMessage({
                  id: 'userManage.add.user',
                  defaultMessage: '添加',
                })
            }
            onCancel={() => {
              setDrawerVisible(false);
              setEditDataInitValue({});
              setOnFormSubmit(0);
            }}
            className="user-mange-modal"
            width={smallPopup}
            open={drawerVisible}
            maskClosable={false}
            destroyOnClose
            footer={
              <div className="text-right">
                <Space>
                  <Button
                    onClick={() => {
                      setDrawerVisible(false);
                      setEditDataInitValue({});
                      setOnFormSubmit(0);
                    }}
                  >
                    <FormattedMessage
                      id="form.handel.cancel"
                      defaultMessage="取消"
                    />
                  </Button>
                  <Button
                    onClick={() => {
                      setOnFormSubmit(onFormSubmit + 1);
                    }}
                    type="primary"
                  >
                    <FormattedMessage
                      id="form.handel.save"
                      defaultMessage="保存"
                    />
                  </Button>
                </Space>
              </div>
            }
          >
            {deptName &&
              <>
                <div className="now-dept">{t.formatMessage({
                  id: 'userMange.label.DeptName',
                  defaultMessage: '部门名称',
                })}{` : ${deptName}`}</div>
              </>
            }
            <AddOrEditForm
              onSave={onFinish}
              inputTenantChange={inputTenantChange}
              initialValues={editDataInitValue}
              submitForm={onFormSubmit}
              option={sexOption}
              addOrEdit={addOrEdit}
            />
          </Modal>
        </Col>
      </Row>
    </>
  );
};

export default UserManage;
