<template>
  <view :class="isUps == true ? 'prevent' : ''">
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText" v-c>返回</block>
      <block slot="content">点位检查照片</block>
    </cu-custom>
    <scroll-view scroll-y="false">
      <view class="form">
        <view class="cu-bar bg-white margin-top">
          <view class="action">
            检查照片
          </view>
          <view class="action">
            {{imgList.length}}/1
          </view>
        </view>
        <view class="cu-form-group">
          <view class="grid col-1 grid-square flex-sub">
            <view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" data-type="0"
                  :data-url="imgList[index].filePath">
              <image :src="imgList[index].filePath" mode="aspectFill"></image>
              <view v-if="ISLOG == 0" class="cu-tag bg-red" @tap.stop="DelImg" data-type="0"
                    :data-index="index">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap="ChooseImage(0)" v-if="imgList.length<1 && ISLOG == 0">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>

        </view>
      </view>
      <view v-if="ISLOG == '0'" class="padding flex flex-direction">
        <button class="cu-btn bg-blue margin-tb-sm lg" @click="$noMultipleClicks(goSubmit)">保存照片</button>
      </view>
    </scroll-view>
    <view style="width: 0;height: 0;overflow: hidden;position:fixed;left: 200%;">
      <canvas canvas-id="firstCanvas" :style="{border:'1px solid #000000',width: width,height: height}"
              class="canvas"></canvas>
    </view>
  </view>
</template>

