import { Button, Col, Form, Input, message, Modal, Row, Space } from 'antd';
import React, { useState } from 'react';
import { createInfraredCategory, updateInfraredCategory } from '@/services/Infrared/category';
import UploadImage from '@/components/UploadImage';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

interface userEditPros {
  visible: boolean;
  editCallback: () => void;
  detailData: any;
}

const Edit: React.FC<userEditPros> = (props) => {
  const { visible, editCallback, detailData } = props;
  const [form] = Form.useForm();
  const [filesList, setFilesList] = useState([]);

  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        data.icon = filesList[0];
        data.keys = JSON.stringify(data.keys);
        if (detailData) {
          data.record_id = detailData.record_id;
          updateInfraredCategory(data)
            .then((res) => {
              if (res && res.code === 0) {
                message.success('新增成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        } else {
          createInfraredCategory(data)
            .then((res) => {
              if (res && res.code === 0) {
                message.success('编辑成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        }
      }
    });
  };

  const onCancel = () => {
    editCallback();
  };

  // 上传图片回调
  const onUploadChange = (files: any) => {
    if (files && files.length) {
      const arr: any = [];
      files.forEach((el: any) => {
        arr.push(el?.response?.data?.url || '');
      });
      setFilesList(arr);
    }
  };

  const formItemLayout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 19,
    },
  };

  return (
    <Modal
      title={`${detailData ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="name"
              label="类型名称"
              rules={[{ required: true, message: '请输入类型名称' }]}
              initialValue={detailData?.name || ''}
            >
              <Input placeholder="请输入类型姓名" />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item {...formItemLayout} label="按键名称">
              <Form.List
                name="keys"
                initialValue={detailData?.keys ? JSON.parse(detailData.keys) : []}
              >
                {(fields: { [x: string]: any; key: any; name: any }[], { add, remove }: any) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space
                        key={key}
                        style={{ display: 'flex', marginBottom: 8 }}
                        align="baseline"
                      >
                        <Form.Item
                          {...restField}
                          name={[name, 'key']}
                          rules={[{ required: true, message: '请输入key' }]}
                        >
                          <Input placeholder="key" />
                        </Form.Item>
                        <Form.Item
                          {...restField}
                          name={[name, 'value']}
                          rules={[{ required: true, message: '请输入value' }]}
                        >
                          <Input placeholder="value" />
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      </Space>
                    ))}
                    <Form.Item>
                      <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        添加按键
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="icon"
              label="上传图片"
              rules={[{ required: true, message: '请选择图片' }]}
              initialValue={detailData?.icon ? [{ url: detailData?.icon }] : []}
            >
              <UploadImage
                maxCount={1}
                onChange={onUploadChange}
                value={[{ url: detailData?.icon }]}
              />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
