import { useEffect, useState } from 'react';
import { SystemManageAPI } from '~/api';
import { InterDataType, PaginationProps } from '~/api/interface';
import { listCompanyMembersType } from '~/api/interface/systemManageType';
import { Button, message, Modal, SelectProps, Table } from 'antd';
import '~/pages/systemManage/companyManage/companyDetail/index.scss';
import { ColumnsType } from 'antd/es/table';
import { PlusOutlined } from '@ant-design/icons';
import AddPeopleModal from '~/pages/systemManage/companyManage/companyDetail/components/addPeopleModal';
import { useSelector } from 'react-redux';
import TransferLeaderModal from '~/pages/systemManage/companyManage/companyDetail/components/transferLeaderModal';

//单位-成员列表返回类型
type companyMembersType = InterDataType<listCompanyMembersType>['list'];

const CompanyMemberView = () => {
  const { userInfo } = useSelector((state: any) => state.UserInfo);
  // 角色列表
  const [roleList, setRoleList] = useState<SelectProps['options']>();
  const [companyId, setCompanyId] = useState<number>(-1);
  const [pagination, setPagination] = useState<PaginationProps & { totalCount: number }>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [listCompanyMembers, setListCompanyMembers] = useState<companyMembersType>([]);
  const [currentCompanyMembers, setCurrentCompanyMembers] = useState<companyMembersType[0]>();
  const [addPeopleModalShow, setAddPeopleModalShow] = useState<boolean>(false);
  const [transferLeaderModalShow, setTransferLeaderModalShow] = useState<boolean>(false);
  //单位成员列表
  const getListCompanyMembers = (companyInfoId: number) => {
    SystemManageAPI.getListCompanyMembers({
      companyInfoId,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    }).then(({ result }) => {
      pagination.totalCount = result.totalCount;
      setPagination(pagination);
      setListCompanyMembers(result.list || []);
    });
  };
  //分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    pagination.pageNo = pageNo;
    pagination.pageSize = pageSize;
    getListCompanyMembers(companyId);
  };
  //添加成员弹窗
  const addPeopleClick = () => {
    setAddPeopleModalShow(true);
  };
  const addPeopleModalOk = () => {
    getListCompanyMembers(companyId);
    setAddPeopleModalShow(false);
  };
  const addPeopleModalCancel = () => {
    setAddPeopleModalShow(false);
  };
  //转让管理员弹窗
  const transferLeaderClick = (record: companyMembersType[0]) => {
    setCurrentCompanyMembers(record);
    setTransferLeaderModalShow(true);
  };
  const transferLeaderModalCancel = () => {
    setTransferLeaderModalShow(false);
  };
  const transferLeaderModalOk = () => {
    setTransferLeaderModalShow(false);
    getListCompanyMembers(companyId);
  };
  //接触绑定
  const unbindCompanyClick = (record: companyMembersType[0]) => {
    Modal.confirm({
      title: '提示',
      content: '确认解除绑定该成员?',
      onOk: () => {
        SystemManageAPI.unbindCompanyMember({
          userAccountId: record.id,
          companyInfoId: companyId,
        }).then(({ code }) => {
          if (code === '200') {
            message.success('解除成功');
            if (pagination.pageNo !== 1 && listCompanyMembers?.length === 1) {
              pagination.pageNo -= 1;
            }
            getListCompanyMembers(companyId);
          }
        });
      },
    });
  };
  // 获取角色列表
  const getRoleList = async () => {
    const res = await SystemManageAPI.getRolesList();
    if (res && res.code === '200') {
      setRoleList(
        res.result?.map((i) => ({ label: i?.roleName, value: i?.id, disabled: i?.id === 1 })),
      );
    }
  };
  useEffect(() => {
    if (!userInfo?.companyInfoVO?.id) {
      message.warning('暂无单位').then();
      return;
    }
    setCompanyId(Number(userInfo?.companyInfoVO?.id));
    getListCompanyMembers(Number(userInfo?.companyInfoVO?.id));
    getRoleList().then();
  }, []);
  const tableColumns: ColumnsType<companyMembersType[0]> = [
    {
      title: 'uid',
      align: 'center',
      dataIndex: 'uid',
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'userName',
      render: (text, record) => text || record?.nickName,
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'leader',
      render: (text) => roleList?.find((i) => i?.value === text)?.label || text,
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phoneNum',
    },
    {
      title: '操作',
      width: '15%',
      align: 'center',
      render: (_text: string, record) => (
        <>
          {/*userInfo.companyInfoVO.leader === record.leader*/}
          <Button
            type='link'
            disabled={userInfo.companyInfoVO.leader !== 1}
            onClick={() => transferLeaderClick(record)}
          >
            转让
          </Button>
          <Button
            type='link'
            disabled={
              userInfo.companyInfoVO.leader !== 1 || userInfo.companyInfoVO.leader === record.leader
            }
            onClick={() => unbindCompanyClick(record)}
          >
            解绑
          </Button>
        </>
      ),
    },
  ];
  return (
    <div className='company-detail'>
      <div className='company-detail-people'>
        <div className='company-detail-people-operate'>
          <Button
            type='primary'
            icon={<PlusOutlined></PlusOutlined>}
            onClick={addPeopleClick}
            disabled={!userInfo.companyInfoVO.leader}
          >
            添加成员
          </Button>
        </div>
        <Table
          rowKey={'id'}
          bordered
          columns={tableColumns}
          dataSource={listCompanyMembers}
          size={'small'}
          pagination={{
            total: pagination.totalCount,
            pageSize: pagination.pageSize,
            current: pagination.pageNo,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
            showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
        />
      </div>
      <AddPeopleModal
        open={addPeopleModalShow}
        onCancel={addPeopleModalCancel}
        onOk={addPeopleModalOk}
        companyInfoId={companyId}
        roleList={roleList}
      />
      {/*转让管理员*/}
      <TransferLeaderModal
        open={transferLeaderModalShow}
        onCancel={transferLeaderModalCancel}
        onOk={transferLeaderModalOk}
        companyInfoId={companyId}
        currentCompanyMembers={currentCompanyMembers}
      />
    </div>
  );
};
export default CompanyMemberView;
