import { FC, useState } from 'react';
import { Form, message, Modal, ModalProps, Select, SelectProps } from 'antd';
import { CommonAPI, SystemManageAPI } from '~/api';

interface selfProps {
  onOk: () => void;
  companyInfoId: number;
  roleList: SelectProps['options'];
}
const AddPeopleModal: FC<ModalProps & selfProps> = ({
  open,
  onCancel,
  onOk,
  companyInfoId,
  roleList,
}) => {
  const [form] = Form.useForm<{ userAccountId: number }>();
  const [options, setOptions] = useState<{ label: string; value: number; key: string }[]>([]);

  // 确认事件
  const handleOk = () => {
    form.validateFields().then((values) => {
      SystemManageAPI.bindingCompanyMember({ ...values, companyInfoId }).then(({ code }) => {
        if (code === '200') {
          message.success('绑定成功').then();
          onOk();
          form.resetFields();
        }
      });
    });
  };
  //select 搜索
  const selectSearchEvent = (value: string) => {
    CommonAPI.getUserAccountByPhoneNum({ phoneNum: value }).then(({ result }) => {
      const list = (result || []).map((v) => ({
        label: `${v?.userName || v?.nickName || v?.uid}（${v?.phoneNum}）`,
        // label: v.phoneNum + `(${v.uid})`,
        value: v.id,
        key: value,
      }));
      setOptions(list);
    });
  };
  return (
    <Modal open={open} title='添加成员' onOk={handleOk} onCancel={onCancel}>
      <Form form={form}>
        <Form.Item
          label='成员'
          name='userAccountId'
          rules={[{ required: true, message: '请选择成员' }]}
        >
          <Select
            placeholder='请输入成员手机号码'
            showSearch
            onSearch={selectSearchEvent}
            filterOption={(input, option) =>
              (option?.key ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={options}
          ></Select>
        </Form.Item>
        <Form.Item label='角色' name='leader' rules={[{ required: true, message: '请选择角色' }]}>
          <Select placeholder='请选择角色' options={roleList}></Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddPeopleModal;
