import React, { useState } from 'react';
import { Modal, Form, Input, Button, Select, DatePicker, Space, InputNumber, Icon, Upload, message } from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
import { openHtml } from '../service';
import { request } from 'umi';
import { cos } from 'cos-js-sdk-v5'

const CreateForm = (props) => {

  const { Option, OptGroup } = Select;

  //动态赋值表单
  const [form] = Form.useForm();

  //当前选中店铺
  const [currentSelect, setCurrentSelect] = useState();

  //广告地址
  const [htmlUrl, setHtmlUrl] = useState();

  const { RangePicker } = DatePicker;
  const { TextArea } = Input;

  //初始数据
  const planTimes = [];
  if (props.values) {
    //初始化时间
    planTimes.push(props.values.startTime);
    planTimes.push(props.values.endTime);
  }
  props.values.planDate = planTimes;

  //店铺下拉框赋值
  function handleChange(value) {
    setCurrentSelect(value);
  }
  //删除文件
  function deleteFiles(data) {
    var res = request(`/kitchen/api/Upload/DeleteFile?fileUrl=${data}`, {
      method: 'post',
    });
  }

  //上传成功后返回的图片相对路径数组
  let imageList = [];

  if (props.values.imageUrl) {
    imageList = props.values.imageUrl;
  }

  //上传文件
  const uploadProps = {
    beforeUpload: (file) => {
      let storeId = form.getFieldValue('storeId')
      if (typeof (storeId) == 'undefined') {
        message.error('请选择店铺!');
        return Upload.LIST_IGNORE;
      }
      let type = form.getFieldValue('type')
      if (type == 0) {
        //校验图片格式和大小
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
        if (!isJpgOrPng) {
          message.error('请上传图片格式文件!');
          return Upload.LIST_IGNORE;
        }
        const isLt2M = file.size / 1024 / 1024 < 4;
        if (!isLt2M) {
          message.error('图片不能大于4MB!');
          return Upload.LIST_IGNORE;
        }
        return true;
      } else if (type == 1) {
        //校验视频格式和大小
        const isVideo = file.type === 'video/mp4' || file.type === 'video/rmvb' || file.type === 'video/avi' || file.type === 'video/m4v';
        if (!isVideo) {
          message.error('请上传视频格式文件!');
          return Upload.LIST_IGNORE;
        }
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
          message.error('视频不能大于100MB!');
          return Upload.LIST_IGNORE;
        }
        return true;
      }
      else {
        message.error('请选择广告类型!');
        return Upload.LIST_IGNORE;
      }
    },
    name: 'file',
    action: `/kitchen/api/Upload/FormImg?storeId=${typeof (currentSelect) == "undefined" ? props.values.storeId : currentSelect}`,
    headers: {
      authorization: 'authorization-text',
    },
    showUploadList: { showPreviewIcon: false },
    listType: 'picture-card',
    multiple: true,
    maxCount: 10,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (!info.file.response.isSuccess) {
          //上传失败错误提示
          message.error(info.file.response.msg);
        }
        else {
          if (info.file.response.msg === 'mv') {
            //给视频地址动态赋值
            form.setFieldsValue({ videoUrl: info.file.response.data[0] });
            // setHtmlUrl(info.file.response.data[0]);
          }
          else {
            //给图片数组地址动态赋值
            //form.setFieldsValue({ imageUrl: info.file.response.data[0] });
            imageList.push({ name: info.file.response.data[0] });
            form.setFieldsValue({ imageUrl: imageList });
          }
          message.success(`${info.file.name} 上传成功`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onRemove(info) {
      let deleteName = "";
      if (typeof (info.response) == "undefined") {
        deleteFiles(info.name);//删除服务器原有的文件
        deleteName = info.name
      } else {
        deleteFiles(info.response.data[0]);//删除刚上传的文件
        deleteName = info.response.data[0]
      }
      //删除图片变量集合对应的文件
      for (let [key, value] of Object.entries(imageList)) {
        if (value.name == deleteName) {
          delete imageList[key]
        }
      }
    },
    onPreview(info) {

    },
    defaultFileList: props.values.imageUrl ? props.values.imageUrl : null


  };

  return (
    <Modal
      title={props.values.id ? '编辑' : '新建'}
      width={700}
      visible={props.createModalVisible}
      bodyStyle={{ padding: '32px 40px 48px' }}
      footer={null}
      onCancel={() => {
        props.onCancel();
      }}
      destroyOnClose
      maskClosable={false}
    >
      <Form
        form={form}
        layout="Horizontal"
        preserve={false}
        initialValues={props.values}
        onFinish={props.onFinish}
      >
        <Form.Item name="id" hidden={true}>
          <Input />
        </Form.Item>

        <Form.Item name="storeId" label={'选择店铺'} rules={[{ required: false }]}>
          <Select disabled={props.values.id ? true : false} onChange={handleChange}>
            {
              props.storeArray.map((item, index) => {
                return (
                  <Select.Option index={index} value={item.id} key={item.id} >
                    {item.text}
                  </Select.Option>
                );
              })
            }
          </Select>
        </Form.Item>

        <Form.Item name="title" label="广告标题" rules={[{ required: false, max: 20, whitespace: true }]}>
          <Input placeholder="广告标题" />
        </Form.Item>

        <Form.Item name="planDate" label="选择时间" rules={[{ required: false }]}>
          <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: 550 }} />
        </Form.Item>

        <Form.Item name="type" label="广告类型">
          <Select>
            <OptGroup>
              <Select.Option value={0}>图片</Select.Option>
              <Select.Option value={1}>视频</Select.Option>
            </OptGroup>
          </Select>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.type !== currentValues.type
          }
        >
          {({ getFieldValue }) =>
            getFieldValue('type') == '1' ? (
              <Form.Item hidden={true}>

              </Form.Item>
            ) : (
              <Form.Item style={{ height: 32 }}>
                <Form.Item label="轮播间隔" name="step" rules={[{ required: false, message: '图片轮播时间间隔' }]}>
                  <InputNumber min={1} max={10} style={{ width: 250 }} />
                </Form.Item>
              </Form.Item>
            )
          }
        </Form.Item>

        <Form.Item name="uploadType" label="上传方式">
          <Select>
            <OptGroup>
              <Select.Option value={0}>自定义上传</Select.Option>
              <Select.Option value={1}>网络路径</Select.Option>
            </OptGroup>
          </Select>
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.uploadType !== currentValues.uploadType
          }
        >
          {({ getFieldValue }) =>
            getFieldValue('uploadType') == '1' ? (
              <Form.Item name="netWorkUrl" label="网络路径">
                <Input placeholder="网络路径" />
              </Form.Item>
            ) : (
              <Form.Item style={{ height: 100 }}>
                <Upload
                  {...uploadProps}
                >
                  <Button icon={<UploadOutlined />}>上传</Button>
                </Upload>
              </Form.Item>
            )
          }
        </Form.Item>

        <Form.Item>
          <span style={{ color: '#FF0000', marginLeft: 70 }}>
            注: 网络路径上传图片时，多张图片规则请用 &nbsp;|&nbsp; 隔开。 &nbsp;&nbsp; 如：1.xxxxxx.jpg|2.xxxxxx.jpg
          </span>
        </Form.Item>

        <Form.Item name="imageUrl" label="图片地址" hidden={true} >
          <Input placeholder="图片地址" />
        </Form.Item>

        <Form.Item name="videoUrl" label="视频地址" hidden={true}  >
          <Input placeholder="视频地址" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ float: 'right' }}>
            保存
          </Button>
        </Form.Item>

      </Form>
    </Modal >
  );
};

export default CreateForm;
