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

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

const CompanyDetail = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  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 [companyDetail, setCompanyDetail] = useState<companyDetailType>();
  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 getCompanyDetailInfo = (id: number) => {
    SystemManageAPI.getCompanyInfoById({ id }).then(({ result }) => {
      setCompanyDetail(result);
    });
  };
  //单位成员列表
  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 backRoute = () => {
    navigate(-1);
  };

  useEffect(() => {
    setCompanyId(Number(searchParams.get('id')));
    getCompanyDetailInfo(Number(searchParams.get('id')));
    getListCompanyMembers(Number(searchParams.get('id')));
  }, []);

  return (
    <div className='company-detail'>
      <div className='company-detail-info'>
        <Descriptions title='基本信息' bordered column={4}>
          <Descriptions.Item label='单位名称'>{companyDetail?.companyName}</Descriptions.Item>
          <Descriptions.Item label='详细地址'>{companyDetail?.address}</Descriptions.Item>
          <Descriptions.Item label='联系人'>
            {companyDetail?.companyUserName || ''}
          </Descriptions.Item>
          <Descriptions.Item label='联系电话'>{companyDetail?.phoneNum || ''}</Descriptions.Item>
        </Descriptions>
      </div>
      <div className='company-detail-people'>
        <div className='company-detail-people-title'>成员信息</div>
        <div className='company-detail-people-operate'>
          <Button
            type='primary'
            icon={<PlusOutlined></PlusOutlined>}
            onClick={addPeopleClick}
            disabled={!userInfo.companyInfoVO.leader}
          >
            添加成员
          </Button>
        </div>
        <Table
          bordered
          columns={tableColumns}
          dataSource={listCompanyMembers}
          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>
      <div className='company-detail-operate'>
        <Button type='primary' onClick={backRoute}>
          返回
        </Button>
      </div>
      {/*添加成员*/}
      <AddPeopleModal
        open={addPeopleModalShow}
        onCancel={addPeopleModalCancel}
        onOk={addPeopleModalOk}
        companyInfoId={companyId}
      />
      {/*转让管理员*/}
      <TransferLeaderModal
        open={transferLeaderModalShow}
        onCancel={transferLeaderModalCancel}
        onOk={transferLeaderModalOk}
        companyInfoId={companyId}
        currentCompanyMembers={currentCompanyMembers}
      />
    </div>
  );
};
export default CompanyDetail;
