<template>
  <view>
    <cu-custom bgColor="bg-gradual-blueness" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">延时监火</block>
    </cu-custom>
    <view style="text-align: right;">
      <button class="cu-btn bg-blue margin-tb-sm sm" v-if="STATE !='11'" @click="addModalShow">添加</button>
      <button class="cu-btn bg-blue margin-tb-sm sm" v-if="STATE !='11'" style="margin-left: 20upx;margin-right: 20upx" @click="taskModalShow">任务转发</button>
    </view>
    <view class="form" v-if="list.length>0">
      <view class="wui-form-list" v-for="(item,index) in list" :key="index">
        <view class="cu-form-group">
          <view class="title">监火人:</view>
          {{ item.userName }}
        </view>
        <view class="cu-form-group">
          <view class="title">时间:</view>
          {{ item.TIME }}
        </view>
        <view class="cu-form-group">
          <view class="title">照片:</view>
          <button class="cu-btn bg-blue margin-tb-sm sm" @click="ViewImage1(item.FILEPATH)">查看图片</button>
        </view>
      </view>
      <view class="cu-bar btn-group" style="margin-top: 30upx;" v-show="list.length !== 0">
        <button class="cu-btn bg-green margin-tb-sm lg" v-if="STATE !='11'" @click="$noMultipleClicks(goSubmit)">完成延时监火</button>
      </view>
    </view>
    <view v-else-if="dataFlag=='noData'" class="dy-null">
      <view class="dy-null-img">
        <image :src="background[dataFlag].url" mode=""></image>
      </view>
      <view class="dy-null-title">
        {{background[dataFlag].msg}}
      </view>
    </view>
    <view class="cu-tabbar-height"></view>
    <view class="padding flex flex-direction"></view>
    <view :class="['cu-modal',{'show':addModal}]">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">延时监火</view>
          <view class="action" @tap="addModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view>
          <view class="wrapper">
            <view class="handCenter">
              <view class="form">
                <view class="wui-form-list">
                  <view class="cu-form-group">
                    <view class="title">监火人:</view>
                    {{addForm.PYROMANCER}}
                  </view>
                  <view class="cu-form-group">
                    <view class="title">时间:</view>
                    <ruiDatePicker :start="todayDate" fields="minute" :value="addForm.TIME || '请选择'" @change="changeApplicationDate"></ruiDatePicker>
                  </view>
                  <view class="cu-form-group">
                    <view class="title">照片:</view>
                    <button class="cu-btn bg-blue margin-tb-sm sm" @click="ChooseImage" v-if="addForm.imgList.length === 0">点击上传</button>
                    <view v-else>
                      <view class="bg-img" v-for="(item,index) in addForm.imgList" :key="index" @tap="ViewImage" :data-url="addForm.imgList[index].filePath">
                        <image :src="addForm.imgList[index].filePath" style="width: 200upx ;height: 200upx"></image>
                        <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                          <text class='cuIcon-close'></text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button class="cu-btn bg-green margin-left" @click="$noMultipleClicks(confirmAdd)">提交</button>
          </view>
        </view>
      </view>
    </view>

    <view :class="['cu-modal',{'show':taskModal}]">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">任务转发</view>
          <view class="action" @tap="taskModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view>
          <view class="wrapper">
            <view class="handCenter">
              <view class="form">
                <view class="wui-form-list">
                  <view class="cu-form-group">
                    <view class="title">接班监火人部门:</view>
                    <view class="picker-tree-box">
                      <view class="picker-tree" @tap="showZgTree">
                        {{ taskForm.SUCCESSOR_FIRE_WATCHER_DEPARTMENT_NAME || '请选择' }}
                      </view>
                    </view>
                    <tki-tree ref="tkiTree" v-if="tkiTreeShow" :selectParent=true :range="treeNode" rangeKey="name" @confirm="zgtreeConfirm"
                              @cancel="zgtreeCancel"></tki-tree>
                  </view>
                  <view class="cu-form-group" v-if="taskForm.SUCCESSOR_FIRE_WATCHER_DEPARTMENT_NAME">
                    <view class="title">接班监火人:</view>
                    <picker @change="successorFireWatcherChange" :value="taskForm.SUCCESSOR_FIRE_WATCHER_INDEX"
                            :range="successorFireWatcherList" range-key="NAME">
                      <view class="picker">
                        {{ taskForm.SUCCESSOR_FIRE_WATCHER_NAME || '选择本班组内人员' }}
                      </view>
                    </picker>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button class="cu-btn bg-green margin-left" @click="$noMultipleClicks(confirmTask)">提交</button>
          </view>
        </view>
      </view>
    </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,
  loginUser,
  loginSession,
  formatDate,
  corpinfoId,
  loginUserId,
  baseImgPath
} from '@/common/tool.js';
import sign from '@/components/sign/sign.vue';
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
import tkiTree from "@/components/select-tree/select-tree.vue"
import gcoord from '@/common/gcoord.js'

