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

//单位-成员列表返回类型
type companyMembersType = InterDataType<listCompanyMembersType>['list'];
const TransferLeaderModal: React.FC<
  ModalProps & {
    onOk: () => void;
    onCancel: () => void;
    companyInfoId: number;
    currentCompanyMembers?: companyMembersType[0];
  }
> = ({ open, onOk, onCancel, companyInfoId, currentCompanyMembers }) => {
  const [form] = Form.useForm<{ toUserAccountId: number }>();
  const [listCompanyMembers, setListCompanyMembers] = useState<SelectProps['options']>([]);
  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?.map((item) => ({
          label: `${item?.userName || item?.nickName || item?.uid}（${item?.phoneNum}）`,
          value: item.id,
          key: item.id,
          disabled: item.id === currentCompanyMembers?.id,
        })),
      );
    });
  };
  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())
            }
            options={listCompanyMembers}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default TransferLeaderModal;
