<template><!-- 源自pages/application/hidden-trouble-investigation/hidden-trouble-app/check-items-custom-list.vue -->
	<view>
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">{{CHECKTYPE_NAME}}排查项</block>
		</cu-custom>
		<scroll-view scroll-y>
			<view class="check-items" v-for="(item,index) in list" :key="item.CUSTOM_ITEM_ID">
				<view class="title">检查项名称:{{item.CHECKITEMNAME}}</view>
        		<view class="title">检查项说明:{{item.REMARKS}}</view>
				<view class="check-items-select">
					<radio-group class="block">
						<view class="flex justify-between padding-sm">
							<view class="select">
								<view @click="checkTrue({index:index},0)" class="flex align-center">
									<radio class='mr10' :class="item.ISNORMAL==0?'checked':''" :checked="item.ISNORMAL==0" disabled></radio>
									<text>合格</text>
								</view>
							</view>
							<view class="select">
								<view @click="checkTrue({index:index},1)" class="flex align-center">
									<radio class='red mr10' :class="item.ISNORMAL==1?'checked':''" :checked="item.ISNORMAL==1" disabled ></radio>
									<text>不合格</text>
								</view>
							</view>

						</view>
							<view v-if="item.ISNORMAL==0 || item.ISNORMAL==1" class="input" >
							  <textarea :disabled="item.OPERATION_TYPE === 1 ? true : false" maxlength="-1" v-model="item.REMARK" placeholder="检查详细描述"  :class="item.OPERATION_TYPE === 1 ? 'bgh' : ''"   style="border: 1px solid #eeeeee;  z-index: 999; height: 50px; padding: 10px;font-size: 12px; width: 100%"></textarea>
							</view>
					</radio-group>

				</view>
			</view>
				<view class="check-items">
					<view class="cu-bar bg-white margin-top">
						<view class="action">
							检查照片
						</view>
						<view class="action">
							{{ checkimgList.length }}/4
						</view>
					</view>
					<view class="cu-form-group">
						<view class="grid col-4 grid-square flex-sub">
							<view class="bg-img" v-for="(item,index) in checkimgList" :key="index" @tap="viewImage(index,'checkimgList')">
								<image :src="baseImgPath + item.filePath" mode="aspectFill"></image>
								<view class="cu-tag bg-red" @tap.stop="delImg" data-type="2" :data-index="index">
									<text class='cuIcon-close'></text>
								</view>
							</view>
							<view class="solids" @tap="chooseImage()" v-if="checkimgList.length<4">
								<text class='cuIcon-cameraadd'></text>
							</view>
						</view>
					</view>
				</view>
			<view class="check-items">
				<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 class="cu-tabbar-height"></view>
		</scroll-view>
		<view class="bottom-fixed" @tap.stop="openAuth('ACCESS_FINE_LOCATION')">
			<button :loading="buttonloading" class="cu-btn bg-green"  @click="$noMultipleClicks(goSubmit)">提交</button>
		</view>

    <yk-authpup ref="authpup" type="top" @changeAuth="$noMultipleClicks(save)" :permissionID="permissionID"></yk-authpup>
	</view>

