import React, { useEffect, useState } from 'react';
import { Col, Form, Input, message, Modal, Row, TreeSelect, Upload } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { createOta, editOta, queryDeviceList } from '@/services/ota';
const { Dragger } = Upload;

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

/**
 * ota管理 - 编辑
 * @param props
 * @constructor
 */
const Edit: React.FC<editPros> = (props) => {
  const { params, visible, editCallback } = props;
  const [form] = Form.useForm();
  const [deviceList, setDeviceList] = useState([]);
  const [fileData, setFileData]: any = useState(
    params && params.url
      ? [
          {
            url: params.url,
            md5: params.md5,
            size: params.file_size,
            name: params.file_name,
          },
        ]
      : [],
  );

  /**
   *  获取设备类型列表
   */
  const getDeviceList = () => {
    queryDeviceList({ q: 'tree' }).then((res) => {
      if (res && res.code === 0) {
        setDeviceList(res.data.list);
      }
    });
  };

  useEffect(() => {
    getDeviceList();
  }, []);

  // 提交
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        data.url = fileData[0].url;
        data.md5 = fileData[0].md5;
        data.file_size = fileData[0].size;
        data.file_name = fileData[0].name;
        if (params) {
          // 编辑
          data.record_id = params.record_id;
          editOta(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 {
          //  新增
          createOta(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 toTreeSelect = (data: any) => {
    if (!data) {
      return [];
    }
    const newData = [];
    for (let i = 0; i < data.length; i += 1) {
      const item = {
        ...data[i],
        title: data[i].name,
        value: data[i].record_id,
      };
      if (item.children && item.children.length > 0) {
        item.children = toTreeSelect(item.children);
        item.disabled = true;
      }
      newData.push(item);
    }
    return newData;
  };

  const uploadProps: UploadProps = {
    name: 'file',
    action: '/web/v1/files',
    maxCount: 1,
    headers: {
      authorization: 'authorization-text',
    },
    defaultFileList: fileData,
    onChange(info) {
      const { status, response } = info.file;
      if (status === 'done') {
        //判断上传状态
        if (response.code === 0) {
          message.success(`上传成功！`);
          setFileData([response.data]);
          form.setFieldValue('remote_map', response.data.name);
        } else {
          message.error(response.resultMsg);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const formItemLayout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 19,
    },
  };
  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="version"
              label="版本号"
              rules={[{ required: true, message: '请输入版本号' }]}
              initialValue={params?.version || ''}
            >
              <Input placeholder="请输入版本号" />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="device_type_id"
              label="设备类型"
              rules={[{ required: true, message: '请选择设备类型' }]}
              initialValue={params?.device_type_id || undefined}
            >
              <TreeSelect
                allowClear
                showSearch
                treeDefaultExpandAll
                treeNodeFilterProp="title"
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={toTreeSelect(deviceList)}
                placeholder="请选择"
              />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="content"
              label="更新内容"
              rules={[{ required: true, message: '请输入更新内容' }]}
              initialValue={params?.content || ''}
            >
              <Input placeholder="请输入更新内容" />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="url"
              getValueFromEvent={normFile}
              label="文件地址"
              rules={[{ required: true, message: '请选择文件' }]}
              initialValue={params?.url || ''}
            >
              <Dragger {...uploadProps}>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
              </Dragger>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
