import React, { useEffect, useState } from 'react';
import { Button, Col, Form, Input, InputNumber, message, Modal, Row, Select, Upload } from 'antd';
import { queryInfraredCategory } from '@/services/Infrared/category';
import { createInfraredRemote, updateInfraredRemote } from '@/services/Infrared/remote';
import { queryInfraredBrands } from '@/services/Infrared/brand';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';

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

/**
 * 码库管理-编辑弹框
 * @param props
 * @constructor
 */
const Edit: React.FC<userEditPros> = (props) => {
  const { visible, editCallback, detailData } = props;
  const [form] = Form.useForm();
  const [categoryList, setCategoryList] = useState([]);
  const [brandList, setBrandList] = useState([]);
  const [fileList, setFileList]: any = useState(
    detailData && detailData.url ? [{ url: detailData.url, name: detailData.file_name }] : [],
  );

  // 获取品牌列表数据
  const getBrandList = (id: string) => {
    queryInfraredBrands({ q: 'list', category_id: id }).then((res) => {
      if (res && res.code === 0) {
        if (res.data.list && res.data.list.length) {
          setBrandList(res.data.list || []);
        } else {
          message.error('该类型下品牌为空');
        }
      } else {
        message.error(res?.message);
      }
    });
  };

  useEffect(() => {
    queryInfraredCategory({ q: 'list' }).then((res) => {
      if (res && res.code === 0) {
        setCategoryList(res.data.list || []);
      }
    });

    if (detailData) {
      getBrandList(detailData.category_id);
    }
  }, []);

  // 选择类型后查询品牌列表
  const onTypeChange = (id: string) => {
    form.setFieldValue('brand_id', undefined);
    getBrandList(id);
  };

  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        data.url = fileList[0].url;
        data.file_name = fileList[0].name;
        if (detailData) {
          data.record_id = detailData.record_id;
          updateInfraredRemote(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 {
          createInfraredRemote(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 uploadProps: UploadProps = {
    name: 'file',
    action: '/web/v1/files',
    maxCount: 1,
    headers: {
      authorization: 'authorization-text',
    },
    defaultFileList: fileList,
    onChange(info) {
      const { status, response } = info.file;
      if (status === 'done') {
        //判断上传状态
        if (response.code === 0) {
          message.success(`上传成功！`);
          setFileList([{ url: response.data.url, name: response.data.name }]);
          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={`${detailData ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="category_id"
              label="所属类型"
              rules={[{ required: true, message: '请选择所属类型' }]}
              initialValue={detailData?.category_id || undefined}
            >
              <Select placeholder="请选择所属类型" onChange={onTypeChange}>
                {categoryList && categoryList.length
                  ? categoryList.map((res: any) => {
                      return (
                        <Select.Option value={res.record_id} key={res.record_id}>
                          {res.name}
                        </Select.Option>
                      );
                    })
                  : null}
              </Select>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="brand_id"
              label="所属品牌"
              rules={[{ required: true, message: '请选择所属品牌' }]}
              initialValue={detailData?.brand_id || undefined}
            >
              <Select placeholder="请选择所属品牌" disabled={brandList && brandList.length < 1}>
                {brandList && brandList.length
                  ? brandList.map((res: any) => {
                      return (
                        <Select.Option value={res.record_id} key={res.record_id}>
                          {res.name}
                        </Select.Option>
                      );
                    })
                  : null}
              </Select>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="remote"
              label="控制编码"
              rules={[{ required: true, message: '请输入控制编码' }]}
              initialValue={detailData?.remote || ''}
            >
              <InputNumber placeholder="请输入控制编码" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="url"
              getValueFromEvent={normFile}
              label="文件地址"
              rules={[{ required: true, message: '请选择文件' }]}
              initialValue={detailData?.url || ''}
            >
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>上传文件</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout}
              name="remote_map"
              label="编码对应文件名称"
              rules={[{ required: true, message: '请输入编码对应文件名称' }]}
              initialValue={detailData?.remote_map || ''}
            >
              <Input placeholder="请输入编码对应文件名称" readOnly />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
