<template>
  <view class="page">
    <u-navbar class="u-navbar" title="欠薪维权申诉" placeholder @leftClick="leftClick" leftIconColor="#fff"  bgColor="#00337A"  :titleStyle="{ color: '#FFF', fontSize: '32rpx' }"/>
	<view class="tab-box">
		<view class="tab-item" :class="currentTabIndex == 0 ? 'active' : ''" @click="currentTabIndex = 0">
			填写申述
			<view class="activeLine" v-if="currentTabIndex == 0"></view>
		</view>
		<view class="tab-item" :class="currentTabIndex == 1 ? 'active' : ''" @click="currentTabIndex = 1">
			申诉回复结果
			<view class="activeLine" v-if="currentTabIndex == 1"></view>
		</view>
	</view>
	
	<scroll-view class="content" scroll-y="true">
		<view class="view-box" v-if="currentTabIndex == 0">
			<view class="title-view">
				基本信息
			</view>
			<u--form class="form-box" :model="formData" :rules="rules" ref="cForm">
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>欠薪单位</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='oweCompany'  style="width:70%;height: 100%;" >
						<u--input v-model="formData.oweCompany" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>欠薪项目</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='oweProject' style="width:70%;height: 100%;" >
						<u--input v-model="formData.oweProject" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>欠薪金额</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='oweMoney' style="width:70%;height: 100%;" >
						<u--input v-model="formData.oweMoney" type="number" placeholder="请输入" maxlength="7"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>单位地址</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='address' style="width:70%;height: 100%;" >
						<u--input v-model="formData.address" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>申请人姓名</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='applayUser' style="width:70%;height: 100%;" >
						<u--input v-model="formData.applayUser" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>身份证号码</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='idCard' style="width:70%;height: 100%;" >
						<u--input v-model="formData.idCard" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
				<view class="form-input-box">
					<view style="width:25%;height: 100%;">
						<text>电话号码</text> <text style="color: red;">*</text>
					</view>
					<u-form-item prop='phone' style="width:70%;height: 100%;" >
						<u--input v-model="formData.phone" type="text" placeholder="请输入" maxlength="40"  border="surround" clearable></u--input>
					</u-form-item>
				</view>
			</u--form>
			
			<view class="title-view">
				欠薪时间 <text style="color: red;">*</text>
			</view>
			<view style="width: 90%;margin: 20rpx auto;padding-bottom: 20rpx;">
				<uni-datetime-picker v-model="range" type="daterange" rangeSeparator="至"/>
			</view>
			
			<view class="title-view">
				有效依据
			</view>
			<view class="view-item" style="display: block;">
				<view>合同照片 <text style="color: red;">*</text></view>
				<view class="img-box"> 
					<view class="img-item upload-btn" @click="openPhotograph(1)">
						<image class="img" src="@/static/realName/tianjia-img.png" mode=""></image>
					</view>
					<view class="img-item" v-if="contractImgUrl!=''">
						<image class="img" :src="contractImgUrl" mode=""></image>
					</view>
				</view>
			</view>
			<view class="view-item" style="display: block;">
				<view>考勤记录 <text style="color: red;">*</text></view>
				<view class="img-box"> 
					<view class="img-item upload-btn" @click="openPhotograph(2)">
						<image class="img" src="@/static/realName/tianjia-img.png" mode=""></image>
					</view>
					<view class="img-item" v-if="attendanceImgUrl!=''">
						<image class="img" :src="attendanceImgUrl" mode=""></image>
					</view>
				</view>
			</view>
			<view class="view-item" style="display: block;">
				<view>工资信息 <text style="color: red;">*</text></view>
				<view class="img-box"> 
					<view class="img-item upload-btn" @click="openPhotograph(3)">
						<image class="img" src="@/static/realName/tianjia-img.png" mode=""></image>
					</view>
					<view class="img-item" v-if="wageImgUrl!=''">
						<image class="img" :src="wageImgUrl" mode=""></image>
					</view>
				</view>
			</view>
			<view class="view-item" style="display: block;">
				<view>其他依据</view>
				<view class="img-box"> 
					<view class="img-item upload-btn" @click="openPhotograph(4)">
						<image class="img" src="@/static/realName/tianjia-img.png" mode=""></image>
					</view>
					<view class="img-item" v-if="otherImgUrl!=''">
						<image class="img" :src="otherImgUrl" mode=""></image>
					</view>
				</view>
			</view>
			
			<view style="padding-bottom: 50rpx;">
				<view class="sumbit-btn" @click="sumbit">确 定</view>
			</view>
			
		</view>
		<view class="view-box list-box" v-if="currentTabIndex == 1">
			<view v-if="listData.length==0" style="width: 96%;height: 40vh;display: flex;flex-direction: column;justify-content: center;align-items: center;" >
				<image src="../../../../static/realName/noData.png" style="width: 100rpx;height: 120rpx;" mode=""></image>
				<view>暂无数据</view>
			</view>
			<u-list height="75vh" v-if="listData.length>0">
				<u-list-item  v-for="(item, index) in listData" :key="index">
					<view class="list-item" @click="goDetail(item)">
						<view class="content-box">
							<view class="item-text" >
								<text class="label" style="font-weight: bold;">姓名：</text>
								<text class="info">{{item.applayUser}}</text>
							</view>
							<view class="item-text">
								<text class="label" style="font-weight: bold;">身份证号：</text>
								<text class="info">{{item.idCard}}</text>
							</view>
							<view class="item-text">
								<text class="label" style="font-weight: bold;">申诉上传时间：</text>
								<text class="info">{{item.representationTime}}</text>
							</view>
							<view class="item-text">
								<text class="label" style="font-weight: bold;">申诉回复结果：</text>
								<text class="info">{{item.replyContent}}</text>
							</view>
							
						</view>
					</view>
				</u-list-item>
			</u-list>
		</view>
	</scroll-view>
  </view>
