<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
	<Navbar2 title="存取证申请" :showRightText="false" :isBack="false" :goTo="'/pages/certificateExamCenter/certificateApply/index'"/>
	<view class="apply-view">
		<view class="apply-item">
			<view style="margin-bottom: 10px;">存 / 取<span style="color: red;">*</span> </view>
			<view><uni-data-checkbox v-model="apply.applyType" :localdata="checkBoxLocalData" @change="changeApplyType"/></view>
		</view>
		<view class="apply-item" style="height: auto;">
			<view style="margin-bottom: 10px;">证件编号<span style="color: red;">*</span> </view>
			<view > 
				<zxz-uni-data-select v-model="apply.certificateNos" multiple="true" :localdata="certificateList"></zxz-uni-data-select>
				<!-- <uni-data-select v-model="apply.certificateNos" multiple="true" :localdata="certificateList"></uni-data-select> -->
			</view>
		</view>
		<view class="apply-item" v-if="apply.applyType==1">
			<view style="margin-bottom: 10px;">证件柜<span style="color: red;">*</span> </view>
			<view><uni-data-select v-model="apply.deviceId" :localdata="deviceList" border="none"></uni-data-select></view>
		</view>
		
		<view class="apply-item">
			<view style="margin-bottom: 10px;">证件用途<span style="color: red;">*</span> </view>
			<view><uni-data-checkbox v-model="apply.applyReason" :localdata="checkBoxLocalData2" /></view>
		</view>
		<view class="apply-item">
			<view style="margin-bottom: 10px;">事由<span style="color: red;">*</span></view>
			<view><uni-easyinput type="text" :inputBorder="false" v-model="apply.applyDetail"  maxlength="50" placeholder="请输入" /></view>
		</view>
		<view class="apply-item" v-if="apply.applyType==2">
			<view style="margin-bottom: 10px;">计划出国（境）地点<span style="color: red;">*</span></view>
			<view><uni-easyinput type="text" :inputBorder="false" v-model="apply.exitAddr"  maxlength="30" placeholder="请输入" /></view>
		</view>
		<view class="apply-item" v-if="apply.applyType==2">
			<view style="margin-bottom: 10px;">计划出国（境）日期<span style="color: red;">*</span></view>
			<view><uni-datetime-picker type="date" v-model="apply.exitTime" :end="endDate" @change="handleStartDateChange" :clear-icon="false" format="YYYY-MM-DD" /></view>
		</view>
		<view class="apply-item" v-if="apply.applyType==2">
			<view style="margin-bottom: 10px;">计划回国（境）日期<span style="color: red;">*</span></view>
			<view><uni-datetime-picker type="date" v-model="apply.entryTime" :start="startDate" @change="handleEndDateChange":clear-icon="false" format="YYYY-MM-DD" /></view>
		</view>
		<view class="apply-item" v-if="apply.applyType==2">
			<view style="margin-bottom: 10px;">允许他人代办<span style="color: red;">*</span> </view>
			<view><uni-data-checkbox v-model="apply.isThrid" :localdata="checkBoxLocalData3" @change="changeIsThrid"/></view>
		</view>
		<view class="apply-item" v-if="apply.isThrid==1">
			<view style="margin-bottom: 10px;">代办人姓名<span style="color: red;">*</span></view>
			<view><uni-data-select v-model="apply.thridId" :localdata="thridManList" @change="changThridId"></uni-data-select></view>
		</view>
		<view class="apply-item" v-if="apply.isThrid==1">
			<view style="margin-bottom: 10px;">代办人身份证号<span style="color: red;">*</span></view>
			<view><uni-easyinput type="text" :inputBorder="false" v-model="apply.thridIdNumber" :disabled="true"  maxlength="30" placeholder="请输入" /></view>
		</view>
		<view class="apply-item">
			<view style="margin-bottom: 10px;">备注</view>
			<view><uni-easyinput type="text" :inputBorder="false" v-model="apply.remark"  maxlength="50" placeholder="请输入" /></view>
		</view>
		<view class="apply-item" style="height: 120px;">
			<view style="margin-bottom: 10px;">附件</view>
			<view>
				<!-- multiple -->
				<u-upload
				  :fileList="fileList"
				  @afterRead="afterRead"
				  @delete="deletePic"
				  :maxCount="5"
				  width="60" height="60"
				>
				  <view class="upload-btn">
				    <u-icon name="camera" size="28" color="#666666"></u-icon> 
				  </view>
				</u-upload>
			</view>
		</view>
	</view>
	
	<!-- <view style="width: 100%;background: #fff;padding: 20rpx;">
		<view style="font-weight: 600;">流程</view>
		<u-steps current="0" direction="column" style="margin: 20rpx;">
			<u-steps-item title="李四">
				<view slot="desc"> 一级审批 10:35 </view>
			</u-steps-item>
			<u-steps-item title="王五" desc="10:35">
				<view slot="desc"> 二级审批 10:35 </view>
			</u-steps-item>
			<u-steps-item title="张三" desc="10:35">
				<view slot="desc"> 三级级审批 10:35 </view>
			</u-steps-item>
		</u-steps>
	</view> -->
	 

	<view style="width: 100%;padding: 20rpx;margin: 40rpx auto;background: #fff;">
		<view @click="submitApply" style="width: 92%;height: 80rpx;margin: 20rpx auto;background: #3888FF;color: #fff;border-radius: 10rpx;text-align: center;line-height: 80rpx;" >
			发起申请
		</view>  
	</view>
	
