import React, { useState, useEffect } from 'react';
import styles from './ContractContent.less';
import { Input, Form, message, Upload, DatePicker, Pagination, Modal, Spin, Image } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import { connect, history } from 'umi';

import LINE from '../../components/Line/Line';

const { TextArea } = Input;

import PDF from 'react-pdf-js';
import moment from 'moment';
import './ContractContent.less';

import SearchOptionsCommnity from '@/components/SearchOptions/SearchOptionsCommnity';
import { tipList } from '@/utils/tip';

import FileViewer from 'react-file-viewer';

const ContractContent = (props: any) => {
  const { Contract, dispatch, FileImg, loading } = props;

  const { DataSaveDetail } = Contract;
  const { RangePicker } = DatePicker; // 日期组件
  const [form] = Form.useForm(); // 表单
  const RA = (index: any, values: any) => {
    dispatch({ type: 'Contract/RA', playload: { index: index, body: values } });
  };

  // 设置之前时间不能选择
  function disabledDate(current: any) {
    return current && current <= moment().subtract(1, 'days').endOf('day');
  }

  const [fileList, setFileList] = useState([] as any); // 图片列表
  const [uploadUp, setUploadUp] = useState(true); // 禁止上传 直到选择了小区后
  const [comtyName, setComtyName] = useState(null); // 小区名字
  const [tipTime, setTipTime] = useState(['previous month', 'two months'] as any); //提示时间
  const [tipModal, settipModal] = useState(false); //附件弹窗
  const [fileInfo, setfileInfo] = useState(null as any); //附件内容
  //pdf 页码内容
  const [numPages, setNumPages] = useState(1 as any); // 总页码数
  const [pageNumber, setPageNumber] = useState(1); // 当前页码数

  const [imgInfo, setimgInfo] = useState(null as any); //本地图片预览
  const [previewVisible, setPreviewVisible] = useState(false); //本地图片预览弹窗

  useEffect(() => {
    // 如果是添加传来没有值的时候 就清空  否则  赋值给表单
    if (DataSaveDetail == null) {
      // 清空表单
      // form.resetFields();
      history.push('/ContractManagement');
    } else {
      // 发起图片请求
      let objData = {
        type: 'tosContractPreview',
        fileName: DataSaveDetail.contractFileName,
        extends: DataSaveDetail.communityName,
      };
      RA(47, objData);

      // 打开禁止
      setUploadUp(false);

      // 提示时间
      let a1 = moment(DataSaveDetail.contractValidEndDate)
        .subtract(2, 'month')
        .format('YYYY-MM-DD');
      let a2 = moment(DataSaveDetail.contractValidEndDate)
        .subtract(1, 'month')
        .format('YYYY-MM-DD');
      setTipTime([a1, a2]);

      // 给到上传绑定
      setComtyName(DataSaveDetail.communityName);
      // 表单内容
      form.setFieldsValue({
        ...DataSaveDetail,
        upload: 'ok',
        time: [
          moment(DataSaveDetail.contractValidStartDate),
          moment(DataSaveDetail.contractValidEndDate),
        ],
      });
    }
  }, [DataSaveDetail]);

  // 监听上传图片列表
  useEffect(() => {
    if (FileImg != null) {
      let obj = new Array();
      for (var i in FileImg) {
        let a = {
          uid: i,
          name: FileImg[i].fileName,
          status: 'done',
          type: FileImg[i].fileName.match(/\.([^\.]+)$/)[1].toLowerCase(),
          url: FileImg[i].fileUrl,
        };
        console.log();
        obj.push(a);
      }
      setFileList([...obj]);
    } else {
      setFileList([]);
    }
  }, [FileImg]);

  // 监听列表
  useEffect(() => {
    if (fileList.length == 0) {
      form.setFieldsValue['upload'] = null;
    }
  }, [fileList]);

  // 返回
  const goToReturn = () => {
    // console.log(fileList)
    history.go(-1);
  };

  // 上传文件设置
  const uploadProps = {
    accept: '.docx,.jpg,.png,.pdf',
    action: '/tos/image/upload',
    data: { imageType: 'tosContract', extends: comtyName },
    fileList: fileList,
    onChange({ file, fileList }: { file: any; fileList: any }) {
      setFileList(fileList);

      // 添加到表单
      form.setFieldsValue({
        upload: 'ok',
      });

      if (file.status == 'done') {
        message.success(file.name, 3);
      }
    },
  };

  //本地图预览处理
  function getBase64(file: any) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }

  //点击预览
  const onPreviews = async (file: any) => {
    // 有值的话  就是本地预览
    if (file.size) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      let info = {
        previewImage: file.url || file.preview,
        previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
      };
      setPreviewVisible(true); // 弹窗
      setimgInfo(info); // 图片信息
    } else {
      setfileInfo(file); // 设置选择的文件
      console.log(file);
      settipModal(true);
    }
  };

  // 关闭预览弹窗
  const handleCancel = () => {
    settipModal(false);
  };

  // pdf 总页数
  const onDocumentLoadSuccess = (pages: any) => {
    setNumPages(pages);
  };

  // 切换pdf 总数
  const onChangePage = (page: any) => {
    setPageNumber(page);
  };

  return (
    <>
      <Spin spinning={loading}>
        <div className={styles.base}>
          {/* 头部组件 */}
          <div className={styles.box}>
            <div className={styles.item1}>{DataSaveDetail ? 'Detail' : 'Add'} Contract</div>
            <button className={styles.item3} onClick={goToReturn}>
              <LeftOutlined />
              Back
            </button>
          </div>
          {/* 表单  initialValues={defForm} */}
          <Form
            // ref={formRef}
            autoComplete="off"
            form={form}
            name="basic"
            initialValues={DataSaveDetail}
          >
            <div className="contract_box">
              <div className="list2">
                <Form.Item
                  name="contractNumber"
                  label="Contract Number"
                  rules={[{ required: true, message: `${tipList[0]}` }]}
                >
                  <Input style={{ width: 200 }} disabled placeholder="Contract Number" />
                </Form.Item>
              </div>
              {/* 合同编号、甲方、乙方 */}
              <div className="list_1">
                <div className="item_1">
                  <Form.Item
                    name="contractPartyA"
                    label="Contract Party A"
                    rules={[{ required: true, message: `${tipList[1]}` }]}
                  >
                    <Input style={{ width: 300 }} disabled placeholder="Contract Party A" />
                  </Form.Item>
                </div>
                <div className="item_1">
                  <Form.Item
                    name="contractPartyB"
                    label="Contract Party B"
                    rules={[{ required: true, message: `${tipList[2]}` }]}
                  >
                    <Input style={{ width: 300 }} disabled placeholder="Contract Party B" />
                  </Form.Item>
                </div>
              </div>
              {/* 小区 */}
              <div className="list2">
                <div className="main">
                  <Form.Item
                    labelAlign="right"
                    name="communityName"
                    label="Community Name"
                    rules={[{ required: true, message: `${tipList[3]}` }]}
                  >
                    <SearchOptionsCommnity
                      defaultName={DataSaveDetail ? DataSaveDetail.communityName : null}
                      disabled={true}
                    />
                  </Form.Item>
                </div>
              </div>
              {/* 合同标题 */}
              <div className="list2">
                <Form.Item
                  labelAlign="right"
                  name="contractTitle"
                  label="Contract Title"
                  rules={[{ required: true, message: `${tipList[4]}` }]}
                >
                  <Input style={{ width: 500 }} disabled placeholder="Contract Title" />
                </Form.Item>
              </div>

              {/* 起止时间 */}
              <div className="list2">
                <Form.Item
                  name="time"
                  labelAlign="right"
                  label="Contract Time"
                  rules={[{ required: true, message: `${tipList[5]}` }]}
                >
                  <RangePicker
                    defaultValue={DataSaveDetail ? DataSaveDetail.time : null}
                    disabledDate={disabledDate}
                    placeholder={['Effective Date', 'Expiration Date']}
                    disabled
                  />
                </Form.Item>
              </div>

              {/* 附件上传 */}
              <div className="list2">
                <Form.Item
                  labelAlign="right"
                  name="upload"
                  label="Contract Annex"
                  rules={[{ required: true, message: `Please upload the attachment!` }]}
                >
                  <Upload
                    {...uploadProps}
                    listType={'picture-card'}
                    disabled={true}
                    onPreview={onPreviews}
                  ></Upload>
                </Form.Item>
              </div>

              {/* 合同内容 */}
              <div className="list2">
                <div className={styles.box8item2x1}>
                  <Form.Item
                    rules={[{ required: true, message: `${tipList[5]}` }]}
                    label="Contract Remarks"
                    name="contractRemindContent"
                    style={{ marginBottom: 0 }}
                  >
                    <TextArea
                      style={{ padding: 8, width: 600 }}
                      placeholder="Remarks"
                      showCount={true}
                      disabled
                      autoSize={{ minRows: 6, maxRows: 6 }}
                    ></TextArea>
                  </Form.Item>
                </div>
                <div
                  className={styles.box8item2x2}
                  style={{ marginLeft: 150, textTransform: 'capitalize' }}
                >
                  <p style={{ marginBottom: 0 }}>
                    The system will send e-mail notification in the{' '}
                    <span style={{ color: 'red' }}>{tipTime[0]}</span> and{' '}
                    <span style={{ color: 'red' }}>{tipTime[1]}</span> that the contract is about to
                    expire !
                  </p>
                  <p style={{ marginBottom: 0 }}>
                    <span style={{ color: 'red' }}>*</span> If the time has passed, it will not be
                    sent
                  </p>
                </div>
              </div>

              <div>
                <LINE />
              </div>
            </div>
          </Form>

          {/* 附件预览 */}
          <Modal
            title="File Preview"
            visible={tipModal}
            width={800}
            onCancel={handleCancel}
            style={{ textAlign: 'center' }}
            footer={null}
          >
            {fileInfo != null ? (
              fileInfo.type == 'pdf' ? (
                // pdf 换一种
                <>
                  <PDF
                    file={fileInfo.url}
                    page={pageNumber}
                    scale={1.25}
                    onDocumentComplete={onDocumentLoadSuccess}
                  />
                  <Pagination
                    style={{ textAlign: 'center', marginTop: 10, display: 'block' }}
                    simple
                    defaultCurrent={pageNumber}
                    total={numPages * 10}
                    onChange={onChangePage}
                  />
                </>
              ) : fileInfo.type == 'jpg' || fileInfo.type == 'png' ? (
                // 图片用指定格式

                <Image
                  src={fileInfo.url}
                  preview={false}
                  style={{ margin: '0 auto', textAlign: 'center' }}
                />
              ) : (
                <FileViewer fileType={fileInfo.type} filePath={fileInfo.url} />
              )
            ) : (
              ''
            )}
          </Modal>

          {/* 本地附件预览 */}
          {imgInfo != null ? (
            <Modal
              visible={previewVisible}
              title={imgInfo.previewTitle}
              footer={null}
              onCancel={() => {
                setPreviewVisible(false);
              }}
            >
              <img alt="example" style={{ width: '100%' }} src={imgInfo.previewImage} />
            </Modal>
          ) : (
            ''
          )}
        </div>
      </Spin>
    </>
  );
};

function mapStateToProps(state: any) {
  const { ContractModel, Contract } = state;
  const FileImg = Contract.FileImg;
  const loading = state.loading.models.Contract || false;
  return {
    ContractModel,
    Contract,
    FileImg,
    loading,
  };
}
export default connect(mapStateToProps)(ContractContent);
