import { Form, message, Modal, ModalProps, Select } from 'antd';
import { FC, useEffect, useState } from 'react';
import { SystemManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { listCompanyMembersType } from '~/api/interface/systemManageType';

//单位-成员列表返回类型
type companyMembersType = InterDataType<listCompanyMembersType>['list'];
interface selfProps {
  onOk: () => void;
  companyInfoId: number;
  currentCompanyMembers: companyMembersType[0] | undefined;
}
const TransferLeaderModal: FC<ModalProps & selfProps> = ({
  open,
  onOk,
  onCancel,
  companyInfoId,
  currentCompanyMembers,
}) => {
  const [form] = Form.useForm<{ toUserAccountId: number }>();
  const [listCompanyMembers, setListCompanyMembers] = useState<companyMembersType>([]);
  const handleOk = () => {
    form.validateFields().then((values) => {
      if (currentCompanyMembers) {
        SystemManageAPI.transferLeader({
          companyInfoId,
          fromUserAccountId: currentCompanyMembers.id,
          ...values,
        }).then(({ code }) => {
          if (code === '200') {
            message.success('转让成功');
            onOk();
          }
        });
      }
    });
  };
  //单位成员列表
  const getListCompanyMembers = () => {
    SystemManageAPI.getListCompanyMembers({
      companyInfoId,
      pageNo: 1,
      pageSize: 999999,
    }).then(({ result }) => {
      setListCompanyMembers((result.list || []).filter((v) => !v.leader));
    });
  };
  useEffect(() => {
    if (currentCompanyMembers) {
      getListCompanyMembers();
    }
  }, [currentCompanyMembers]);
  return (
    <Modal open={open} title='转让管理员' onCancel={onCancel} onOk={handleOk}>
      <Form form={form}>
        <Form.Item label='转让人' name='toUserAccountId'>
          <Select
            placeholder='请选择受让人'
            filterOption={(input, option) =>
              (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
          >
            {listCompanyMembers.map((v) => (
              <Select.Option key={v.id} value={v.id}>
                {v.phoneNum}({v.uid})
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default TransferLeaderModal;
