<template>
	<view>
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">隐患验收</block>
		</cu-custom>
    <view>
      <hiddenView :hidden_id="this.id"/>
    </view>
    <view>
      <view class="wui-form-list">
        <view class="wui-sub-title">
          <text>隐患验收</text>
        </view>
        <view class="cu-form-group bb-default">
          <view class="title text-hui">是否合格</view>
          <radio-group class="selected">
            <view class="group mr20">
              <radio class='radio' value="1" :checked="ISQUALIFIED==='1'" @click="radio('1')"></radio>
              <text>是</text>
            </view>
            <view class="group">
              <radio class='radio' value="0" :checked="ISQUALIFIED==='0'" @click="radio('0')"></radio>
              <text>否</text>
            </view>
          </radio-group>
        </view>
        <view v-if="ISQUALIFIED==1" class="cu-form-textarea">
          <view class="cu-form-title">验收描述</view>
          <textarea maxlength="-1" @input="textareaAInput" placeholder="请对隐患验收进行详细描述(必填项)"></textarea>
        </view>
        <view v-if="ISQUALIFIED==1" class="cu-form-group bb-default">
          <view class="title">验收日期</view>
          <picker mode="date" :value="CHECK_TIME" :start="now" @change="changeDate">
            <view class="picker">
              {{CHECK_TIME==''?'请选择':CHECK_TIME}}
            </view>
          </picker>
        </view>
        <view v-if="ISQUALIFIED==1" class="cu-bar bg-white">
          <view class="action" style="font-size: 28upx; font-weight: bold; color: #000;">
            验收图片
          </view>
          <view class="action">
            {{imgList.length}}/4
          </view>
        </view>
        <view v-if="ISQUALIFIED==1" class="cu-form-group">
          <view class="grid col-4 grid-square flex-sub">
            <view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
                  :data-url="imgList[index]">
              <image :src="imgList[index]" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap.stop="openAuth('CAMERA')" v-if="imgList.length<4">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>
        </view>
        <view v-if="ISQUALIFIED==0" class="cu-form-textarea">
          <view class="cu-form-title">重新整改原因</view>
          <textarea maxlength="-1" @input="textareaAInputREPULSE_CAUSE" placeholder="请对隐患重新整改原因进行详细描述(必填项)"></textarea>
        </view>
      </view>
      <view class="padding flex flex-direction">
        <button :loading="buttonloading" class="cu-btn bg-green margin-tb-sm lg" @click="$noMultipleClicks(goSubmit)">提 交</button>
      </view>
    </view>
    <yk-authpup ref="authpup" type="top" @changeAuth="ChooseImage" :permissionID="permissionID"></yk-authpup>
	</view>
</template>

