import React, { useEffect } from 'react';
import { InterListType, InterReqType } from '~/api/interface';
import { insertBAccountType, listBAccountPageType } from '~/api/interface/systemManageType';
import { Col, Form, Input, message, Modal, Row, Select, TreeSelect } from 'antd';
import { SystemManageAPI } from '~/api';

// 列表的类型
type TableType = InterListType<listBAccountPageType>;
// 请求的表单类型
type ReqType = InterReqType<insertBAccountType>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}
const AddEditModal: React.FC<propType> = (props) => {
  AddEditModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data } = props;
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await SystemManageAPI[data?.id ? 'updateBAccount' : 'insertBAccount']({
      ...data,
      ...values,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={600}
    >
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
      >
        <Row gutter={{ xs: 8, sm: 16, md: 24 }}>
          <Col span={11}>
            <Form.Item
              label='账号'
              name='accountNo'
              rules={[{ required: true, message: '请输入账号' }]}
            >
              <Input placeholder={'请输入账号'} maxLength={20} allowClear />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item
              label='姓名'
              name='userName'
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder={'请输入姓名'} maxLength={20} allowClear />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={{ xs: 8, sm: 16, md: 24 }}>
          <Col span={11}>
            <Form.Item
              label='手机号'
              name='phoneNum'
              rules={[
                { required: true, message: '请输入手机号' },
                // 校验手机号
                () => ({
                  validator(_, value) {
                    if (!value || /^1[3-9]\d{9}$/.test(value)) {
                      return Promise.resolve();
                    }
                    return Promise.reject('请输入正确的手机号');
                  },
                }),
              ]}
            >
              <Input placeholder={'请输入手机号'} maxLength={20} allowClear type={'number'} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item
              label='角色'
              name='roleId'
              rules={[{ required: true, message: '请选择角色' }]}
              initialValue={1}
            >
              <Select
                placeholder={'请选择角色'}
                style={{ width: '168px' }}
                options={[{ value: 1, label: '超级管理员' }]}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={{ xs: 8, sm: 16, md: 24 }}>
          <Col span={11}>
            <Form.Item
              label='邮箱'
              name='email'
              rules={[{ type: 'email', message: '请输入正确的邮箱' }]}
            >
              <Input placeholder={'请输入邮箱'} maxLength={48} allowClear />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item
              label='账号类型'
              name='accountType'
              rules={[{ required: true, message: '请选择账号类型' }]}
              initialValue={1}
            >
              <Select
                placeholder={'请选择账号类型'}
                style={{ width: '168px' }}
                options={[
                  { value: 1, label: '员工' },
                  { value: 0, label: '合伙人' },
                ]}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          label='所属单位'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          rules={[{ required: true, message: '请选择所属单位' }]}
          name='companyId'
          initialValue={1}
        >
          <TreeSelect
            treeData={[{ id: 1, company: '科比特' }]}
            placeholder='请选择所属单位'
            fieldNames={{
              children: 'children',
              label: 'company',
              value: 'id',
            }}
            allowClear
          />
        </Form.Item>
        <Form.Item
          label='账号状态'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          name='accountStatus'
          initialValue={1}
        >
          <Select
            placeholder={'请选择账号状态'}
            options={[
              { value: 1, label: '可用' },
              { value: 0, label: '停用' },
            ]}
          />
        </Form.Item>
        {!data?.id && (
          <>
            <Form.Item
              label='密码'
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 18 }}
              rules={[{ required: true, message: '请输入密码' }]}
              name='passWord'
            >
              <Input.Password
                placeholder='请输入密码'
                maxLength={20}
                autoComplete='new-password'
                allowClear
              />
            </Form.Item>
            <Form.Item
              label='确认密码'
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 18 }}
              name='alertPwd'
              rules={[
                { required: true, message: '请输入密码' },
                // 判断密码是否相同
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('passWord') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password
                placeholder='请再次输入密码'
                maxLength={20}
                autoComplete='new-password'
                allowClear
              />
            </Form.Item>
          </>
        )}
        <Form.Item label='备注' labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} name='remark'>
          <Input.TextArea placeholder='请输入备注' maxLength={70} showCount rows={4} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