</template>
<script>
	import {
		basePath,corpinfoId,loginUser,loginSession,formatDate,baseImgPath
	} from '@/common/tool.js';
	import gcoord from '@/common/gcoord.js'
  import ykAuthpup from "@/components/yk-authpup/yk-authpup"
	export default {
		data() {
			return {
				baseImgPath:baseImgPath,
        		permissionID:'',
				noClick:true,
				buttonloading: false,
				list: [],
				pd:[],
				CHECKTYPE_ID:'',
				checkimgList:[],
				modalName:null,
				imgList:[],
			}
		},
		onLoad(e){
			this.todayDate =  formatDate(new Date(), 'yyyy-MM-dd hh:mm');
			this.CHECKTYPE_ID=e.CHECKTYPE_ID;
			this.CHECKTYPE_NAME = e.CHECKTYPE_NAME;
			this.WAYBILLREGISTRATION_ID = e.WAYBILLREGISTRATION_ID;
			console.log(this.WAYBILLREGISTRATION_ID)
			this.getData();
			loginSession();
		},
		onShow() {
			var _this = this;
			if(_this.initflag){
				_this.initflag = false;
				_this.$forceUpdate();//强制刷新
			}
		},
		methods: {
			delImg(e) {
				var _this = this;
				uni.showModal({
					title: '秦安双控',
					content: '确定要删除这张图片吗？',
					cancelColor: "#000000",
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							uni.request({
								url: basePath+'/app/eightwork/deleteFile',
								method: 'POST',
								dataType: 'json',
								header: {
									'Content-type':'application/x-www-form-urlencoded'
								},
								data: {
									FILE_PATH:_this.checkimgList[e.currentTarget.dataset.index].filePath
								},
								success: (res) => {
									uni.showToast({
										icon: 'none',
										title: '删除成功',
										duration: 1500
									});
									this.checkimgList.splice(e.currentTarget.dataset.index, 1)
								},
								fail: (err) => {
									uni.showModal({
										content: "删除失败",
										showCancel: false
									});
								}
							})
						}
					}
				})
			},
			chooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						uni.uploadFile({
							url: basePath+'/app/eightwork/saveFile',
							filePath: res.tempFilePaths[0],
							name: 'file',
							formData: {
								CORPINFO_ID:loginUser.CORPINFO_ID,
							},
							success: ({data}) => {
								let img = {};
								img.filePath = JSON.parse(data).FILE_PATH;
								this.checkimgList.push(img)
								console.log(this.checkimgList)
							},
							fail: (err) => {
								uni.showModal({
									content: "图片上传失败",
									showCancel: false
								});
							}
						})
					}
				});
			},
			/*
     *手写板
     */
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			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)
				})
			},
			//完成
			subCanvas(e) {
				this.imgList.splice(0,this.imgList.length);
				this.imgList.push(e);
				e.SIGNER_TIME = formatDate(new Date(), 'yyyy-MM-dd hh:mm');
				this.hideModal()
			},
			ViewImage(e) {
				let files =[];
				files.push(e.currentTarget.dataset.url)
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.url
				});
			},

			getData() {
				var _this = this;
				console.log(_this)
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/drivingtype/listForSafetyDrivingType', // /app/listmanager/goCheck
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type':'application/x-www-form-urlencoded'
					},
					data: {
						CHECKTYPE_ID: _this.CHECKTYPE_ID,
						USER_NAME : loginUser.NAME,
						CORPINFO_ID:loginUser.CORPINFO_ID,
						USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
						if("success" == res.data.result){
							uni.hideLoading();
							_this.pd=res.data.pd;
							_this.list = res.data.varList;
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},

		  openAuth(permissionID){
			this.permissionID = permissionID;
			setTimeout(()=>{
			  this.$refs['authpup'].open();
			},200)
		  },

			//去保存
			save: function (){
				var _this = this;
				for(var i=0;i<_this.list.length;i++){
				  if(this.list[i].ISNORMAL && this.list[i].OPERATION_TYPE === 2) {
					var REMARK = ''
					if (this.list[i].ISNORMAL === 0 || this.list[i].ISNORMAL === 1) {
					  REMARK = _this.list[i].REMARK
					}
					if (!REMARK) {
					  uni.showToast({
						icon: 'none',
						title: '第'+(i+1)+'项检查为填写检查，检查结果不能为空',
						duration: 1500
					  });
					  return;
					}
				  }
				}
				uni.showLoading({
					title: '请稍候'
				})
				var items=[];
				var ids=[];
				for(var i=0;i<_this.list.length;i++){
					var item = {};
					if(_this.list[i].ISNORMAL>-1 ) {
						item.CUSTOM_ITEM_ID = _this.list[i].CUSTOM_ITEM_ID

						item.ISNORMAL = _this.list[i].ISNORMAL
						if (_this.list[i].ISNORMAL === 0 || _this.list[i].ISNORMAL === 1) {
						  item.REMARK = _this.list[i].REMARK
						}
						item.DRIVINGTYPE_ID = _this.list[i].DRIVINGTYPE_ID
						items.push(item)

					}
				}
				let longitude;
				let latitude;

				uni.getLocation({
					type: 'GCJ02',
					success: function (res1) {
						longitude = res1.longitude;
						latitude = res1.latitude;
						var result = gcoord.transform(
								[longitude, latitude],    // 经纬度坐标
								gcoord.GCJ02,               // 当前坐标系
								gcoord.BD09                // 目标坐标系
						);
						longitude = result[0];
						latitude =  result[1];
						//发送 post 请求提交保存
						this.buttonloading = true
						uni.request({
							url: basePath+'/app/customCheckRecord/add',  // /app/checkrecord/add'
							xhrFields: {
								withCredentials: true
							},
							method: 'POST',
							dataType: 'json',
							header: {
								'Content-type':'application/x-www-form-urlencoded'
							},
							data: {
								CUSTOM_ID:_this.listId,
								LIST_NAME:_this.listName,
								CREATOR:loginUser.NAME,
								LATITUDE:latitude,
								LONGITUDE:longitude,
								ITEMS:JSON.stringify(items),
								IDS:ids.join(","),
								CHECKRECORD_ID:_this.CHECKRECORD_ID,
								tm:new Date().getTime(),
								CORPINFO_ID:loginUser.CORPINFO_ID,
								USER_ID:loginUser.USER_ID,
							},
							success: function(res){
								this.buttonloading = false
								if("success" == res.data.result){
									uni.showToast({
										icon: 'none',
										title: '提交成功',
										duration: 1500
									});
									setTimeout(function(){
										var pages = getCurrentPages();	// 获取当前页面栈
										var prePage = pages[pages.length - 2];	// 上一个页面
										prePage.$vm.initflag = true;    // A 页面 init方法 为true
										uni.navigateBack({});
										uni.hideLoading();
									},1500);
								}else {
									uni.showToast({
										title: "系统错误",
										duration: 2000
									});
								}
							}
						})
					},
					fail: function(res){
						uni.hideLoading();
						uni.showToast({
							title: "获取位置失败",
							duration: 2000
						});
					}
				});

			},
			goSubmit(){
				var _this = this;
				let required = true
				uni.showLoading({
					title: '请稍候'
				})

				if (_this.checkimgList.length <= 0) {
					uni.showToast({
						icon: 'none',
						title: '请上传车辆检查照片',
						duration: 1500
					});
					return;
				}
				if (_this.imgList.length <= 0) {
					uni.showToast({
						icon: 'none',
						title: '请签字',
						duration: 1500
					});
					return;
				}

				var files = [];
				var signtime = [];
				const formData={}
				this.uploadImgFaults(files,signtime)
				formData.SIGNTIME = signtime
				formData.CORPINFO_ID = loginUser.CORPINFO_ID
				formData.USER_ID = loginUser.USER_ID
				formData.USER_NAME = loginUser.USERNAME
				formData.CHECKTYPE_ID = this.CHECKTYPE_ID
				formData.IMG_PATH = this.checkimgList.map(item => {
					return item.filePath
				}).join(",")
				formData.checklist = JSON.stringify(this.list)
				if(this.CHECKTYPE_NAME == "出车前" || this.CHECKTYPE_NAME == "行车中"){
					formData.WAYBILLSTATUS = 1
				}else if (this.CHECKTYPE_NAME == "收车后"){
					formData.WAYBILLSTATUS = 2
				}
				formData.WAYBILLREGISTRATION_ID = this.WAYBILLREGISTRATION_ID
				console.log(JSON.stringify(this.list))
				uni.uploadFile({
					url: basePath+'app/drivingitem/add',
					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
						});
					}
				})
			},
			goback(){
				var pages = getCurrentPages();	// 获取当前页面栈
				var prePage = pages[pages.length - 2];	// 上二级页面
				prePage.$vm.initflag = true;    // A 页面 init方法 为true
				uni.navigateBack({delta: 2});
				uni.hideLoading();
			},
			//点击合格
			checkTrue(e,STATUS) {

				let _this=this;
				_this.list[e.index].ISNORMAL=STATUS;
				console.log(_this.list[e.index].ISNORMAL)
				_this.$forceUpdate();//强制刷新
				_this.$set(_this.list[e.index], 'REMARK', _this.list[e.index].REMARK)
			},

		}
	}
</script>

<style>
.select radio {
		transform: scale(0.9);
	}

.bgh{
  background: #f8f6f6;
  color: #d9d7d7;
}

</style>
