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, 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 tableColumns: ColumnsType<companyMembersType[0]> = [
    {
      title: 'uid',
      align: 'center',
      dataIndex: 'uid',
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'userName',
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'leader',
      render: (text: number) => (text ? '单位管理员' : '普通员工'),
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phoneNum',
    },
    {
      title: '操作',
      width: '15%',
      onHeaderCell: () => ({
        style: {
          textAlign: 'center',
        },
      }),
      render: (_text: string, record) => (
        <>
          <Button
            type='link'
            disabled={!userInfo.companyInfoVO.leader || !record.leader}
            onClick={() => transferLeaderClick(record)}
          >
            转让
          </Button>
          <Button
            type='link'
            disabled={!userInfo.companyInfoVO.leader || !!record.leader}
            onClick={() => unbindCompanyClick(record)}
          >
            解绑
          </Button>
        </>
      ),
    },
  ];

  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);
          }
        });
      },
    });
  };
  useEffect(() => {
    if (!userInfo?.companyInfoVO?.id) {
      message.warning('暂无单位').then();
      return;
    }
    setCompanyId(Number(userInfo?.companyInfoVO?.id));
    getListCompanyMembers(Number(userInfo?.companyInfoVO?.id));
  }, []);

  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}
      />
      {/*转让管理员*/}
      <TransferLeaderModal
        open={transferLeaderModalShow}
        onCancel={transferLeaderModalCancel}
        onOk={transferLeaderModalOk}
        companyInfoId={companyId}
        currentCompanyMembers={currentCompanyMembers}
      />
    </div>
  );
};
export default CompanyMemberView;