</template>

<script>
import config from '@/config';
import { pathToBase64, base64ToPath } from 'image-tools';
export default {
  data() {
    return {
		currentTabIndex:0, 
		formData:{
			"id":"",//uuid
			"oweCompany":"",//欠薪单位
			"oweProject":"",//欠薪项目
			"address":"",//单位地址
			"applayUser":"",//申请人姓名
			"idCard":"",//身份证号码
			"phone":"",//电话号码
			"oweMoney":"",//欠薪金
			"oweStartDay":"",//欠薪开始时间
			"oweEndDay":"",//欠薪结束时间
			"representationTime": "",
			"addTime": "",
			"uploadUserId": uni.getStorageSync('realNameUser').userId,
			"currentDay": "",
			"isActive": "1",
			"replyStatus": "0",
			"replyContent": "",
		},
		range: [],
		rules: {
			'oweCompany': {
				type: 'string',
				required: true,
				message: '请填写欠薪单位',
				trigger: ['blur', 'change']
			},
			'oweProject': {
				type: 'string',
				required: true,
				message: '请填写欠薪项目',
				trigger: ['blur', 'change']
			},
			'address': {
				type: 'string',
				required: true,
				message: '请填写单位地址',
				trigger: ['blur', 'change']
			},
			'applayUser': {
				type: 'string',
				required: true,
				message: '请填写申请人姓名',
				trigger: ['blur', 'change']
			},
			'idCard': {
				type: 'string',
				required: true,
				message: '请填写身份证号码',
				trigger: ['blur', 'change']
			},
			'phone': {
				type: 'string',
				required: true,
				message: '请填写电话号码',
				trigger: ['blur', 'change']
			},
			'oweMoney': {
				type: 'string',
				required: true,
				message: '请填写欠薪金额',
				trigger: ['blur', 'change']
			},
		},
		contractPath:'', 
		attendancePath:'',
		wagePath:'',
		otherPath:'',
		contractImgUrl:'',
		attendanceImgUrl:'',
		wageImgUrl:'',
		otherImgUrl:'',
		listData:[] 
    }
  },
  onLoad() {
	
  },
  onShow() {
  },
  watch: {
	currentTabIndex: function(newVal, oldVal) {
		if (newVal == 1) {
			this.getSafeguardingInfoList()
		} else {
			
		}
	}
  },
 methods: {
	getSafeguardingInfoList(){
		let param={
			uploadUserId:uni.getStorageSync('realNameUser').userId
		}
		uni.request({
			url: config.realAppUrl+'/safeguardingInfo/getSafeguardingInfoList',
			method: 'post',
			data: param,
			header: {
				'Content-Type': 'application/json',
				Authorization: uni.getStorageSync('realNameToken')	
			},
			success: res => {
			console.log(res)
				res = res.data;
				if(res.code==200){
					this.listData=res.data;
				}else{
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			fail: err => {
				console.log(err)
			}
		}) 
	},
	goDetail(item){
		console.log(item)
		uni.navigateTo({
			url: `/pages/realName/workbench/safeguarding/detail?id=${item.id}` 
		})
	},
    //提交
	sumbit(){
		this.$refs.cForm.validate().then(res => {
			this.formData.id=this.uuid()
			this.formData.representationTime = this.timeFormat(null,'yyyy-mm-dd hh:MM:ss');
			this.formData.addTime = this.timeFormat(null,'yyyy-mm-dd hh:MM:ss');
			this.formData.currentDay = this.timeFormat(null,'yyyy-mm-dd');
			var pattern = /^1[3-9]\d{9}$/;
			if(!this.verifyidNumber(this.formData.idCard)){
				uni.$u.toast('请填写正确身份证号');
			}else if(!pattern.test(this.formData.phone)){
				uni.$u.toast('请填写正确手机号码');
			}else if(this.range.length==0){
				uni.$u.toast('请选择欠薪时间');
			}else if(this.contractPath==''){
				uni.$u.toast('请上传合同照片图片');
			}else if(this.attendancePath==''){
				 uni.$u.toast('请上传考勤记录图片');
			}else if(this.wagePath==''){
				uni.$u.toast('请上传工资信息图片');
			}else{
				this.formData.oweStartDay=this.range[0]
				this.formData.oweEndDay=this.range[1]
				console.log(this.formData)
				uni.request({
				  url: config.realAppUrl+'/safeguardingInfo/uploadSafeguardingInfo',
				  method: 'post',
				  data: this.formData,
				  header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					Authorization: uni.getStorageSync('realNameToken')
				  },
				  success: res => {
				    console.log(res)
					res = res.data;
					if(res.code==200){
						uni.showToast({
							title: res.data,
							icon: 'none'
						})
						this.formData={
							"id":"",//uuid
							"oweCompany":"",//欠薪单位
							"oweProject":"",//欠薪项目
							"address":"",//单位地址
							"applayUser":"",//申请人姓名
							"idCard":"",//身份证号码
							"phone":"",//电话号码
							"oweMoney":"",//欠薪金
							"oweStartDay":"",//欠薪开始时间
							"oweEndDay":"",//欠薪结束时间
							"representationTime": "",
							"addTime": "",
							"uploadUserId": uni.getStorageSync('realNameUser').userId,
							"currentDay": "",
							"isActive": "1",
							"replyStatus": "0",
							"replyContent": "",
						}
						this.range=[]
						this.uploadPhoto(this.contractPath,1)
						this.uploadPhoto(this.attendancePath,2)
						this.uploadPhoto(this.wagePath,3)
						if(this.otherPath!=''){
							this.uploadPhoto(this.otherPath,4)
						}
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				  },
				  fail: err => {
					console.log(err)
				  }
				}) 
			}
		}).catch(errors => {
			console.log(errors)
			uni.$u.toast('填写数据存在问题')
		})
	},
	// 拍照录入
	openPhotograph(type) {
	  uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['camera'],
		success: res => {
			console.log('?? ~ res-拍照:', res)
			this.imgToBase64(res.tempFilePaths[0]).then(base64 => {
				if(type==1){
					this.contractImgUrl=base64; 
					this.contractPath=res.tempFilePaths[0];
				}
				if(type==2){
					this.attendanceImgUrl=base64;
					this.attendancePath=res.tempFilePaths[0];
				}
				if(type==3){
					this.wageImgUrl=base64;
					this.wagePath=res.tempFilePaths[0];
				}
				if(type==4){
					this.otherImgUrl=base64;
					this.otherPath=res.tempFilePaths[0];
				}
			})
		},
		fail: err => { 
		  console.log('?? ~ err:', err)
		}
	  })
	},
	//上传图片
	uploadPhoto(path,type){
		uni.uploadFile({
			url: config.realFileUrl+`file/upload`, //服务器地址
			fileType:"image",//ZFB必填,不然报错
			filePath: path,//这个就是我们上面拍照返回或者先中照片返回的数组
			name: "imgFile",
			formData: {
				photoType:'safeguarding',
			},
			success: (uploadFileRes) => {
				console.log(uploadFileRes)
				if(uploadFileRes.statusCode==200){
					this.uploadSafeguardingPhoto(JSON.parse(uploadFileRes.data).data.url,type)
				}else{
					uni.$u.toast('上传失败');
				}
				
			},
			fail: err => {
				uni.$u.toast('上传失败');
				console.log(err)
			}
		});
	},
	//更新图片
	uploadSafeguardingPhoto(path,type){
		let obj={
			"id":this.uuid(),
			"safeguardingId":this.formData.id,
			"path":path,
			"type":type,
			"uploadUserId": uni.getStorageSync('realNameUser').userId,
			"addTime":this.timeFormat(null,'yyyy-mm-dd hh:MM:ss'),
			"currentDay":this.timeFormat(null,'yyyy-mm-dd')
		}
		console.log(obj)
		uni.request({
		  url: config.realAppUrl+'/safeguardingInfo/uploadSafeguardingPhoto',
		  method: 'post',
		  data: obj,
		  header: {
			'Content-Type': 'application/x-www-form-urlencoded',
			Authorization: uni.getStorageSync('realNameToken')
		  },
		  success: res => {
		    console.log(res)
			res = res.data;
			if(res.code==200){
				if(type==1){
					this.contractImgUrl=""; 
					this.contractPath="";
				}
				if(type==2){
					this.attendanceImgUrl="";
					this.attendancePath="";
				}
				if(type==3){
					this.wageImgUrl="";
					this.wagePath="";
				}
				if(type==4){
					this.otherImgUrl="";
					this.otherPath="";
				}
				uni.showToast({
					title: '图片已上传',
					icon: 'none'
				})
			}else{
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		  },
		  fail: err => {
			console.log(err)
		  }
		}) 
	},

	imgToBase64(data) {
	  return new Promise((resolve, reject) => {
		pathToBase64(data)
		  .then(base64 => {
			resolve(base64)
		  })
		  .catch(error => {
			console.error(error)
			reject(error)
		  })
	  })
	},
	//身份证校验
	verifyidNumber(idNumber) {
	  // 校验长度
	  if (idNumber.length !== 18) {
	    return false;
	  }
	  // 校验前17位是否为数字
	  if (!/^\d{17}$/.test(idNumber.substr(0, 17))) {
	    return false;
	  }
	  
	  // 校验最后一位
	  var weightFactor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	  var checkCodeList = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
	  var checkSum = 0;
	  for (var i = 0; i < 17; i++) {
	    checkSum += parseInt(idNumber.charAt(i)) * weightFactor[i];
	  }
	  var checkCodeIndex = checkSum % 11;
	  if (idNumber.charAt(17).toUpperCase() !== checkCodeList[checkCodeIndex]) {
	    return false;
	  }
	  
	  return true;
	},
	timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
		let date
		// 若传入时间为假值，则取当前时间
		if (!dateTime) {
			date = new Date()
		}
		// 若为unix秒时间戳，则转为毫秒时间戳（逻辑有点奇怪，但不敢改，以保证历史兼容）
		else if (/^\d{10}$/.test(dateTime?.toString().trim())) {
			date = new Date(dateTime * 1000)
		}
		// 若用户传入字符串格式时间戳，new Date无法解析，需做兼容
		else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
			date = new Date(Number(dateTime))
		}
		// 处理平台性差异，在Safari/Webkit中，new Date仅支持/作为分割符的字符串时间
		// 处理 '2022-07-10 01:02:03'，跳过 '2022-07-10T01:02:03'
		else if (typeof dateTime === 'string' && dateTime.includes('-') && !dateTime.includes('T')) {
			date = new Date(dateTime.replace(/-/g, '/'))
		}
		// 其他都认为符合 RFC 2822 规范
		else {
			date = new Date(dateTime)
		}
	
		const timeSource = {
			'y': date.getFullYear().toString(), // 年
			'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
			'd': date.getDate().toString().padStart(2, '0'), // 日
			'h': date.getHours().toString().padStart(2, '0'), // 时
			'M': date.getMinutes().toString().padStart(2, '0'), // 分
			's': date.getSeconds().toString().padStart(2, '0') // 秒
			// 有其他格式化字符需求可以继续添加，必须转化成字符串
		}
	
		for (const key in timeSource) {
			const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
			if (ret) {
				// 年可能只需展示两位
				const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
				formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
			}
		}
		return formatStr
	},
	uuid() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 32; i++) {
	    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	    s[8] = s[13] = s[18] = s[23];
	    var uuid = s.join("");
	    return uuid;
	},
    // 返回
    leftClick() {
      console.log('返回')
      uni.navigateBack({
      	delta: 1 // 返回
      });
    }
  },

}
</script>

