import React, { useEffect, useState } from 'react';
import {
  Modal,
  Form,
  Input,
  notification,
  message,
  Upload,
  Drawer,
  Select,
  Space,
  Button,
  Row,
  Col,
} from 'antd';
import { SaveUpload, UpdateModelInfo } from '@/services/drawBoardManage/api';

const EditTemplate = props => {
  const { visible, treeData, obj, pickItem, callBackSubmit = () => {}, onCancel } = props;
  const [addTemplateForm] = Form.useForm();
  const [selectValue, setSelectValue] = useState('');
  const [file, setFile] = useState('');
  const { Option } = Select;

  useEffect(() => {
    addTemplateForm.resetFields();
    console.log(pickItem);
    console.log(obj);
    if (obj.Path) {
      let index = obj.Path.lastIndexOf('\\');
      let ab = obj.Path.substring(index + 1, obj.Path.length);
      let a = JSON.parse(obj.Json);
      console.log(a);
      let aa;
      let bb;
      if (a) {
        if (a.width.charAt(a.width.length - 1) == 'x') {
          aa = `${a.width}`;
          bb = `${a.height}`;
        } else {
          aa = `${a.width}px`;
          bb = `${a.height}px`;
        }
      }
      addTemplateForm.setFieldsValue({
        Name: obj.ModelName,
        Type: obj.ModelTypeName,
        ModelFile: ab,
        imageWidth: aa,
        imageHeight: bb,
      });
    }
  }, [visible]);

  const submitAdd = () => {
    addTemplateForm.validateFields().then(validate => {
      if (validate) {
        let aa = {};
        aa.width = addTemplateForm.getFieldsValue().imageWidth.toString();
        aa.height = addTemplateForm.getFieldsValue().imageHeight.toString();
        console.log(aa);
        console.log(file);
        const formData = new FormData();
        formData.append('ModelName', addTemplateForm.getFieldsValue().ModelFile);
        formData.append('ModelType', obj.ModelTypeName);
        formData.append('width', aa.width);
        formData.append('height', aa.height);
        formData.append('ID', obj.ID);
        formData.append('ModelFile', file);
        // if (obj.realModal != 0) {
        //   formData.append('RelModel', obj.realModel);
        // }
        console.log(formData);
        UpdateModelInfo(formData).then(res => {
          if (res.code === 0) {
            callBackSubmit();
            notification.success({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          } else {
            notification.error({
              message: '提示',
              duration: 3,
              description: res.msg,
            });
          }
        });
      }
    });
  };
  const changTable = e => {
    setSelectValue(e);
  };

  const aa = {
    beforeUpload: file => {
      // const isPNG = file.type === 'image/png';
      // if (!isPNG) {
      //   message.error(`${file.name} 不是png类型的图片`);
      // } else {
      setFile(file);
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const image = new Image();
        image.src = reader.result;
        image.onload = () => {
          addTemplateForm.setFieldsValue({
            imageWidth: `${image.width}px`,
            imageHeight: `${image.height}px`,
            ModelFile: file.name,
            Name: file.name.substring(0, file.name.lastIndexOf('.')),
          });
        };
        // };
      };
      return Upload.LIST_IGNORE;
    },
    onChange: info => {
      console.log(info);
    },
  };

  return (
    <Drawer
      title="编辑模型"
      visible={visible}
      width="500px"
      destroyOnClose
      {...props}
      footer={
        <Space>
          <Button onClick={submitAdd} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={addTemplateForm} labelCol={{ span: 5 }}>
        <Form.Item name="Type" label="模板类型" rules={[{ required: true, message: '不能为空' }]}>
          <Select
            placeholder="选择模板类型"
            onChange={changTable}
            style={{ marginLeft: '-3px' }}
            showSearch
            disabled
          >
            {treeData
              ? treeData.map((item, index) => (
                  <Option key={item.id} value={item.name}>
                    {item.name}
                  </Option>
                ))
              : ''}
          </Select>
        </Form.Item>
        <Row>
          <Col span={17}>
            <Form.Item
              label="模型文件"
              name="ModelFile"
              labelCol={{ span: 7 }}
              rules={[
                {
                  required: true,
                  message: '请选择模型文件',
                },
              ]}
            >
              <Input placeholder="仅支持png和svg格式" disabled />
            </Form.Item>
          </Col>
          <Col span={7}>
            <Form.Item>
              <Upload {...aa} accept=".png, .svg">
                <Button style={{ width: '130px' }}>上传图片</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item label="模型名称" name="Name">
          <Input placeholder="请输入菜单组名称" disabled />
        </Form.Item>
        <Row>
          <Col span={13}>
            <Form.Item label="宽" name="imageWidth" labelCol={{ span: 9 }}>
              <Input style={{ width: '153px' }} disabled />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item label="高" name="imageHeight" labelCol={{ span: 7 }}>
              <Input style={{ width: '146px' }} disabled />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};
export default EditTemplate;
