<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.HOTWORK_ID" :hotworkId="pd.HOTWORK_ID"></detail>
			<view class="wui-form-list">
				<view class="cu-form-textarea" style="border-bottom: 1px dashed #eee;">
					<view class="cu-form-title">完工验收</view>
					<textarea maxlength="255" v-model="pd.DESCR" placeholder="请输入意见"></textarea>
				</view>
				<view style="border-bottom: 1px dashed #eee;">
					<view class="cu-form-group">
						<view class="title">验收时间</view>
						<ruiDatePicker fields="minute"
									   :value="pd.ACCEPT_TIME?pd.ACCEPT_TIME:''"
									   @change="changeStartDate"
						></ruiDatePicker>
					</view>
				</view>
				<view class="cu-bar bg-white">
					<view class="action">
						验收视频
					</view>
					<view class="action">
						{{videoList.length}}/1
					</view>
				</view>
				<view class="cu-form-group">
					<view class="grid col-4 grid-square flex-sub">
						<view class="bg-img" v-for="(item,vindex) in videoList" :key="vindex" style="background-color: #000">
							<image src="/static/icon-apps/video.png" mode="aspectFill" @click="playVideo"
								   :data-src="videoList[vindex].filePath"></image>
							<view class="cu-tag bg-red" @tap.stop="DelVideo" data-type="0" :data-index="vindex">
								<text class='cuIcon-close'></text>
							</view>
						</view>
						<view class="solids" @tap.stop="openAuthVideo('CAMERA')" v-if="videoList.length == 0">
							<text class='cuIcon-cameraadd'></text>
						</view>
					</view>
				</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 wui-sign-box1"  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 class="cu-tag bg-red" @tap.stop="DelImg(index)">
								<text class='cuIcon-close'></text>
							</view>
						</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>
		<yk-authpup ref="authpup_video" type="top" @changeAuth="chooseVideo(0)" :permissionID="permissionID"></yk-authpup>

	</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 detail from '@/pages/application/hotwork/hotwork-detail/index'
	export default {
		components: {
			tkiTree,ruiDatePicker,writingBoard,detail
		},
		data() {
			return {
				permissionID:'',
				baseImgPath:baseImgPath,
				buttonloading: false,
				isUps:false,
				forbidEdit:true,// 禁止修改
				msg:'add',
				files: [],
				noClick:true,
				treeNode:[],//部门下拉数据
				pd:{},// 数据
				measuresList:[],
				gasList:[],
				todayDate:'',
				modalName:null,
				imgList:[],
				videoList:[]
			}
		},
		onLoad(event){
			this.todayDate =  formatDate(new Date(), 'yyyy-MM-dd hh:mm');
			this.pd.HOTWORK_ID = event.HOTWORK_ID;
			if(this.pd.HOTWORK_ID){
				this.msg="edit";
				this.getData();
			}else {
				// 初始化作业负责人
				this.pd.APPLY_DEPARTMENT_ID = loginUser.DEPARTMENT_ID;
				this.pd.APPLY_DEPARTMENT_NAME = loginUser.DEPARTMENT_NAME;
				this.pd.APPLY_USER_ID = loginUser.USER_ID;
				this.pd.APPLY_USER_NAME = loginUser.NAME;
				this.forbidEdit = false;
			}
			// 初始化现场作业负责人
			this.getDept();
			loginSession();

		},
		methods: {
			//跳转事件
			goToDetail(e) {
				uni.navigateTo({
					url: '/pages/application/hotwork/hotwork-gas/gas-list?HOTWORK_ID='+e
				});
			},
			getData() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/hotwork/findById',
					method: 'POST',
 					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						HOTWORK_ID: _this.pd.HOTWORK_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
							});
						}
					}
				});
			},
			ViewShowImage(url) {
				let files = [];
				files.push(url)
				uni.previewImage({
					urls: files,
					current: 0
				});
			},
			changeStartDate(e) {
				this.pd.ACCEPT_TIME = e
				this.$forceUpdate();//强制刷新
			},
			goSubmit(APPLY_STATUS){
				var _this = this;
				let required = true
				uni.showLoading({
					title: '请稍候'
				})
				if (_this.imgList.length <= 0) {
					uni.showToast({
						icon: 'none',
						title: '请签字',
						duration: 1500
					});
					return;
				}
				if (!_this.pd.DESCR) {
					uni.showToast({
						icon: 'none',
						title: '请输入负责人意见',
						duration: 1500
					});
					return;
				}

				if(APPLY_STATUS == 1){
					if(new Date(this.pd.ACCEPT_TIME).getTime() - new Date(this.pd.WORK_END_DATE).getTime() >= 3600000){
						uni.showToast({
							icon: 'none',
							title: '请在作业结束30分钟内完成验收',
							duration: 1500
						});
						return;
					}
					if(!this.pd.ACCEPT_TIME){
						uni.showToast({
							icon: 'none',
							title: '请选择验收时间',
							duration: 1500
						});
						return;
					}
					if(!_this.videoList){
						uni.showToast({
							icon: 'none',
							title: '请上传验收视频',
							duration: 1500
						});
						return;
					}
				}

				var fileList = [];
				for (var i = 0; i < _this.videoList.length; i++) {
					if(!_this.videoList[i].id){
						var file = {};
						file.type = 3;
						file.filePath = _this.videoList[i].filePath;
						fileList.push(file);
					}
				}
				const formData={}
				var files = [];
				var signtime = [];
				this.uploadImgFaults(files,signtime)
				formData.SIGNTIME = signtime.join(",")
				formData.ACCEPT_TIME = _this.pd.ACCEPT_TIME
				formData.HOTWORK_ID = _this.pd.HOTWORK_ID
				formData.DESCR = _this.pd.DESCR?_this.pd.DESCR:"无"
				formData.USER_ID = loginUser.USER_ID
				formData.APPLY_STATUS = APPLY_STATUS
				formData.VIDEO_PATH = this.videoList.map(item => {
					return item.filePath
				})
				console.log(formData.VIDEO_PATH)
				uni.uploadFile({
					url: basePath+'app/hotwork/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
						});
					}
				})
			},

			uploadImg(file){
				return new Promise((resolve, reject) => {
					var _this = this;
					uni.uploadFile({
						url: basePath+'/app/imgfiles/add',
						filePath: file.filePath,
						name: 'FFILE',
						formData: {
							'TYPE': file.type,
							'FOREIGN_KEY': _this.pd.HOTWORK_ID,
							CORPINFO_ID: loginUser.CORPINFO_ID,
							USER_ID: loginUser.USER_ID,
						},
						success: (res) => {
							resolve();
						},
						fail: (err) => {
							uni.hideLoading();
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					})
				})
			},
			chooseVideo(e) {
				var _this = this;
				uni.chooseVideo({
					maxDuration: 60,
					count: 1, //默认9
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						if(res.tempFilePath.substring(res.tempFilePath.lastIndexOf(".") + 1, res.tempFilePath.length) === 'mp4'){
						uni.uploadFile({
							url: basePath + '/app/eightwork/saveFile',
							filePath: res.tempFilePath,
							name: 'file',
							formData: {
								CORPINFO_ID:loginUser.CORPINFO_ID,
							},
							success: ({data}) => {
								let img = {};
								img.filePath = JSON.parse(data).FILE_PATH;
								this.videoList.push(img)
							}
						});
					}else {
						uni.showToast({
							title: "只能上传MP4格式",
							duration: 2000
						});
					}
					}
				})
			},
			DelVideo(e){
				uni.showModal({
					title: '',
					content: '确定要删除这个视频吗？',
					cancelColor: "#000000",
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.videoList = []
						}
					}
				})
			},

			openAuthVideo(permissionID){
				this.permissionID = permissionID;
				setTimeout(()=>{
					this.$refs['authpup_video'].open();
				},200)
			},
			playVideo(e) {
				this.videoSrc = e.currentTarget.dataset.src
				this.modalShow = true
			},
			uploadImgFaults(fileList,signtime) {
				this.imgList.map(item => {
					var img = {}
					img.name = 'file'+(fileList.length)
					img.uri = item.filePath
					fileList.push(img)
					signtime.push(item.SIGNER_TIME)
				})
			},

			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 : corpinfoId,
					},
					success: (res) => {
						if("success" == res.data.result){
							_this.treeNode=eval(res.data.zTreeNodes);
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},
			//获取人员列表
			getUserList(dept,list,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()},
					success: function(res){
						if("success" == res.data.result){
							if(i>-1) {
								_this[list][i] = [];
								_this[list][i] = res.data.userList;
								_this.$forceUpdate();//强制刷新
							}else{
								_this[list]=res.data.userList;
							}
						}else{
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				})
			},

			/*
         *手写板
         */
			showModal(ISSELF) {
				this.ISSELF = ISSELF
				this.modalName = 'Modal'
			},
			hideModal(e) {
				this.modalName = null
			},
			//完成

			subCanvas(e) {
				e.SIGNER_TIME = formatDate(new Date(), 'yyyy-MM-dd hh:mm')
				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
				});
			},
			DelImg(index){
				this.imgList.splice(index,1)
			},

			goback(){
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 1});
				uni.hideLoading();
			},
			radioType(e){
				this.HASINSTRUCTOR = e.detail.value
			},
			goToEdit(){
				this.forbidEdit = false;
			}
		}
	}
</script>
<style scoped>
	.wui-sign-box1{
		margin-top: 20upx;
		display: block;
	}
	.sign-img{
		position: relative;
		border-bottom: 1px dashed #eee;
		padding-top: 20upx;
	}
	.cu-tag{
		position: absolute;
		right: 20upx;
		top: 20upx;
	}
</style>