</template>

<script> 
import { applyCertificateNoListApi,thridListApi,addCertificateApplyApi,editCertificateApplyApi,deviceListApi } from '@/api/certificateExamCenter/index.js';
import { pathToBase64, base64ToPath } from 'image-tools';
import { uploadBase64,uploadImg } from "@/api/upload"; 
export default {
    data() {
      return { 
		fontValue:uni.getStorageSync('fontSize') || 8,  
		certificateList:[],
		thridManList:[],
		columns: [[
			{text:"往来国外",value:'1'},
			{text:"往来台湾通行证",value:'2'},
			{text:"往来香港通行证",value:'3'},
		]],
		show:false,
		// 单选数据源
		checkBoxLocalData: [{text: '存证',value: 1}, {text: '取证',value: 2}],
		checkBoxLocalData2: [{text: '公事',value: 1}, {text: '私事',value: 2}],
		checkBoxLocalData3: [{text: '是',value: 1}, {text: '否',value: 2}],
		isSumbit:false,
		apply:{
			applyType:1, 
			applyReason:1,
			applyLocation:"", 
			isThrid:2,
			thridId:"",
			thridName:"",
			thridIdNumber:"",
			applyDetail:"",
			exitAddr:"", 
			exitTime:"", 
			entryTime:"",
			remark:"", 
			certificateNos:[],
		},
		startDate: '', // 开始日期
	    endDate: '',  // 结束日期
		fileList: [],
		deviceList: [],
      }
    }, 
	onLoad(options) {  
		this.getCertificateList()
		this.getDeviceList()
		this.getThridList()
		this.apply = JSON.parse(options.apply) 
		console.log(this.apply)
	},
    methods: {
		//获取证件柜列表
		async getDeviceList() {  
			const params = {}
			this.$set(this.apply,"deviceId","") 
			this.deviceList=[]
			try {
			const res = await deviceListApi(params)
				console.log('?? ~ getList ~ res:', res)
				if(res&&res.length>0){
					res.forEach(item=>{
						this.deviceList.push({value:item.deviceId,text:item.deviceName})
					})
				}
			} catch (error) {
				console.log(error)
			}
		},
		//获取证件列表
		async getCertificateList() {  
			const params = {
				applyType:this.apply.applyType,
				userId:uni.getStorageSync("userId")
			}
			this.$set(this.apply,"certificateNos",[]) 
			this.certificateList=[]
			try {
			const res = await applyCertificateNoListApi(params)
				console.log('?? ~ getList ~ res:', res)
				if(res&&res.length>0){
					res.forEach(item=>{
						this.certificateList.push({value:item.certificateNo,text:item.certificateNo+"-"+item.certificateTypeName})
					})
				}
			} catch (error) {
				console.log(error)
			}
		},
		//获取代办人列表
		async getThridList() {  
			const params = { 
				userId:uni.getStorageSync("userId")
			} 
			this.thridManList=[]
			try {
			const res = await thridListApi(params)
				console.log('?? ~ getList ~ res:', res)
				if(res.data&&res.data.length>0){
					res.data.forEach(item=>{
						this.thridManList.push({value:item.id,text:item.name,idNumber:item.idNumber})
					})
				}
			} catch (error) {
				console.log(error)
			}
		}, 
		//更改申请类型
		changeApplyType(e){
			console.log('e:',this.apply.applyType);
			this.getCertificateList()
			this.$set(this.apply,"deviceId","")
			this.$set(this.apply,"exitAddr","")
			this.$set(this.apply,"exitTime","") 
			this.$set(this.apply,"entryTime","") 
			this.$set(this.apply,"isThrid",2) 
			this.$set(this.apply,'thridId',"")
			this.$set(this.apply,'thridName',"")
			this.$set(this.apply,'thridIdNumber',"")
		},
		changeIsThrid(e){
			this.$set(this.apply,'thridId',"")
			this.$set(this.apply,'thridName',"")
			this.$set(this.apply,'thridIdNumber',"")
		},
		changThridId(e){
			console.log('e:',e); 
			let index = this.thridManList.findIndex(v=>v.value==e) 
			console.log(index)
			this.$set(this.apply,'thridName',this.thridManList[index].text)
			this.$set(this.apply,'thridIdNumber',this.thridManList[index].idNumber)
		}, 
		submitApply() { 
			console.log(this.isSumbit)
			let arr = []
			let arr1 = []
			if(this.fileList&&this.fileList.length>0){
				this.fileList.forEach(item=>{
					arr.push(item.url)
					arr1.push(item.name)
				})
			}
			//fileUrls 附件 数组 
			this.apply.fileUrls = arr
			this.apply.fileNames = arr1
			const regex = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
			console.log(this.apply)
			if(this.apply.certificateNos.length==0){
				uni.$u.toast(`请选择证件编号！`) 
			}else if(this.apply.applyDetail==""){
				uni.$u.toast(`事由不能为空`)  
			}else if(this.apply.isThrid==1){
				if(this.apply.thridName==""){
					uni.$u.toast(`代办人姓名不能为空`) 
				}else if(this.apply.thridIdNumber==""){
					uni.$u.toast(`代办人身份证号不能为空`) 
				}else if(this.apply.applyType==2){
					if(this.apply.exitAddr==""){
						uni.$u.toast(`计划出国（境）地点不能为空`)   
						return false
					}else if(this.apply.exitTime==""){	
						uni.$u.toast(`计划出国（境）日期不能为空`)
						return false
					}else if(this.apply.entryTime==""){
						uni.$u.toast(`计划回国（境）日期不能为空`) 
						return false
					}else if(!this.isSumbit){ 
						console.log("请求添加")
						this.insertApply(); 
					}
				}else if(!this.isSumbit){ 
					console.log("请求添加")
					this.insertApply(); 
				}
			}else if(this.apply.isThrid==2){    
				this.apply.thridId=""
				this.apply.thridName=""
				this.apply.thridIdNumber=""
				if(this.apply.applyType==2){
					if(this.apply.exitAddr==""){
						uni.$u.toast(`计划出国（境）地点不能为空`)   
						return false
					}else if(this.apply.exitTime==""){	
						uni.$u.toast(`计划出国（境）日期不能为空`)
						return false
					}else if(this.apply.entryTime==""){
						uni.$u.toast(`计划回国（境）日期不能为空`) 
						return false
					}else if(!this.isSumbit){ 
						console.log("请求添加")
						this.insertApply(); 
					}
				}else if(this.apply.applyType==1){
					if(this.apply.deviceId==""){
						uni.$u.toast(`证件柜不能为空`)   
						return false
					}else if(!this.isSumbit){ 
						console.log("请求添加")
						this.insertApply(); 
					}
				}else if(!this.isSumbit){ 
					console.log("请求添加")
					this.insertApply(); 
				} 
			}
		}, 
		async insertApply(){
			this.isSumbit=true
			setTimeout(()=>{
				this.isSumbit=false 
			},1000) 
			this.apply.applyState=0;
			this.apply.userId=uni.getStorageSync('userId');
			let param = this.apply; 
			const res = await addCertificateApplyApi(param); 
			if(res.code==200){
				uni.$u.toast(`提交成功！`,1000)
				setTimeout(()=>{ 
					uni.navigateBack()
				},1000)
			} 
		},
		// 新增图片
		async afterRead(event) {
			console.log(event)
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: "uploading",
					message: "上传中",
				});  
			});
			console.log(lists)
			for (let i = 0; i < lists.length; i++) {
			  const result = await this.uploadFilePromise(lists[i].url);
			  console.log(result)
			  let item = this[`fileList${event.name}`][fileListLen];
			  this[`fileList${event.name}`].splice(
				fileListLen,
				1,
				Object.assign(item, {
				  status: "success",
				  message: "",
				  name:'附件'+(i+1),
				  url: result.url,
				})
			  );
			  fileListLen++;
			}
		},
		//上传接口
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				this.imgToBase64(url).then(base64 => {
					 let param = { 
						"base64File":base64
					 } 
					uploadBase64(param).then(res => {
						if(res.code==200){
							res.data.base64 = base64
							resolve(res.data) 
						}
					})
				})
			});
		},
		imgToBase64(data) {
		  return new Promise((resolve, reject) => {
					pathToBase64(data).then(base64 => {
						resolve(base64)
					}).catch(error => {
						console.error(error)
						reject(error)
					})
		  })
		},
		deletePic(event) {
			this.fileList.splice(event.index, 1);
		},
		handleStartDateChange(value) {
		  this.startDate = value;
		  // 更新结束日期的可选范围
		  // this.updateEndDateRange();
		},
		handleEndDateChange(value) {
		  this.endDate = value;
		  // 如果需要，可以在这里添加额外的逻辑
		},
	}
}
</script>

<style lang="scss">
  page {
    background-color: #F5F5F5;
  }
  .apply-view{
	  width: 100%;
	  height: auto;
	  margin: 40rpx auto;
  }
  .apply-item{
	  width: 100%;
	  height: 80px;
	  padding: 20rpx;
	  background: #FFF;
	  border-bottom: 1px solid rgba(209,211,215,0.5);
	  font-size: 28rpx;
  }
  .upload-btn {
    width: 120rpx;
    height: 120rpx;
    // background-color: #f7f8fa;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 1px dashed #000;
    border-radius: 8rpx; 
    .upload-text {
      font-size: 24rpx;
      color: #666666;
      margin-top: 10rpx;
    }
  }
</style>
