import React, { useState } from 'react';
import { Col, Form, Input, message, Modal, Row } from 'antd';
import UploadImage from '@/components/UploadImage';
import { updateDeviceFaults } from '@/services/DeviceFaults';

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

/**
 * 更新故障
 * @param props
 * @constructor
 */
const UpdateFaults: React.FC<editPros> = (props) => {
  const { params, visible, editCallback } = props;
  const [form] = Form.useForm();
  const [filesList, setFilesList] = useState([]);

  const { TextArea } = Input;

  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        data.files = filesList;
        data.record_id = params.record_id;
        updateDeviceFaults(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({ url: el?.response?.data?.url });
      });
      setFilesList(arr);
    }
  };

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

  if (params) {
    return (
      <Modal title="更新" open={visible} onOk={onOk} onCancel={onCancel} width={800}>
        <Form form={form}>
          <Row>
            <Col span={24}>
              <Form.Item
                {...formItemLayout24}
                name="solution"
                label="解决办法"
                rules={[{ required: true, message: '请输入解决办法' }]}
                initialValue={params?.solution}
              >
                <TextArea placeholder="请输入解决办法" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                {...formItemLayout24}
                name="files"
                label="上传图片"
                rules={[{ required: true, message: '请选择图片' }]}
                initialValue={params?.files || []}
              >
                <UploadImage
                  maxCount={9}
                  onChange={onUploadChange}
                  value={[{ url: params?.url }]}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  } else {
    return null;
  }
};
export default UpdateFaults;
