<template>
	<view >
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true" >
			<block slot="backText">返回</block>
			<block slot="content">安全措施确认人意见</block>
		</cu-custom>
		<scroll-view scroll-y="false" >
            <view class="form">
                <detail v-if="pd.CONFINEDSPACE_ID" :confinedspaceId="pd.CONFINEDSPACE_ID" :showMeasures="false"></detail>

                <view class="wui-form-list" style="padding-top: 20upx;">
                    <view class="wui-title" style="margin-left: 20upx;">
                        <text class="text-semi">安全防护措施</text>
                    </view>
                    <view class="wui-table" style="padding: 0 20upx;">
                        <uni-table name='measuresList' border stripe emptyText="暂无更多数据" >
                            <!-- 表头行 -->
                            <uni-tr>
                                <uni-th align="center" style="font-weight: bold;">主要安全措施</uni-th>
                                  <uni-th align="center">
                                    <view class="title" style="width: 50px">操作</view>
                                  </uni-th>
                            </uni-tr>
                            <template v-for="(item,index) in measuresList">
                              <uni-tr>
                                <uni-td>
                                  <view style="margin-bottom: 20upx;">
                                    {{item.PROTECTIVE_MEASURES}}
                                  </view>

                                  <view class="cu-form-group" v-if="item.QUESTION1">
                                    <view class="title">{{item.QUESTION1}}</view>
                                    <input name="input" v-model="item.ANSWER1"  type="number" placeholder="请输入"></input>
                                  </view>
                                  <view class="cu-form-group" v-if="item.QUESTION2">
                                    <view class="title">{{item.QUESTION2}}</view>
                                    <input name="input" v-model="item.ANSWER2" type="number" placeholder="请输入"></input>
                                  </view>
                                  <view class="cu-form-group" v-if="item.QUESTION3">
                                    <view class="title">{{item.QUESTION3}}</view>
                                    <input name="input"  v-model="item.ANSWER3" type="number" placeholder="请输入"></input>
                                  </view>
                                </uni-td>

                                <uni-td align="center">
                                    <view class="title" @click="$noMultipleClicks(goToSign,index)">
                                        {{!item.SIGN_PATH ? '签字' : '已签字'}}
                                    </view>
                                </uni-td>
                              </uni-tr>
                            </template>
                        </uni-table>
                    </view>
                    <view class="cu-form-group" >
                        <view class="title">其他安全措施:</view>
                        <input name="input" ref="DESCR" v-model="pd.DESCR" placeholder="请输入其他安全措施"></input>
                    </view>
                    <view class="wui-sign" >
                      <view class="title"></view>
                      <button class="cu-btn bg-green shadow" @tap="showModal" data-target="Modal">手写签字</button>
                    </view>
                    <view class="wui-sign-box"  v-show="imgList && imgList.length > 0">
                      <view class="sign-title">
                        签字照片:
                      </view>
                      <view class="wui-sign-cotent">
                        <view class="sign-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="aspectFit"></image>
                        </view>
                      </view>
                    </view>
                    <view class="cu-modal" :class="modalName=='Modal'?'show':''">
                      <writing-board  @confirm="subCanvas" @cancel="hideModal"></writing-board>
                    </view>
                </view>
            </view>
            <view class="cu-bar btn-group" style="margin-top: 30upx;">
                <button class="cu-btn bg-red margin-tb-sm lg" @click="$noMultipleClicks(goSubmit,'-1')">打 回</button>
                <button class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goSubmit,'1')">通 过</button>
            </view>
            <view class="padding flex flex-direction">
            </view>
		</scroll-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 writingBoard from "@/components/writing-board/writing-board.vue"
	import gcoord from '@/common/gcoord.js'
	import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue';
  import { setMeasures } from '@/pages/application/dangerous_options/index.js';
  import detail from '@/pages/application/confinedspace/confinedspace-detail/index'
	export default {
		components: {
			tkiTree,ruiDatePicker,writingBoard,detail
		},
		data() {
			return {
				baseImgPath:baseImgPath,
				buttonloading: false,
				noClick:true,
				treeNode:[],//部门下拉数据
				pd:{},// 数据
				measuresList:[],
				modalName:null,
				imgList:[],

			}
		},
		onLoad(event){
			this.pd.CONFINEDSPACE_ID = event.CONFINEDSPACE_ID;
            this.getData();
			// 初始化现场作业负责人
			this.getDept();
			this.getMeasures();
			loginSession();
		},
    // 监听事件
    mounted() {
      uni.$on('dangerous_options_submit', (data) => {
          this.$set(this.measuresList[data.index],'SIGN_PATH',data.signImgList[0].filePath)
          this.$set(this.measuresList[data.index],'SIGN_TIME',data.signImgList[0].SIGNER_TIME)
          this.$set(this.measuresList[data.index],'IMG_PATH',data.imgList.map(item => {
              return item.filePath
          }).join(","))
          this.$set(this.measuresList[data.index],'STATUS',data.STATUS)
      })
    },
    // 取消监听
    beforeDestroy() {
      uni.$off('dangerous_options_submit');
        },
		methods: {
			//跳转事件
			goToDetail(e) {
				uni.navigateTo({
					url: '/pages/application/confinedspace/confinedspace-gas/gas-list?CONFINEDSPACE_ID='+e
				});
			},
              goToSign(index) {
                const measures = this.measuresList[index]
                const signImgList = []
                if (measures.SIGN_PATH) {
                  signImgList.push({"filePath":measures.SIGN_PATH,"SIGNER_TIME":measures.SIGN_TIME})
                }
                const imgList = []
                if (measures.IMG_PATH) {
                  measures.IMG_PATH.split(",").forEach(item => {
                    imgList.push({"filePath":item})
                  })
                }
                setMeasures(measures.PROTECTIVE_MEASURES)
                uni.navigateTo({
                  url: '/pages/application/dangerous_options/index?index='+index +
                      '&STATUS='+(measures.STATUS || 1) + '&signImgList='+JSON.stringify(signImgList) + '&imgList='+JSON.stringify(imgList)
                });
            },
			getData() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/confinedspace/findById',
					method: 'POST',
 					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						CONFINEDSPACE_ID: _this.pd.CONFINEDSPACE_ID,
						CORPINFO_ID:loginUser.CORPINFO_ID,
						USER_ID:loginUser.USER_ID,
                        },
					success: (res) => {
						if ("success" == res.data.result) {
							uni.hideLoading();
							_this.pd = res.data.pd; //参数map
						} else if ("exception" == data.result) {
							uni.showToast({
								title: '错误',
								duration: 2000
							});
						}
					}
				});
			},

			goSubmit(APPLY_STATUS) {
                var _this = this;
                uni.showLoading({
                    title: '请稍候'
                })
                if (_this.imgList.length <= 0) {
                    uni.showToast({
                        icon: 'none',
                        title: '请签字',
                        duration: 1500
                    });
                    return;
                }
                if (APPLY_STATUS == 1) {
                    if(!this.pd.DESCR){
                        uni.showToast({
                            icon: 'none',
                            title: '请输入其他安全措施,没有请填“无”',
                            duration: 1500
                        });
                        return;
                    }
                    for (let i = 0; i < this.measuresList.length; i++) {
                        const measures = this.measuresList[i]
                        if(!measures.SIGN_PATH){
                            uni.showToast({
                                icon: 'none',
                                title: '第'+(i+1)+'项未签字',
                                duration: 1500
                            });
                            return;
                        }
                        if(measures.STATUS=='1' && measures.QUESTION1 && !measures.ANSWER1){
                            uni.showToast({
                                icon: 'none',
                                title: '第'+(i+1)+'项未填写第一项',
                                duration: 1500
                            });
                            return;
                        }
                        if(measures.STATUS=='1' && measures.QUESTION2 && !measures.ANSWER2){
                            uni.showToast({
                                icon: 'none',
                                title: '第'+(i+1)+'项未填写第二项',
                                duration: 1500
                            });
                            return;
                        }
                        if(measures.STATUS=='1' && measures.QUESTION3 && !measures.ANSWER3){
                            uni.showToast({
                                icon: 'none',
                                title: '第'+(i+1)+'项未填写第三项',
                                duration: 1500
                            });
                            return;
                        }
                    }
                }

                const formData={}
                var files = [];
                var signtime = [];
                this.uploadImgFaults(files,signtime)
                formData.APPLY_STATUS = APPLY_STATUS
                formData.CONFINEDSPACE_ID = _this.pd.CONFINEDSPACE_ID
                formData.DESCR = _this.pd.DESCR?_this.pd.DESCR:"无"
                formData.SIGNTIME = signtime.join(",")
                formData.USER_ID = loginUser.USER_ID
                formData.MEASURES = JSON.stringify(this.measuresList)
                uni.uploadFile({
                  url: basePath+'app/confinedspace/nextStep',
                  files: files,
                  formData:formData,
                  success: (res) => {
                    uni.showToast({
                      icon:'none',
                      title: '保存成功',
                      duration: 2000
                    });
                    _this.goback()
                  },
                  fail: (err) => {
                    uni.hideLoading();
                    uni.showModal({
                      content: err.errMsg,
                      showCancel: false
                    });
                  }
                })
			},

              uploadImgFaults(files,signtime) {
                this.imgList.map((item,index) => {
                  var img = {}
                  img.name = 'file'+index
                  img.uri = item.filePath
                  files.push(img)
                  signtime.push(item.SIGNER_TIME)
                })
              },

			getMeasures(){
				var _this = this;
				uni.request({
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					url: basePath + '/app/confinedspace/listAllMeasuresForSign?tm=' + new Date().getTime(),
					data: {
						CORPINFO_ID:loginUser.CORPINFO_ID,
                        CONFIRM_ID:loginUser.USER_ID,
                        CONFINEDSPACE_ID: _this.pd.CONFINEDSPACE_ID,
					},
					success: function (res) {
						_this.measuresList = res.data.measuresForSignList
					}
				});
			},

			getDept() {
				var _this = this;
				uni.request({
					url: basePath + '/app/sys/listTree',//部门下拉接口
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type':'application/x-www-form-urlencoded'
					},
					data: {
						CORPINFO_ID:loginUser.CORPINFO_ID,
						USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
						if("success" == res.data.result){
							_this.treeNode=eval(res.data.zTreeNodes);
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},

              showDeptTree(index) {
                this.isUps=true
                this.$refs['tkiTree'+index][0]._show();
              },

              deptTreeConfirm(e,i) {
                this.isUps=false;
                this.measuresList[i].DEPARTMENT_ID=e[0].id;
                this.measuresList[i].DEPARTMENT_NAME=e[0].name;
                this.measuresList[i].USER_ID = ''
                this.measuresList[i].USER_NAME = ''
                this.getUserList(e[0].id,i);
              },

              deptTreeCancel(e) {
                this.isUps=false;
              },

              pickerUser(e,i) {
                this.measuresList[i].userIndex = e.detail.value;
                this.measuresList[i].USER_ID=this.measuresList[i].userList[e.detail.value].USER_ID;
                this.measuresList[i].USER_NAME=this.measuresList[i].userList[e.detail.value].NAME;
                this.$forceUpdate();//强制刷新
              },

              isBlankList(i) {
                if (this.measuresList[i].userList.length == 0) {
                  uni.showToast({
                    icon: 'none',
                    title: '请先选择确认单位',
                    duration: 1500
                  })
                }
              },

			//获取人员列表
			getUserList(dept,i){
				//发送 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:dept,
						tm:new Date().getTime(),
						CORPINFO_ID:loginUser.CORPINFO_ID,
						USER_ID:loginUser.USER_ID,
					  },
					success: function(res){
						if("success" == res.data.result){
							_this.measuresList[i].userList = res.data.userList;
						}else{
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				})
			},

			/*
         *手写板
         */
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			//完成
			subCanvas(e) {
                e.SIGNER_TIME = formatDate(new Date(), 'yyyy-MM-dd hh:mm')
				this.imgList.splice(0,this.imgList.length);
				this.imgList.push(e);
				this.hideModal()
			},
			ViewImage(e) {
				let files =[];
				files.push(e.currentTarget.dataset.url)
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.url
				});
			},

			goback(){
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 1});
				uni.hideLoading();
			},
		},
	}
</script>

<style>

</style>