<script>
	import {
		basePath,
		loginUserId,
		loginSession,
		baseImgPath,
		corpinfoId,
      loginUser,
    formatDate
	} from '@/common/tool.js';
  import ykAuthpup from "@/components/yk-authpup/yk-authpup"
  import hiddenView from '@/components/hidden_view/index.vue';

	export default {
    components: {
      ykAuthpup,
      hiddenView
    },
		data() {
			return {
        REPULSE_CAUSE:'',
        permissionID:'',
        noClick: true,
				date: '',
				RECTIFICATIONTIME: '',
				buttonloading: false,
				CHECK_TIME: '',
				imgList: [],
				id: '',
				pd: [],
				hs: [],
				files: [],
				files2: [],
				files3: [],
				files4: [],
				files5: [],
        videoList: [],
				CHECKDESCR: '',
				basePath: basePath,
				baseImgPath: baseImgPath,
				ISQUALIFIED: '1',
				check: [],
        modalShow: false,
        videoSrc: '',
        now:formatDate(new Date(),'yyyy-MM-dd')

			}
		},
		onLoad(e) {
			this.id = e.id;
			// let now = new Date();
			// this.date = formatDate(now, 'yyyy-MM-dd');
			this.getData();
			loginSession();
		},
		// filters: {
		// 	formatDate(time) {
		// 		time = time * 1
		// 		let date = new Date(time)
		// 		return formatDate(date, 'yyyy-MM-dd hh:mm')
		// 	}
		// },
		methods: {
      fullScreenHandler(e) {
        if (uni.getSystemInfoSync().platform == "ios") { return }
      },
			getData() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/hidden/goEdit',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						HIDDEN_ID: _this.id,
            CORPINFO_ID:loginUser.CORPINFO_ID,
            USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
						console.info(res);
						if ("success" == res.data.result) {
							uni.hideLoading();
							_this.pd = res.data.pd; //参数map
							_this.hs = res.data.hs; //参数map
              for (let i = 0; i < res.data.hImgs.length; i++) {
                if(res.data.hImgs[i].FILEPATH.substring(res.data.hImgs[i].FILEPATH.lastIndexOf(".") + 1, res.data.hImgs[i].FILEPATH.length) === 'mp4'){
                  _this.videoList.push(res.data.hImgs[i])
                }else {
                  _this.files.push(res.data.hImgs[i])
                }
              }
              _this.videoList = res.data.hiddenVideo;
							// _this.files = res.data.hImgs;
							_this.files2 = res.data.rImgs;
							_this.files3 = res.data.cImgs;
							_this.files4 = res.data.sImgs;
							_this.files5 = res.data.pImgs;
						} else if ("exception" == data.result) {
							uni.showToast({
								title: '错误',
								duration: 2000
							});
						}
					}
				});
			},

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

			//图片上传
			ChooseImage() {
				var _this = this;
				uni.chooseImage({
					count: 4-this.imgList.length, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '新泰安全',
					content: '确定要删除这张图片吗？',
					cancelColor: "#000000",
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			textareaAInput(e) {
				this.CHECKDESCR = e.detail.value
			},
			textareaAInputREPULSE_CAUSE(e) {
				this.REPULSE_CAUSE = e.detail.value
			},
			async goSubmit() {
				var _this = this;
				if (_this.ISQUALIFIED == '1') {
					if (!_this.CHECKDESCR) {
						uni.showToast({
							icon: 'none',
							title: '请填验收描述',
							duration: 1500
						});
						return;
					}
					if (!_this.CHECK_TIME) {
						uni.showToast({
							icon: 'none',
							title: '请选择验收时间',
							duration: 1500
						});
						return;
					}
					// if (_this.imgList.length <= 0) {
					// 	uni.showToast({
					// 		icon: 'none',
					// 		title: '请上传验收照片',
					// 		duration: 1500
					// 	});
					// 	return;
					// }
				}
        if (_this.ISQUALIFIED == '0') {
          if (!_this.REPULSE_CAUSE) {
            uni.showToast({
              icon: 'none',
              title: '请填写重新整改原因',
              duration: 1500
            });
            return;
          }

        }
        var fileList = [];
        for (var i = 0; i < _this.imgList.length; i++) {
          var file = {};
          file.type = 5;
          file.filePath = _this.imgList[i];
          file.FOREIGN_KEY = _this.id;
          fileList.push(file);
        }
        uni.showLoading({
          title: '数据提交中'
        })
        this.buttonloading = true
        const FILE_IDS = []
        await _this.uploadPromise(fileList,FILE_IDS)
        await _this.submit(FILE_IDS)
        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);
			},
      async uploadPromise(tempFilePaths,FILE_IDS) {
        if (tempFilePaths.length == 0) {
          uni.hideLoading();
          this.buttonloading = false
          return
        }
        for (let i = 0; i < tempFilePaths.length; i++) {
          await this.uploadImg(tempFilePaths[i],FILE_IDS)
        }
      },
			uploadImg(file,FILE_IDS) {
        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':'',
              CORPINFO_ID: loginUser.CORPINFO_ID,
              USER_ID: loginUser.USER_ID,
            },
            success: (res) => {
              res.data = JSON.parse(res.data)
              FILE_IDS.push(res.data.pd.IMGFILES_ID)
              resolve();
            },
            fail: (err) => {
              uni.hideLoading();
              this.buttonloading = false
              uni.showModal({
                content: err.errMsg,
                showCancel: false
              });
            }
          })
        })
			},
			submit(FILE_IDS) {
				return new Promise((resolve, reject) => {
					var _this = this;
					uni.request({
						url: basePath + "/app/hidden/check", //提交接口
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							ISQUALIFIED: _this.ISQUALIFIED,
							CHECKDESCR: _this.CHECKDESCR,
							CHECK_TIME: _this.CHECK_TIME,
              REPULSE_CAUSE: _this.REPULSE_CAUSE,
							HIDDEN_ID: _this.id,
							CHECKOR: loginUserId,
							CORPINFO_ID:loginUser.CORPINFO_ID,
							USER_ID:loginUser.USER_ID,
              FILE_IDS:FILE_IDS.join(',')
						},
						success: (res) => {
							if ("success" == res.data.result) {
								_this.check = res.data.check;
								resolve();
							} else {
								uni.showToast({
									title: '错误',
									duration: 2000
								});
							}
              uni.hideLoading();
              this.buttonloading = false

						}
					});
				})
			},
			changeDate(e) {
				this.CHECK_TIME = e.detail.value
			},
			radio(e) {
				this.ISQUALIFIED = e
			},
			ViewShowImage(e) {
				let files = [];
				for (var i = 0; i < this.files.length; i++) {
					files.push(baseImgPath + this.files[i].FILEPATH)
				}
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.index
				});
			},
			ViewShowImage2(e) {
				let files = [];
				for (var i = 0; i < this.files2.length; i++) {
					files.push(baseImgPath + this.files2[i].FILEPATH)
				}
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.index
				});
			},

			ViewShowImage4(e) {
				let files = [];
				for (var i = 0; i < this.files4.length; i++) {
					files.push(baseImgPath + this.files4[i].FILEPATH)
				}
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.index
				});
			},
			ViewShowImage5(e) {
				let files = [];
				for (var i = 0; i < this.files5.length; i++) {
					files.push(baseImgPath + this.files5[i].FILEPATH)
				}
				uni.previewImage({
					urls: files,
					current: e.currentTarget.dataset.index
				});
			},
      playVideo(e) {
        this.videoSrc = e.currentTarget.dataset.src
        this.modalShow = true
      }
		}
	}
</script>

<style>
	.selected {
		display: flex;
		align-items: center;
	}

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

	.cu-btn {
		border-radius: 0;
		width: 100%;
		height: 84upx;
		font-weight: bold;
	}

	.group {
		display: flex;
		align-items: center;
	}
</style>
