import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { listCompanyMembersType, updateAliasImgByUidType } from '~/api/interface/systemManageType';
import { InterListType, InterReqType } from '~/api/interface';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { SystemManageAPI } from '~/api';

// 单位-成员列表返回类型
type MembersType = InterListType<listCompanyMembersType>[0];
// 请求类型
type ReqType = InterReqType<updateAliasImgByUidType>;

const EditMemberModalView: React.FC<ModalProps & { data?: MembersType; onCancel: () => void }> = ({
  open,
  onCancel,
  title,
  data,
}) => {
  // 表单钩子
  const [form] = Form.useForm<ReqType & { serviceImg: { url: string }[] }>();
  // 关闭弹窗事件
  const handleCancel = () => {
    onCancel?.();
  };
  // 确认事件
  const handleOk = () => {
    form.validateFields().then(async (values) => {
      const res = await SystemManageAPI.updateAliasImgByUid({
        serviceAlias: values.serviceAlias,
        serviceImg: values.serviceImg?.[0].url,
        userAccountId: data?.id,
      });
      if (res && res.code === '200') {
        message.success('操作成功');
        onCancel?.();
      }
    });
  };
  // 组件挂载
  useEffect(() => {
    if (!open) return;
    form.setFieldsValue({
      serviceAlias: data?.serviceAlias || data?.userName || data?.nickName,
      serviceImg: [{ url: data?.serviceImg || data?.userImg }],
    });
    // console.log('组件挂载 --->', data);
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk}>
      <Form form={form} wrapperCol={{ span: 10 }}>
        <Form.Item
          label='客服昵称'
          name='serviceAlias'
          rules={[{ required: true, message: '请输入客服昵称' }]}
        >
          <Input placeholder='请输入客服昵称' maxLength={25} />
        </Form.Item>
        <Form.Item
          label='客服头像'
          name='serviceImg'
          rules={[{ required: true, message: '请上传客服头像' }]}
        >
          <Uploader fileUpload={true}>
            <UploadOutlined />
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditMemberModalView;
