import React, { useState, useEffect } from 'react';
import { Upload, Input, Modal, Menu, Dropdown, Button, Icon, message, Table, Divider, Tag, Select, Form, Alert } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import XForm, { FieldTypes } from '../../../components/XForm';
import router from 'umi/router';
import apis from '../../../services/apis';
import request from '../../../utils/request';
import { fetch } from '../../../utils/request';
import moment from 'moment';

const header = props => {

  const [data, setData] = useState({})
  const [flag, setFlag] = useState({})
  const [uploadTip, setUploadTip] = useState({})
  const [loading, setLoading] = useState({})
  const uploadFile = fetch(apis.image.upload)


  useEffect(() => {
    setFlag(false);
    setUploadTip("请选择合同文件")
    setLoading(false)
  }, []);

  const upload = () => {
    console.log("上传")
  }

  const removeFile = () => {
    console.log("删除文件")
  }

  const uploaderProps = {
    name: 'file',
    accept: '.pdf',
    showUploadList: true,
    customRequest({
      action,
      file,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {
      const data = new FormData()
      data.append('file', file)

      uploadFile({ data }).then((img) => {
        setFlag(true)
        setUploadTip("上传成功")
        setData({
          contractTemplateAddress: img
        })
        onSuccess(img, file)
      }).catch(onError);

      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    },
    onRemove(file) {
      setFlag(false)
      setUploadTip("请选择合同文件")
    }
  }

  const fields = [
    {
      label: '合同标题',
      name: 'contractTemplateName',
      type: FieldTypes.Text,
      value: data.contractTemplateName,
      rules: [
        { required: true, message: '标题长度20字以内不能有空格', pattern: new RegExp('^[^ ]+$') },
        { max: 20, message: '标题长度不能超过20个字符' }
      ],
      placeholder: "标题长度20字以内不能有空格"
    },
    {
      label: '合同文件',
      name: 'contractTemplateAddress',
      // type: FieldTypes.text,
      value: data.contractTemplateAddress,
      // beforeUpload: (e) => photoBeforeUpload(e),
      rules: [
        { required: true, message: '请选择合同文件' },
      ],
      render: <div><Upload beforeUpload={beforeUpload} {...uploaderProps}><Button disabled={flag}>{uploadTip}</Button></Upload></div>,
      help: <div>仅支持pdf格式，合同必须按规则生成，否则无法正确签章。未按规则生成合同导致的问题，致云免除相关责任。详细要求查看
        <a href='https://easydoc.xyz/s/24703398/3SqDkJDw/odnmIIwl' style={{ color: '#66B3FF' }} target='_blank'>《合同模板制作要求》</a></div>
    },

  ]

  function beforeUpload(file) {
    console.log(file, 'file')
    return new Promise((resolve, reject) => {
      if (file.type === 'application/pdf') {
          resolve(file)
      } else {
        message.info('仅支持PDF格式')
        reject()
      }
    })
  }  

  const handleSubmit = (values) => {
    let submitValues = values;
    submitValues.contractTemplateAddress = data.contractTemplateAddress

    props.form.validateFields((err, values) => {
      console.log(values)
      if (!err) {
        request({ ...apis.taEcontract.addContractTemplate, data: { ...submitValues }, }).then((data) => {
          router.push({
            pathname: '/eContract/template/list',
            query: {
              //   salesBatchId: data.salesBatchId,
            },
          });
        }).catch((err) => {
          message.info(err.msg || err.message)
        })
      }
    });
  }
  //model
  const handleShowModel = val => {
    setVisible(true);
  }

  const handleCancel = val => {
    setVisible(false);
  }

  const cancelPage = () => {
    router.push({
      pathname: '/eContract/template/list',
    });
  }

  return (
    <>
      <div>
        <XForm onSubmit={handleSubmit} onCancel={cancelPage} fields={fields}></XForm>
      </div>
    </>
  )
}

const WrappedNormalLoginForm = Form.create({ name: 'header' })(header);
export default WrappedNormalLoginForm