export default {
  components: {
    sign,
    ruiDatePicker,
    tkiTree
  },
  data() {
    return {
      noClick: true,
      dataFlag: 'noData',
      list: [],
      addModal:false,
      addForm:{
        PYROMANCER: '',
        TIME: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
        imgList: [],
        delayedUserId:'',
      },
      todayDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
      taskModal:false,
      taskForm:{
        SUCCESSOR_FIRE_WATCHER_DEPARTMENT_ID: '',
        SUCCESSOR_FIRE_WATCHER_DEPARTMENT_NAME: '',
        SUCCESSOR_FIRE_WATCHER_INDEX: '',
        SUCCESSOR_FIRE_WATCHER_NAME: '',
        SUCCESSOR_FIRE_WATCHER_ID: '',
      },
      HOTWORKAPPLICATION_ID:'',
      STATE:'',
      successorFireWatcherList:[],
      treeNode: [],
      tkiTreeShow: false,
	  width: '',
	  height: ''
    }
  },
  onLoad(event) {
    this.background = require('@/common/background.json');
    this.HOTWORKAPPLICATION_ID = event.id
    this.STATE =event.state
    console.info(this.STATE)
    this.getData();
    this.addForm.PYROMANCER = loginUser.NAME;
    this.addForm.delayedUserId = loginUserId;
    loginSession();
    this.getDept();
  },
  methods: {
    getData() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + '/app/hotworkapplicationdelayed/list?showCount=1&currentPage=999',
        method: 'POST',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          HOTWORKAPPLICATION_ID: _this.HOTWORKAPPLICATION_ID,
        },
        success: (res) => {
          if ("success" == res.data.result) {
            this.list = res.data.varList
            uni.hideLoading();
          } else if ("exception" == res.data.result) {
            uni.showToast({
              title: '错误',
              duration: 2000
            });
          }
        }
      });
    },
    goSubmit() {
      var _this = this;
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + "/app/hotworkapplication/editOpinion",
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          TYPE: '2',
          loginUserId: loginUserId,
          STATE: '10',
          CORPINFO_ID :corpinfoId,
          HOTWORKAPPLICATION_ID: _this.HOTWORKAPPLICATION_ID,
        },
        success: (res) => {
          let resJson = res.data
          if(resJson.result =='success'){
            uni.showToast({
              icon: 'none',
              title: '完成延时监火成功',
              duration: 2000
            });
            uni.redirectTo({
              url: '/pages/application/eight-assignments/hotwork/delay-fire-monitoring/list'
            })
          }else{
            uni.showToast({
              icon: 'none',
              title: resJson.msg,
              duration: 1500
            });
            uni.redirectTo({
              url: '/pages/application/eight-assignments/hotwork/delay-fire-monitoring/list'
            })
          }
          uni.hideLoading();

        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
    addModalShow(){
      this.addModal = true;
      this.addForm.imgList = [];
    },
    ChooseImage() {
      var _this = this;
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
        sourceType: ['camera'], //从相册选择
        success: (res) => {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
			_this.setimg(res.tempFilePaths[0],0)
          //if (this.addForm.imgList.length != 0) {
          //  this.addForm.imgList = this.addForm.imgList.concat(res.tempFilePaths)
          //} else {
          //  this.addForm.imgList = res.tempFilePaths
          //}
        }
      });
    },
	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';
		   console.log(_this.height);
	      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 => {
					  console.log("水印合成完成");
	                if (e == 0 ) {
	                  let img = {};
	                  img.id = '';
	                  img.filePath = ress.tempFilePath;
					  _this.addForm.imgList = _this.addForm.imgList.concat(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) {
      uni.previewImage({
        urls: this.addForm.imgList,
        current: e.currentTarget.dataset.url
      });
    },
    ViewImage1(urls) {
      uni.previewImage({
        urls:[baseImgPath + urls]
      });
    },
    DelImg(e) {
      uni.showModal({
        title: '双控平台',
        content: '确定要删除这张图片吗?',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            this.addForm.imgList.splice(e.currentTarget.dataset.index, 1)
          }
        }
      })
    },
    confirmAdd(){
      if(this.addForm.imgList.length === 0){
        uni.showToast({
          icon: 'none',
          title: '请上传图片',
          duration: 2000
        });
        return;
      }
      uni.showLoading({
        title: '请稍候'
      })
      uni.uploadFile({
        url: basePath+'/app/hotworkapplicationdelayed/add',
        filePath: this.addForm.imgList[0].filePath,
        name: 'FFILE',
        formData: {
          ...this.addForm,
          HOTWORKAPPLICATION_ID: this.HOTWORKAPPLICATION_ID,
        },
        success: (res) => {
          uni.hideLoading();
          this.addModal = false
          this.getData()
          uni.showToast({
            icon: 'none',
            title: '添加成功',
            duration: 2000
          });
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
    taskModalShow(){
      this.taskModal = true;
      this.taskForm = {
        SUCCESSOR_FIRE_WATCHER_INDEX: '',
        SUCCESSOR_FIRE_WATCHER_NAME: '',
        SUCCESSOR_FIRE_WATCHER_ID: '',
      }
    },
    successorFireWatcherChange(e){
      this.taskForm.SUCCESSOR_FIRE_WATCHER_INDEX = e.detail.value;
      this.taskForm.SUCCESSOR_FIRE_WATCHER_ID = this.successorFireWatcherList[e.detail.value].USER_ID;
      this.taskForm.SUCCESSOR_FIRE_WATCHER_NAME = this.successorFireWatcherList[e.detail.value].NAME;
    },
    getDept() {
      let _this = this;
      uni.request({
        url: basePath + '/app/sys/listTree', //部门下拉接口
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          CORPINFO_ID: corpinfoId,
        },
        success: (res) => {
          if ("success" == res.data.result) {
            _this.treeNode = eval(res.data.zTreeNodes);
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      });
    },
    confirmTask(){
      if(!this.taskForm.SUCCESSOR_FIRE_WATCHER_ID){
        uni.showToast({
          icon: 'none',
          title: '请选择接班监火人',
          duration: 2000
        });
        return;
      }
      uni.showLoading({
        title: '请稍候'
      })
      uni.request({
        url: basePath + "/app/hotworkapplication/delayedUser",
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          ...this.taskForm,
          HOTWORKAPPLICATION_ID: this.HOTWORKAPPLICATION_ID,
          delayedUserId: this.taskForm.SUCCESSOR_FIRE_WATCHER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          this.taskModal = false
          uni.showToast({
            icon: 'none',
            title: '转发成功',
            duration: 2000
          });
          this.goback();
          uni.redirectTo({
            url: '/pages/application/eight-assignments/hotwork/delay-fire-monitoring/list'
          })
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      })
    },
    changeApplicationDate(e) {
      this.addForm.TIME = e
    },
    showZgTree() {
      this.tkiTreeShow = true;
      this.$nextTick(()=>{
        this.$refs.tkiTree._show();
      })
    },
    zgtreeConfirm(e) {
      console.info(e)
      this.$set(this.taskForm, 'SUCCESSOR_FIRE_WATCHER_DEPARTMENT_ID', e[0].id)
      this.$set(this.taskForm, 'SUCCESSOR_FIRE_WATCHER_DEPARTMENT_NAME', e[0].name)
      this.$set(this.taskForm, 'SUCCESSOR_FIRE_WATCHER_INDEX', '')
      this.$set(this.taskForm, 'SUCCESSOR_FIRE_WATCHER_ID', '')
      this.$set(this.taskForm, 'SUCCESSOR_FIRE_WATCHER_NAME', '')
      this.getUserList(e[0].id);
      this.tkiTreeShow = false;
    },
    zgtreeCancel(e) {
      this.isUps = false;
      this.tkiTreeShow = false;
    },
    getUserList(DEPARTMENT_ID) {
      //发送 post 请求
      var _this = this;
      uni.request({
        method: 'POST',
        dataType: 'json',
        header: {
          'Content-type': 'application/x-www-form-urlencoded'
        },
        url: basePath + '/app/sys/listUser',
        data: {
          DEPARTMENT_ID, NOMAIN:'1',
          tm: new Date().getTime()
        },
        success: function (res) {
          if ("success" == res.data.result) {
            _this.successorFireWatcherList = res.data.userList;
          } else {
            uni.showToast({
              title: res.data.message,
              duration: 2000
            });
          }
        }
      })
    },
    goback() {
      uni.navigateBack({
        delta: 1
      });
      uni.hideLoading();
    },
  }
}
</script>

<style scoped>
.cu-modal{
  z-index: 0;
}
.bg-img{
  position: relative;
}
.cu-tag{
  position: absolute;
  right: 0;
  top: 0;
  border-bottom-left-radius: 3px;
  padding: 3px 6px;
  height: auto;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>