import React, { useEffect, useState } from 'react';
import { Col, Form, message, Modal, Radio, Row, Select } from 'antd';
import { queryRole } from '@/services/role';
import { queryUserList } from '@/services/setting';
import { createPush } from '@/services/pushMessage';

interface editPros {
  visible: boolean;
  pushCallback: () => void;
  params: any;
}

/**
 * 推送消息 - 编辑
 * @param props
 * @constructor
 */
const PushModal: React.FC<editPros> = (props) => {
  const { params, visible, pushCallback } = props;
  const [form] = Form.useForm();
  const { setFieldsValue } = form;
  const [roleList, setRoleList] = useState([]);
  const [userList, setUserList] = useState([]);
  const [type, setType] = useState(null);

  // 获取角色列表
  const getRoleList = () => {
    queryRole({ q: 'list' }).then((res) => {
      if (res && res.code === 0) {
        setRoleList(res.data.list || []);
      }
    });
  };

  // 获取用户列表
  const getUserList = () => {
    queryUserList({ q: 'list' }).then((res) => {
      if (res && res.code === 0) {
        setUserList(res.data || []);
      }
    });
  };

  useEffect(() => {
    getRoleList();
    getUserList();
  }, []);

  // 提交
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        const res: any = {
          type: 'single',
        };
        if (data.push_type === 1) {
          res.all = true;
        }

        if (data.push_type === 2) {
          res.role_id = data.role_id.join(',');
        }

        if (data.push_type === 3) {
          res.user_id = data.user_id.join(',');
        }

        createPush(res)
          .then((item) => {
            if (item && item.code === 0) {
              message.success('推送成功');
              pushCallback();
            } else {
              message.error(item?.message || '推送失败');
            }
          })
          .catch((e) => {
            message.error(e?.message || '推送失败');
          });
      }
    });
  };

  // 取消
  const onCancel = () => {
    pushCallback();
  };

  const formItemLayout24 = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
  };

  // 切换类型
  const onRadioChange = (e: any) => {
    setType(e.target.value);
    setFieldsValue({ role_id: [], user_id: [] });
  };

  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={24}>
            <Form.Item
              {...formItemLayout24}
              name="push_type"
              label="推送类型"
              rules={[{ required: true, message: '请选择推送类型' }]}
              initialValue={params?.push_type}
            >
              <Radio.Group onChange={onRadioChange}>
                <Radio value={1}>全部推送</Radio>
                <Radio value={2}>按角色推送</Radio>
                <Radio value={3}>按用户推送</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          {type === 2 && (
            <Col span={24}>
              <Form.Item
                {...formItemLayout24}
                name="role_id"
                label="角色"
                rules={[{ required: true, message: '请选择角色' }]}
                initialValue={params?.role_id}
              >
                <Select placeholder="请选择角色" mode="multiple">
                  {roleList &&
                    roleList.map((item: any) => {
                      return (
                        <Select.Option value={item.record_id} key={item.record_id}>
                          {item.name}
                        </Select.Option>
                      );
                    })}
                </Select>
              </Form.Item>
            </Col>
          )}
          {type === 3 && (
            <Col span={24}>
              <Form.Item
                {...formItemLayout24}
                name="user_id"
                label="用户"
                rules={[{ required: true, message: '请选择用户' }]}
                initialValue={params?.user_id}
              >
                <Select
                  placeholder="请选择用户"
                  mode="multiple"
                  showSearch
                  optionFilterProp="user_name"
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                >
                  {userList &&
                    userList.map((item: any) => {
                      return (
                        <Select.Option
                          value={item.record_id}
                          key={item.record_id}
                          label={item.user_name}
                        >
                          {item.user_name}
                        </Select.Option>
                      );
                    })}
                </Select>
              </Form.Item>
            </Col>
          )}
        </Row>
      </Form>
    </Modal>
  );
};
export default PushModal;