<style lang="scss">
/deep/.uni-date .uni-date-x{
	background: #EFEFEF;
}
	
.page {
	width: 100vw;
	height: 100vh;
	background-color: #EFEFEF;
	box-sizing: border-box;
	// padding: 0 20px;
	.tab-box {
		width: 100%;
		margin: 20rpx auto;
		display: flex;
		justify-content: space-between;
		.tab-item {
			height: 70upx;
			width: 45%;
			font-size: 30upx;
			text-align: center;
			line-height: 70upx;
			color: #666;
		}
		.active {
			color: #00337A;
			border-radius: 10upx 10upx 0 0;
			font-weight: bold;	
		}
		.activeLine{
			background: #00337A;
			border-radius: 10upx;
			width: 100%;
			height: 6upx;
		}
	}
	.content{
		width: 100%;
		height: 87vh;
		margin-top: 20rpx;
		// padding-bottom: 80rpx;
		background-color: #EFEFEF;
	}
	.view-box{
		width: 100%;
		height: auto;
		margin: 20rpx auto;
		border-radius: 10rpx;
		padding-top: 20rpx;
		// background-color: #FFF;
		
		.title-view{
			font-weight: 600;
			margin-left: 20rpx;
			border-bottom: 1rpx solid #EFEFEF;
		}
		.form-box{
			width: 100%;
			height: auto;
			font-size: 26rpx;
			.form-input-box{
				padding: 0 20rpx;
				display: flex;
				align-items: center;
				border-bottom: 1rpx solid #eee;
			}
		}
		.view-item{
			width: 94%;
			margin: 0rpx auto;
			padding:10rpx;
			display: flex;
			border-bottom: 1rpx solid #EFEFEF;
			font-size: 26rpx;
			.label{
				width: 160rpx;
				color: #666;
				margin-bottom: 10rpx;
			}
			.img-box{
				width: 94%;
				height: auto;
				margin: 0rpx auto;
				padding:10rpx;
				display: flex;
				border-bottom: 1rpx solid #EFEFEF;
				.img-item {
					float: left;
					width: 200upx;
					height: 200upx;
					border: 1px solid #ddd;
					margin: 0 22rpx 20upx 0upx;
					position: relative;
					box-sizing: border-box;
					background: #eee;
					.img {
						display: block;
						width: 100%;
						height: 100%;
					}
					.remove-btn {
						position: absolute;
						top: -18upx;
						right: -18upx;
						width: 44upx;
						height: 44upx;
						z-index: 2;
					}
				}
				.upload-btn {
							display: flex;
							justify-content: center;
							align-items: center;
						.img {
							width: 60upx;
							height: 60upx;
							margin: unset;
						}
				}
			}
		}
	
	
		.sumbit-btn{
			width: 94%;
			height: 80rpx;
			margin: 0 auto;
			display: flex;align-items: center;justify-content: center;
			background: #00337A;
			color: #FFF;
			border-radius: 10rpx;
		}
	}
	
	.list-box{
		width: 90%;
		height: auto;
		// border: 1px solid #000;
		margin: 0rpx auto;
		
		.list-item{
			width: 100%;
			height: auto;
			background-color: #fff;
			border-radius: 20rpx;
			margin: 20rpx 0;
			
			.content-box{
				width: 94%;
				height: auto;
				margin: 20rpx;
				// background-color: #F8F9FC;
				padding: 10rpx 0;
				
				.item-text{
					width: 95%;
					margin-left: 20rpx;
					margin-top: 15rpx;
					// display: flex;
					align-items: center;
					position: relative;
					.label{
						color: #3A3A3A;
						font-weight: 500;
					}
					.info-right{
						position: absolute;
						top: 0rpx;
						right: 40rpx;
					}
					.info{
						color: #6F6F6F;
					
					}
				}
			}
		}
	}
 
	
}
</style>
