/* eslint-disable */
/* eslint-disable prefer-destructuring */
/* eslint no-dupe-keys: 0, no-mixed-operators: 0 */
import React from 'react';
import { Button, Toast } from 'antd-mobile-v2';
import 'antd-mobile-v2/dist/antd-mobile.css';
import weixin from 'weixin-js-sdk';
import logo from '@/assets/footer_logo.png';
import * as commonUtils from '../../utils/utils';
import CommobileClassifyEvent from '../common/CommobileClassifyEvent';
import CommobileBase from '../common/CommobileBase';
import  commonConfig from '../../utils/config';
import * as commonServices from '../../services/services';
import preView from '../components/preView';
import styles from './fileManage.less';


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();
   }

  // 上传图片
  //  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) {
                   /* 通过文件名拿到文件地址222 */
                   const fileName = dataReturn[0].fileName;
                   const filePath = dataReturn[0].filePath;
                   /* 上传到通用文件管理中 */
                   const imgObj = {};
                   imgObj.filePath = filePath;
                   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);
    }
  }

  handleGetWxCode = async (successHandler) => {
    let scanResult = '';
    const { app } = this.props;
    // eslint-disable-next-line prefer-destructuring,no-unused-vars
    const userinfo = app.userinfo;
    // const myUrl = `http://${location.host}/index.html`;
    const myUrl = location.href.split("#")[0];
    // const myUrl = 'http://sztlerp.gnway.vip:62665/index.html';
    const configUrl = `${commonConfig.server_host}wechat/getWxToken`;
    const values = {
      url: myUrl,
      sBrandsId: userinfo.sBrandsId,
      sSubsidiaryId: userinfo.sSubsidiaryId,
    };
    const configReturn = (await commonServices.postValueService(null, values, configUrl)).data;
    if (configReturn.code === 1) {
      const { rows } = configReturn.dataset;/* 获取费用分摊单据配置 */
      if (commonUtils.isNotEmptyArr(rows)) {
        const appId = rows[0].appId.toString();
        const nonceStr = rows[0].nonceStr.toString();
        const signature = rows[0].signature.toString();
        const timestamp = rows[0].timestamp.toString();
        // alert(appId);
        // Toast.fail(`1-获取TokenAppId！${appId}`);
        weixin.config({
          beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId, // 必填，公众号的唯一标识
          timestamp, // 必填，生成签名的时间戳    <%= Html.Encode(ViewData["timestamp" ]) %>
          nonceStr, // 必填，生成签名的随机串
          signature, // 必填，签名
          jsApiList: ['checkJsApi', 'scanQRCode', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getLocalImgData'], // 必填，需要使用的JS接口列表, 这里只需要调用扫一扫
        });
        weixin.ready(() => {
          weixin.checkJsApi({ // 判断当前客户端版本是否支持指定JS接口222
            jsApiList: ['scanQRCode', 'chooseImage'],
            success(res) { // 以键值对的形式返回，可用true，不可用false。如：{"checkResult":{"scanQRCode":true},"errMsg":"checkJsApi:ok"}
              // Toast.fail(`成功校验:${res}`);
            },
            // eslint-disable-next-line no-unused-vars
            fail(res) { // 检测getNetworkType该功能失败时处理
              Toast.fail('checkJsApi error');
            },


          }); // wx.ready结束
          weixin.chooseImage({
            count: 9, // 默认9  一共选择图片数量
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success(res) {
              const localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
              // const imgHtml = '';
              let imgUrl = localIds[0];
              // Toast.fail(`2-选定照片的本地src！${imgUrl}`);
              // eslint-disable-next-line no-plusplus
              // for (let i = 0; i < localIds.length; i++) {
                // 选择照片展示
                // imgHtml = `${imgHtml}<img src="${localIds[i]}"><br>`;
                // successHandler(localIds[i]);
              // imgUrl = localIds[i];
                // imgHtml+fnGetLocalImgData(localIds[i]);
              // }
              // imgUrl = localIds[0];
              // const base64Url = this.fnGetLocalImgData(imgUrl);
              // console.log('base1111', base64Url);
              successHandler(imgUrl);
            },
            fail(res) {
              Toast.fail(`照片上传失败！${res}`);
            },
          });
        });
      } else {
        Toast.fail(configReturn.msg);
      }
    } else {
      Toast.fail(configReturn.msg);
    }
    return scanResult;
  }

  /* 处理照片上传业务 */
  handleWxBusiness = async (localIds) => {
    const { sModelsId, token, app } = this.props;
    const { files } = this.state;
    this.fnGetLocalImgData(localIds, async (base64Url) => {
      if(commonUtils.isNotEmptyObject(base64Url)) {
        const dataUrl = `${commonConfig.file_host}file/mobileuploadwechat?sModelsId=${sModelsId}&token=${token}`;
        /*  将二进制地址存储到数据中 */
        const value ={ picUrl : [base64Url]};
        const returnData = (await commonServices.postValueService(app.token, value, dataUrl)).data;
        /* 拿到上传返回的数据库地址 */
        const dataReturn = returnData.dataset.rows;
        if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
          /* 通过文件名拿到文件地址 */
          const sFileName = dataReturn[0].fileName;
          const sFilePath = dataReturn[0].filePath;
          // Toast.fail(`3-照片上传成功后！${sFileName}`);
          /* 上传到通用文件管理中 */
          if(commonUtils.isNotEmptyObject(sFileName) && commonUtils.isNotEmptyObject(sFilePath)) {
            const imgObj = {};
            imgObj.filePath = sFilePath;
            imgObj.fileName = sFileName;
            files.push(imgObj);
            this.handleUploadImage(imgObj);
          }
        }
      }
    });
  }

  fnGetLocalImgData = (localID, successHandler ) => {
    weixin.getLocalImgData({
      localId: localID, // 图片的localID
      success: (res) => {
        let baseUrL = '';
        let { localData } = res; //  localData是图片的base64数据，可以用img标签显示
        // if (localData.startsWith('data:image')) { // 判断是否有这样的头部
        //   // 没有则加上头部
        //   localData = `data:image/jpeg;base64,${localData}`;
        // }
        // 去掉所以换行符
        localData = localData.replace(/\r|\n/g, '');
        // return `<img src="${localData}"><br>`;
        baseUrL =  localData;
        successHandler(baseUrL);
      },
    });
  }

  /* 微信拍照 */
  handleWxPhoto = async () => {
    this.handleGetWxCode((code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleWxBusiness(code);
      }
    });
  }

  /* 微信二进制 */
  handleWxPhotoScream = async () => {
    this.handleGetWxCode((code) => {
      if (!commonUtils.isEmpty(code)) {
        this.handleWxBusiness(code);
      }
    });
  }

  // /* 图片上传入库 */
  handleUploadImage = (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();/* 通用保存 */
    }
  }

  readAsDataURL = async()=> {
     const { sModelsId, token, app } = this.props;
     let { slaveData } = this.props;
     let { imageData } = this.state;
     const files = [];
    //检验是否为图像文件
    var file = document.getElementById("file").files[0];
    if (!/image\/\w+/.test(file.type)) {
      alert("看清楚，这个需要图片！");
      return false;
    }
    const onUploadImage = this.handleUploadImage;
    var reader = new FileReader();
    //将文件以Data URL形式读入页面
    reader.readAsDataURL(file);
    reader.onload = async function (e) {
      const urlArr = [reader.result];
      const dataUrl = `${commonConfig.server_host}file/mobileuploadwechat?sModelsId=${sModelsId}&token=${token}`;
      /*  将二进制地址存储到数据中 */
      const value ={ picUrl : urlArr};
      const returnData = (await commonServices.postValueService(app.token, value, dataUrl)).data;
      /* 拿到上传返回的数据库地址 */
      const dataReturn = returnData.dataset.rows;
      if (commonUtils.isNotEmptyArr(dataReturn) && dataReturn.length > 0) {
        /* 通过文件名拿到文件地址 */
        const sFileName = dataReturn[0].fileName;
        const sFilePath = dataReturn[0].filePath;
        /* 上传到通用文件管理中 */
        if(commonUtils.isNotEmptyObject(sFileName) && commonUtils.isNotEmptyObject(sFilePath)) {
          const imgObj = {};
          imgObj.filePath = sFilePath;
          imgObj.fileName = sFileName;
          files.push(imgObj);
          onUploadImage(imgObj);
        }
      }
    }
  }

  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; /* 获取手机视窗宽度 */
    /* 上传照片样式定位 */
    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.server_host}file/download?savePathStr=${item}&width=${dWidth}&&height=${dHeight}&sModelsId=100&token=${token}`; /* 预览 */
                      previewImageArr.push(dataPreviewUrl);
                    });
                    const dataUrl = `${commonConfig.server_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 type="button" inline disabled={false} onClick={() => this.handleUploadPhoto('slave')} style={btnStyle}>*/}
          {/*  上传图片*/}
          {/*</Button>*/}
          <Button type="button" inline disabled={false} onClick={() => this.handleWxPhoto()} style={btnStyle}>
            上传图片
          </Button>
          {/*<input type="file" id="file"/>*/}
          {/*<Button type="button" onClick={() => this.readAsDataURL()} >读取图片</Button>*/}
          {/*<div id="result" ></div>*/}
          {/* <Button */}
          {/*  inline */}
          {/*  style={btnStyle} */}
          {/*  // disabled={!enabled} */}
          {/*  onClick={() => */}
          {/*    Modal.alert('', <div />, [ */}
          {/*      { text: '拍照', onPress: () => this.handleWxPhoto('BtnCamera') }, */}
          {/*    ]) */}
          {/*  } */}
          {/* >{btnUpdConfig.showName} */}
          {/* </Button> */}
        </div>
        }
      </div>

    );
  }
}

export default CommobileBase(CommobileClassifyEvent(FileManageMobile));
