/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { Button, Modal } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import * as commonUtils from '../../utils/utils';
import CommobileClassifyEvent from '../common/CommobileClassifyEvent';
import CommobileBase from '../common/CommobileBase';
import commonConfig from '../../utils/config';
import preView from '../components/preView';
import styles from './fileManage.less';
import * as commonFunc from "@/components/Common/commonFunc";

class FileManageMobile extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      files: [], // 图片存放的数组 可以上传一个，或者多个图片
      imageData: [],
    };
  }

  /* 调用手机摄像头并拍照 */
   getImage =() => {
     const { plus } = window;
     const cmr = plus.camera.getCamera();
     cmr.captureImage((p) => {
       plus.io.resolveLocalFileSystemURL(p, (entry) => {
         this.startUpload(entry.toLocalURL(), entry.name);
       }, (e) => {
         plus.nativeUI.toast(`读取拍照文件错误：${e.message}`);
       });
     }, (e) => {
       plus.nativeUI.toast(`调用摄像头错误：${e.message}`);
     }, {
       filter: 'image',
     });
   }

  /* 相册选择图片 */
   getPhoto =() => {
     const { plus } = window;
     plus.gallery.pick((path) => {
       const name = path.substring(path.lastIndexOf('/') + 1);
       this.startUpload(path, name);
     }, (e) => {
       plus.nativeUI.toast(`选取图片错误：${e.message}`);
     }, { filter: 'image' });
   }

  showImgDetail = (imgId, imgkey, id, src) => {
    let html = '';
    html += `<div  id="Img${imgId}${imgkey}" class="image-item ">`;
    html += `   <img id="picBig" data-preview-src="" data-preview-group="1" ${src}  />`;
    html += `    <span class="del" onclick="delImg('${imgId}','${imgkey}',${id});">`;
    html += '        <div class="fa fa-times-circle"></div>';
    html += '    </span>';
    html += '</div>';
    document.getElementById('imgDiv').innerHTML = html;
  }

  // 压缩图片
  compressImage =(url, filename, divid) => {
    const { plus } = window;
    const name = `_doc/upload/${divid}-${filename}`;// _doc/upload/F_ZDDZZ-1467602809090.jpg
    plus.zip.compressImage(
      {
        src: url, // src: (String 类型 )压缩转换原始图片的路径
        dst: name, // 压缩转换目标图片的路径
        quality: 20, // quality: (Number 类型 )压缩图片的质量.取值范围为1-100
        overwrite: true, // overwrite: (Boolean 类型 )覆盖生成新文件
      },
      (event) => {
      // uploadf(event.target,divid);
        const path = name;// 压缩转换目标图片的路径
        // event.target获取压缩转换后的图片url路
        // filename图片名称
        this.saveimage(event.target, divid, filename, path);
      }, (error) => {
        plus.nativeUI.toast(`${error}压缩图片失败，请稍候再试`);
      },
    );
  }


  // 保存信息到本地
  /**
   *
   * @param {Object} url  图片的地址
   * @param {Object} divid  字段的名称
   * @param {Object} name   图片的名称
   */
   saveimage = (url, divid, name, path) => {
     const { plus } = window;
     // alert(url);//file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg
     // alert(path);//_doc/upload/F_ZDDZZ-1467602809090.jpg
     // const state = 0;
     const wt = plus.nativeUI.showWaiting();
     //  plus.storage.clear();
     name = name.substring(0, name.indexOf('.'));// 图片名称：1467602809090
     const id = document.getElementById('ckjl.id').value;
     const itemname = `${id}img-${divid}`;// 429img-F_ZDDZ
     let itemvalue = plus.storage.getItem(itemname);
     if (itemvalue == null) {
       itemvalue = `{${name},${path},${url}}`;// {IMG_20160704_112614,_doc/upload/F_ZDDZZ-IMG_20160704_112614.jpg,file:///storage/emulated/0/Android/data/io.dcloud...../doc/upload/F_ZDDZZ-1467602809090.jpg}
     } else {
       itemvalue = `${itemvalue}{${name},${path},${url}}`;
     }
     plus.storage.setItem(itemname, itemvalue);

     const src = `src="${url}"`;
     this.showImgDetail(name, divid, id, src);
     wt.close();
   }
  // /* 图片上传入库 */
   uploadImage =(imageObj) => {
     if (commonUtils.isNotEmptyObject(imageObj) && commonUtils.isNotEmptyObject(imageObj.filePath)) {
       /* -封装slaveData */
       const name = 'slave';
       const { app } = this.props;
       let { slaveData } = this.props;
       let { imageData } = this.state;
       if (commonUtils.isEmpty(slaveData) || commonUtils.isEmpty(imageData)) {
         slaveData = [];
         imageData = [];
       }
       const { currentPane } = app;
       /* 上传图片 */
       const tableDataRow = this.props.onDataRowAdd(name, true);/* 选中行 */
       tableDataRow.iOrder = 0;
       tableDataRow.sSrcNo = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcNo : '';
       tableDataRow.sSrcFormId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcFormId : '';
       tableDataRow.sSrcId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcId : '';
       tableDataRow.sSrcSlaveId = commonUtils.isNotEmptyObject(currentPane) ? currentPane.sSrcSlaveId : '';
       tableDataRow.sPicturePath = imageObj.filePath;
       tableDataRow.sFileName = imageObj.fileName;
       if (commonUtils.isNotEmptyObject(imageObj.filePath)) {
         imageData.push(imageObj.filePath);
       }
       slaveData.push(tableDataRow);
       this.props.onSaveState({ slaveData, imageData });
       this.props.onSubmit();/* 通用保存 */
     }
   }

  // 上传图片
  //  upload_img = (p) => {
  //    // 又初始化了一下文件数组 为了支持单个上传,如果你要一次上传多个，就不要在写这一行了
  //    // 注意
  //    // files=[];
  //    const n = p.substr(p.lastIndexOf('/') + 1);
  //    files.push({
  //      name: `name${files.length}`,
  //      path: p,
  //    });
  //  }

   startUpload =(path, filename) => {
     const { files } = this.state;
     const { sModelsId, token } = this.props;
     const { plus } = window;
     // if (files.length <= 0) {
     //   plus.nativeUI.alert('没有添加上传文件！');
     //   return;
     // }

     // 原生的转圈等待框
     const wt = plus.nativeUI.showWaiting();

     const task = plus.uploader.createUpload(
       `${commonConfig.file_host}file/mobileupload?sModelsId=${sModelsId}&token=${token}`, {
         method: 'POST',
       },
       (t, status) => { // 上传完成
         if (status === 200) {
           // 关闭转圈等待框
           wt.close();
           if (commonUtils.isNotEmptyObject(t.responseText)) {
             try {
               const responseObj = JSON.parse(t.responseText);
               if (commonUtils.isNotEmptyObject(responseObj) && responseObj.code === 1) {
                 /* 拿到上传返回的数据库地址 */
                 const dataReturn = responseObj.dataset.rows;
                 if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
                   /* 通过文件名拿到文件地址 */
                   const sPicturePath = dataReturn[0][filename];
                   /* 上传到通用文件管理中 */
                   const imgObj = {};
                   imgObj.filePath = sPicturePath;
                   imgObj.fileName = filename;
                   files.push(imgObj);
                   this.uploadImage(imgObj);
                 }
               } else {
                 alert(responseObj.msg);
               }
             } catch (e) {
               alert(`解析地址失败：${e}`);
             }
           }
           // window.location.reload();
         } else {
           alert(`上传失败：${status}`);
           // 关闭原生的转圈等待框
           wt.close();
         }
       },
     );

     task.addData('string_key', 'string_value'); // 可以向后台传值
     task.addFile(path, { key: 'testimage' });
     task.start();
   }


  handleClick =(name) => {
    if (name === 'BtnCamera') { /* 手机调动摄像头拍照 */
      this.getImage();
    } else if (name === 'BtnPhoto') { /* 手机相册选择图片 */
      this.getPhoto();
    } else if (name === 'BtnCancel') {
      window.history.back(-1);
    }
  }


  render() {
    const {
      config: btnUpdConfig, btnStyle, app,
    } = this.props;
    const { files } = this.state;
    const dWidth = document.documentElement.clientWidth || document.body.clientWidth; /* 获取手机视窗宽度 */
    const dHeight = document.documentElement.clientHeight || document.body.clientHeight; /* 获取手机视窗宽度 */

    const btnCamera = commonFunc.showLocalMessage(this.props, 'btnCamera', '拍照');

    const album = commonFunc.showLocalMessage(this.props, 'Album', '相册');

    const btnCancel = commonFunc.showLocalMessage(this.props, 'btnCancel', '取消');

    /* 上传照片样式定位 */
    let imgDivTop = '500';
    const mobileBarStyle = document.getElementsByClassName('am-list-view-scrollview-content');
    if (commonUtils.isNotEmptyArr(mobileBarStyle) && mobileBarStyle.length > 0) {
      const obj = mobileBarStyle[0].getBoundingClientRect();
      const objHeight = mobileBarStyle[0].clientHeight;
      if (commonUtils.isEmptyObject(obj)) {
        if (obj.top < dHeight) {
          imgDivTop = Math.floor(obj.top + objHeight);
        }
      }
    }

    return (
      <div>
        {commonUtils.isEmptyObject(btnUpdConfig) ? '' :
        <div className="content">
          <div className={styles.commonImage} id="imgDiv" key="imgDivKey" style={{ top: imgDivTop }}>
            {
              commonUtils.isNotEmptyArr(files) && files.length > 0 ?
                files.map((child) => {
                if (commonUtils.isNotEmptyObject(child.filePath)) {
                  const { token } = app;
                  let imgBox = '';
                  const picAddr = commonUtils.isNotEmptyObject(child.filePath) ? child.filePath.split(',') : '';
                  const previewImageArr = [];
                  if (commonUtils.isNotEmptyArr(picAddr)) {
                    picAddr.forEach((item) => {
                      const dataPreviewUrl = `${commonConfig.file_host}file/download?savePathStr=${item}&width=${dWidth}&&height=${dHeight}&sModelsId=100&token=${token}`; /* 预览 */
                      previewImageArr.push(dataPreviewUrl);
                    });
                    const dataUrl = `${commonConfig.file_host}file/download?savePathStr=${picAddr[0]}&width=80&&height=80&sModelsId=100&token=${token}`; /* 缩略图 */
                    // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
                    imgBox = <img src={dataUrl} alt="img" onFocus={() => 0} onClick={e => preView(previewImageArr, e)} />;
                  }
                  return imgBox;
                } else {
                  return '';
                }
              }) : ''
            }
          </div>
          <Button
            inline
            style={btnStyle}
            // disabled={!enabled}
            onClick={() =>
              Modal.alert('', <div />, [
                { text: btnCamera, onPress: () => this.handleClick('BtnCamera') },
                { text: album, onPress: () => this.handleClick('BtnPhoto') },
                { text: btnCancel, onPress: () => this.handleClick.bind(this, 'BtnCancel') },
              ])
            }
          >{btnUpdConfig.showName}
          </Button>
        </div>
        }
      </div>

    );
  }
}

export default CommobileBase(CommobileClassifyEvent(FileManageMobile));