<script>
import {
  basePath,
  corpinfoId,
  deptId,
  loginUser,
  formatDate,
  loginSession,
  baseImgPath
} from '@/common/tool.js';
import tkiTree from "@/components/select-tree/select-tree.vue"
import gcoord from '@/common/gcoord.js'
export default {
  components: {
    tkiTree
  },
  data() {
    return {
      isUps: false,
      EQUIPMENT_POINT_ID: '',
      ISLOG: '',
      index: '',
      noClick: true,
      imgList: [],
      width: '',
      height: ''
    }
  },
  onLoad(event) {
    this.EQUIPMENT_POINT_ID = event.EQUIPMENT_POINT_ID;
    this.ISLOG = event.ISLOG
    this.getData();
  },
  methods: {
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/imgfiles/listImgs',
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          FOREIGN_KEY: _this.EQUIPMENT_POINT_ID,
          TYPE: 14
        },
        success: (res) => {
          if ("success" == res.data.result) {
            uni.hideLoading();
            let files = res.data.imgs;
            for (var i = 0; i < files.length; i++) {
              let img = {};
              img.filePath = baseImgPath + files[i].FILEPATH;
              img.id = files[i].IMGFILES_ID;
              _this.imgList.push(img);
            }
          } else if ("exception" == data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    //图片上传
    ChooseImage(e) {
      var _this = this;
      if (this.imgList.length >= 1) {
        uni.showToast({
          title: '只能上传一张照片',
          icon: 'none'
        });
        return;
      }
      uni.chooseImage({
        count: 1, // 限制只能选择1张照片
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], //从相册选择
        success: (res) => {
          uni.showLoading({
            title: '加载中',
            mask: true
          })
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            this.setimg(res.tempFilePaths[i],e)
          }
        }
      });
    },

    setimg(path,e){
      var _this = this
      let newDate = new Date();
      let year = newDate.getFullYear() //年
      let month = newDate.getMonth() + 1 //月
      let day = newDate.getDate() //日
      const hour = newDate.getHours();
      const minute = newDate.getMinutes();
      const second = newDate.getSeconds();
      let date = year + '-' + month + '-' + day +
          '- ' + hour + ':' + minute + ':' + second
      uni.getImageInfo({
        src: path,
        success: res => {
          // console.log(res);
          this.width = res.width/3 + 'px';
          this.height = res.height/3 + 'px';
          // if (res.width < 800) {
          //   uni.hideLoading()
          //   uni.showToast({
          //     title: '图片尺寸不能小于800',
          //     icon: 'none'
          //   })
          //   return
          // }
          //初始化画布
          const ctx = uni.createCanvasContext('firstCanvas', this);
          ctx.fillRect(0, 0, res.width, res.height);
          ctx.drawImage(res.path, 0, 0, res.width/3, res.height/3);   //将图片src放到cancas内，宽高为图片大小
          ctx.setFontSize(10);
          // ctx.globalAlpha = 1;
          ctx.setFillStyle('red');
          let textToWidth = (res.width/3) - 100;
          let textToHeight = (res.height/3) - 20;
          ctx.fillText(date, textToWidth, textToHeight);
          setTimeout(() => {// 这个不加异步 第一次的图片显示不出来
            ctx.draw(false, () => {
              setTimeout(() => {
                uni.canvasToTempFilePath({
                  canvasId: 'firstCanvas',//将画布中内容转成图片，即水印与图片合成
                  x: 0,
                  y: 0,
                  width: res.width,
                  height: res.height,
                  destWidth: res.width,
                  destHeight: res.height,
                  success: ress => {
                    if (e == 0 ) {
                      let img = {};
                      img.id = '';
                      img.filePath = ress.tempFilePath;
                      _this.imgList.push(img)
                      uni.hideLoading()
                    } else {
                      let img = {};
                      img.id = '';
                      img.filePath = ress.tempFilePath;
                      _this.imgList1.push(img)
                      uni.hideLoading()
                    }
                  },
                  fail: (err) => {
                    console.log(err);
                  }
                });
              }, 500);
            });
          },300);
        }
      });
    },
    ViewImage(e) {
      if (e.currentTarget.dataset.type == 0) {
        let files = [];
        for (var i = 0; i < this.imgList.length; i++) {
          files.push(this.imgList[i].filePath)
        }
        uni.previewImage({
          urls: files,
          current: e.currentTarget.dataset.url
        });
      } else {
        let files = [];
        for (var i = 0; i < this.imgList1.length; i++) {
          files.push(this.imgList1[i].filePath)
        }
        uni.previewImage({
          urls: files,
          current: e.currentTarget.dataset.url
        });
      }
    },
    DelImg(e) {
      var _this = this;
      let i = e.currentTarget.dataset.index
      uni.showModal({
        title: '秦港-双基双控',
        content: '确定要删除这张图片吗？',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            if (e.currentTarget.dataset.type == 0) {
              if (_this.imgList[i].id) {
                uni.showLoading({
                  title: '处理中'
                })
                uni.request({
                  url: basePath + '/app/imgfiles/delete',
                  method: 'POST',
                  dataType: 'json',
                  header: {
                    'Content-type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    IMGFILES_ID: _this.imgList[i].id,
                  },
                  success: (res) => {
                    uni.hideLoading();
                    uni.showToast({
                      icon: 'none',
                      title: '删除成功',
                      duration: 1500
                    });
                    _this.imgList.splice(i, 1)
                  },
                  fail: (err) => {
                    uni.hideLoading();
                    uni.showModal({
                      content: err.errMsg,
                      showCancel: false
                    });
                  }
                })
              } else {
                this.imgList.splice(e.currentTarget.dataset.index, 1)
              }
            } else {
              if (_this.imgList1[i].id) {
                uni.showLoading({
                  title: '处理中'
                })
                uni.request({
                  url: basePath + '/app/imgfiles/delete',
                  method: 'POST',
                  dataType: 'json',
                  header: {
                    'Content-type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    IMGFILES_ID: _this.imgList1[i].id,
                  },
                  success: (res) => {
                    uni.hideLoading();
                    uni.showToast({
                      icon: 'none',
                      title: '删除成功',
                      duration: 1500
                    });
                    _this.imgList1.splice(i, 1)
                  },
                  fail: (err) => {
                    uni.hideLoading();
                    uni.showModal({
                      content: err.errMsg,
                      showCancel: false
                    });
                  }
                })
              } else {
                this.imgList1.splice(e.currentTarget.dataset.index, 1)
              }
            }
          }
        }
      })
    },
    goSubmit() {
      var _this = this;
      var fileList = [];
      if(!_this.imgList.length > 0 ) {
        uni.showToast({
          icon: 'none',
          title: '请选择图片',
          duration: 1000
        });
        return
      }
      if (_this.imgList.length > 0) {
        uni.request({
          url: basePath + '/app/fireRecordManger/editDeviceCheckFine',
          method: 'POST',
          dataType: 'json',
          header: {
            'Content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            EQUIPMENT_POINT_ID: _this.EQUIPMENT_POINT_ID,
          },
          success: (res) => {

          }
        });

      }
      for (var i = 0; i < _this.imgList.length; i++) {
        if (!_this.imgList[i].id) {
          var file = {};
          file.type = 14;
          file.filePath = _this.imgList[i].filePath;
          fileList.push(file);
        }
      }
      if (fileList.length > 0) {
        var i = 0;
        _this.uploadImg(fileList, i);
      } else {
        uni.showToast({
          icon: 'none',
          title: '保存成功',
          duration: 1000
        });
        setTimeout(function() {
          console.log('123333')
          var pages = getCurrentPages(); // 获取当前页面栈
          var prePage = pages[pages.length - 2]; // 上一个页面
          // var task = prePage.$vm.list[_this.index];
          if (_this.index) {
            prePage.$vm.initflag = true; // A 页面 init方法 为true
          }
          uni.navigateBack({
            delta: 2
          });
          uni.hideLoading();
        }, 1000);

      }
    },
    uploadImg(tempFilePaths, i) {
      var _this = this;
      uni.showLoading({
        title: '上传中'
      })
      uni.uploadFile({
        url: basePath + '/app/imgfiles/add',
        filePath: tempFilePaths[i].filePath,
        name: 'FFILE',
        formData: {
          'TYPE': tempFilePaths[i].type,
          'FOREIGN_KEY': _this.EQUIPMENT_POINT_ID
        },
        success: (res) => {
          i++;
          if (tempFilePaths.length > i) {
            _this.uploadImg(tempFilePaths, i);

          } else {

            uni.showToast({
              icon: 'none',
              title: '保存成功',
              duration: 1000
            });
            setTimeout(function() {
              var pages = getCurrentPages(); // 获取当前页面栈
              var prePage = pages[pages.length - 2]; // 上一个页面
              // var task = prePage.$vm.list[_this.index];
              if (_this.index) {
                prePage.$vm.initflag = true; // A 页面 init方法 为true
                /* prePage.$vm.list[_this.index].ISNORMAL = 1;
                prePage.$vm.list[_this.index].HIDDEN_ID = _this.pd.HIDDEN_ID; */
              }
              uni.navigateBack({
                delta: 2
              });
              uni.hideLoading();
            }, 1000);
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
  }
}
</script>

<style>
.prevent {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
}

.cu-form-title {
  padding: 20upx 0;
}

.cu-form-textarea {
  background-color: #ffffff;
  padding: 1upx 30upx 20upx;
  min-height: 100upx;
}

.cu-form-textarea textarea {
  height: 4.6em;
  width: 100%;
  line-height: 1.2em;
  flex: 1;
  font-size: 28upx;
  padding: 0;
}

.selected {
  display: flex;
  align-items: center;
  height: 100upx;
}

.selected .radio {
  transform: scale(0.8);
  margin-right: 10upx;
}

.group {
  display: flex;
  align-items: center;
}

.cu-form-group .title {
  font-size: 28upx;
  color: #666;
}

.cu-bar .action:first-child {
  font-size: 28upx;
}
</style>
