<template>
	<view>
		<view class="wrap" v-if="merchInfo.state==30">
			<u-form ref="uForm">
				<u-form-item label-position="left" label="商户名称" label-width="190">
					<u-input v-model="authInfo.storeName" disabled type="text"></u-input>
				</u-form-item>
				<u-form-item label-position="left" v-if="authInfo.mercType!=2" label="联系人类型" label-width="190">
					<u-radio-group shape="square" v-model="authInfo.merContactType" size='30' iconSize='26'>
						<u-radio v-for="(item, index) in merContactTypeList" :key="index" :name="item.name">
							{{item.label}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-position="left" v-if="authInfo.mercType==2" label="是否有门店" label-width="190">
					<u-radio-group shape="square" v-model="authInfo.managementType" size='30' iconSize='26'>
						<u-radio v-for="(item, index) in shopList" :key="index" :name="item.name">
							{{item.label}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label-position="left" label="联系人证件号" label-width="190">
					<u-input v-model="authInfo.contactCorpId" type="text"></u-input>
				</u-form-item>
				<u-form-item label-position="left" label="联系人手机号" label-width="190">
					<u-input v-model="authInfo.contactsTel" type="text"></u-input>
				</u-form-item>
				<u-form-item label="身份证开始日期" v-if="isCardShow" prop="idcard_back" labelWidth="290">
					<view class="" @click="id_start_date=true">
						<u--input v-model="authInfo.contIdValidDateBegin" disabled placeholder='请选择开始日期'
							:placeholder-style="placeholderStyle" />
					</view>
					<u-popup :show="id_start_date" @close="closeTimeID">
						<pdd-date-picker @closeTimeS='closeTimeID' ref="pDataSelect" @change="handleChangeDateID" />
					</u-popup>
				</u-form-item>
				<u-form-item v-if="isCardShow" label="身份证是否永久有效" label-width="290" prop="isWitch">
					<u-switch v-model="authInfo.isWitch" size='40'></u-switch>
				</u-form-item>
				<u-form-item label="身份证结束日期" v-if="isCardShow&&!authInfo.isWitch" prop="idcard_backend"
					labelWidth="290">
					<view class="" @click="id_end_date=true">
						<u--input v-model="authInfo.contIdValidDateEnd" disabled placeholder='请选择结束日期'
							:placeholder-style="placeholderStyle" />
					</view>
					<u-popup :show="id_end_date" @close="closeTimeIDEND">
						<pdd-date-picker @closeTimeS='closeTimeIDEND' ref="pDataSelect"
							@change="handleChangeDateIDEND" />
					</u-popup>
				</u-form-item>
				<u-form-item label-position="left" label="联系人证件证面照片" label-width="190" v-if="isCardShow">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" width="160"
						height="160" :maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label-position="left" label=" 联系人证件反面照片" label-width="190" v-if="isCardShow">
					<u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" width="160"
						height="160" :maxCount="1"></u-upload>
				</u-form-item>
			</u-form>
			<u-button type="success" v-if="iswxcome" :disabled="wxIsAuth" class="subBtn"
				@click="toAuth(0)">提交微信实名认证</u-button>
			<u-button type="primary" v-if="isalicome" :disabled="aliIsAuth" class="subBtn"
				@click="toAuth(1)">提交支付宝实名认证</u-button>
		</view>
		<view class="authRe" v-else-if="merchInfo.state==31">
			<u-subsection :list="subList" :current="curNm" :animation="true" @change="sectionChange"
				fontSize='26'></u-subsection>
			<view class="" v-if="!isState">
				<view>
					<view class="tips">{{tip}}</view>
					<view class="imgBox">
						<image :src="'data:image/png;base64,'+bara" class="codeImg" v-if="!curNm"></image>
						<image :src="bara" class="codeImg" v-if="curNm"></image>
					</view>
				</view>
				<u-button type="success" class="reBtn" @click="getAuthStatus">重新获取实名认证申请状态</u-button>
				<u-button type="primary" class="reBtn" @click="getStatus(1)">获取实名认证结果</u-button>
			</view>
			<view class="" v-else>
				<u-form v-if="!curNm" ref="uForm">
					<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="250">
						<u--input v-model="success" disabled type="text"
							:placeholder-style="placeholderStyle"></u--input>
					</u-form-item>
				</u-form>
				<u-form v-if="curNm" ref="uForm">
					<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="220">
						<u--input v-model="success" disabled type="text"
							:placeholder-style="placeholderStyle"></u--input>
					</u-form-item>
				</u-form>
				<u-button type="success" class="reBtn" @click="getStatus">重新获取实名认证结果</u-button>
				<u-button type="error" v-if="(isAuthwx&&!curNm)||(isAuthali&&curNm)" class="reBtn"
					@click="deleteAuth">撤销实名认证</u-button>
				<u-button type="primary" v-else class="reBtn" @click="toAuthAgin">重新发起实名认证</u-button>
			</view>

		</view>
		<view class="wrap" v-if="merchInfo.state==32">
			<u-subsection :list="subList" :current="curNm" :animation="true" @change="sectionChangeStatus"
				fontSize='26'></u-subsection>
			<u-form v-if="!curNm" ref="uForm">
				<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="250">
					<u--input v-model="success" disabled type="text" :placeholder-style="placeholderStyle"></u--input>
				</u-form-item>
			</u-form>
			<u-form v-if="curNm" ref="uForm">
				<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="220">
					<u--input v-model="success" disabled type="text" :placeholder-style="placeholderStyle"></u--input>
				</u-form-item>
			</u-form>
			<u-button type="primary" class="reBtn" @click="toAuthAgin">重新发起实名认证</u-button>
		</view>
		<view class="wrap" v-if="merchInfo.state==40">
			<u-subsection :list="subList" :current="curNm" :animation="true" @change="sectionChangeStatus"
				fontSize='26'></u-subsection>
			<u-form v-if="!curNm" ref="uForm">
				<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="250">
					<u--input v-model="success" disabled type="text" :placeholder-style="placeholderStyle"></u--input>
				</u-form-item>
			</u-form>
			<u-form v-if="curNm" ref="uForm">
				<u-form-item label-position="left" label="实名认证结果：" prop="idcard_backend" labelWidth="220">
					<u--input v-model="success" disabled type="text" :placeholder-style="placeholderStyle"></u--input>
				</u-form-item>
			</u-form>
			<u-button type="success" class="reBtn" @click="getStatus">重新获取实名认证结果</u-button>
			<u-button type="error" v-if="(isAuthwx&&!curNm)||(isAuthali&&curNm)" class="reBtn"
				@click="deleteAuth">撤销实名认证</u-button>
			<u-button type="primary" v-else class="reBtn" @click="toAuthAgin">重新发起实名认证</u-button>
		</view>
	</view>
</template>

<script>
	import {
		wx_real_name,
		ali_real_name,
		uploadImg,
		wx_real_name_status,
		ali_real_name_detail,
		wx_real_name_cancel,
		ali_real_name_cancel,
		wx_auth_status,
		ali_auth_status
	} from '@/utils/api.js'
	import {
		toBase64
	} from '@/utils/imgtobase.js'
	import ysDict from '@/pages/index/dictDatas.js'
	import pddDatePicker from '@/uni_modules/pdd-date-picker/components/pdd-date-picker/pdd-date-picker.vue'
	export default {
		components: {
			pddDatePicker
		},
		data() {
			return {
				isState: false, //如果用户状态是31，还未点击查询实名结果
				success: '实名认证成功',
				error: '实名认证失败',
				isAuthwx: false, //wx是否授权
				isAuthali: false, //ali是否授权
				id_start_date: false,
				id_end_date: false,
				placeholderStyle: 'font-size:22rpx;color:#c0c4cc;',
				params: null,
				merchInfo: {
					mercType: '',
				},
				authInfo: {
					merContactType: '65'
				},
				bara: "",
				tip: "",
				ysDict: null,
				subList: [{
						name: '微信'
					},
					{
						name: '支付宝'
					},
				],
				curNm: 0,
				reBtnIsShow: false,
				merContactTypeList: [{
					name: '65',
					label: '经营者/法人'
				}],
				isCardShow: false,
				post_url: '',
				idcard_front: {
					'type': 'idcard',
					'id_card_side': 'front'
				}, //身份证正面
				idcard_back: {
					'type': 'idcard',
					'id_card_side': 'back'
				}, //身份证反面
				isAgin: false,
				wxIsAuth: false,
				aliIsAuth: false,
				shopList: [{
						name: '00',
						label: '是'
					},
					{
						name: '01',
						label: '否'
					},
				],
				fileList1: [], //身份证正面
				fileList2: [], //身份证反面
				account_id: '', //编号
				iswxcome: true,
				isalicome: true,
			}
		},

		onLoad(options) {
			var option = JSON.parse(options.val)
			// option.state =40
			this.ysDict = ysDict
			this.post_url = getApp().globalData.baidu_sdk_url
			this.merchInfo = {
				...this.merchInfo,
				...option
			}
			this.params = option
			if (parseInt(option.state) != '30' && parseInt(option.state) != '40' && parseInt(option.state) != '32') {
				this.getAuthStatus()
			} else {
				this.initAuthInfo(option)
			}
			if (parseInt(option.state) == '40' || parseInt(option.state) == '32') {
				this.getStatus()
			}
		},

		watch: {
			//是否是法人
			'authInfo.merContactType': {
				handler: function(n, o) {
					this.isCardShow = !this.isCardShow
				},
			},
			'merchInfo.mercType': {
				handler: function(n, o) {
					if (n === '2') { //小微
						this.merContactTypeList = [{
							name: '65',
							label: '经营者/法人'
						}]
					} else {
						this.merContactTypeList = [{
							name: '65',
							label: '经营者/法人'
						}, {
							name: '66',
							label: '经办人'
						}]
					}
				},
				immediate: true
			},

		},
		methods: {
			//认证状态的值
			initAuthInfo(params) {
				console.log(params)
				this.account_id = params.account_id
				this.authInfo = {
					ysMercId: JSON.parse(params.extend).merc_id, //“商户号"
					mercId: JSON.parse(params.extend).merc_id, //“商户号"
					contactCorpId: '', //联系人证件号码”
					contactsTel: "", //联系人手机号
					merContactType: '65', //65法人，66非法人"
					mercType: params.shop_type, //2 小微、3个体。4企业
					managementType: '00', //00-门店场所、01-流动经营/便民服务(小微商户必填)"
					storeName: params.shop_name, //门店名称(小微商户必填)
					idTypeCd: '00', //
					idFrontImg: '', //联系人证件正面照片(66必填)
					idBackImg: '', //联系人证件反面照片(66必填)"
					contIdValidDateBegin: '', //联系人证件有效期开始时间yyyy-MM-dd(66必填)
					contIdValidDateEnd: '', //联系人证件有效期结束时间yyyy-MM-dd(66必填)著为永久，传2999-12-31"
					isWitch: true, //身份证是否一直有效
				}
			},
			closeTimeID() {
				this.id_start_date = false
			},
			handleChangeDateID(date) {
				this.authInfo.contIdValidDateBegin = date
				this.closeTimeID()
			},
			closeTimeIDEND() {
				this.id_end_date = false
			},
			handleChangeDateIDEND(date) {
				this.authInfo.contIdValidDateEnd = date
				this.closeTimeIDEND()
			},
			//实名认证提交
			toAuth(type) {
				if (this.authInfo.mercType == 2 && this.authInfo.merContactType == '66') {
					this.authInfo.idFrontImg = this.fileList1[0].url
					this.authInfo.idBackImg = this.fileList2[0].url
					if (this.authInfo.isWitch) {
						this.authInfo.contIdValidDateEnd = '2999-12-31'
					}

				}
				var authApi = type == 0 ? wx_real_name : ali_real_name
				uni.showLoading({
					title: '正在提交实名认证',
					mask: true
				})
				var _this = this
				console.log(this.authInfo);
				const data = {
					account_id: this.account_id,
					info: JSON.stringify(this.authInfo)
				}
				authApi(data).then(res => {
					if (res.code !== 200) {
						uni.hideLoading()
						_this.$u.toast(res.msg)
						return
					} else {
						_this.$u.toast((type == 0 ? "微信" : "支付宝") + "实名认证已提交，等待审核")
						if (type == 0) {
							this.wxIsAuth = true
						} else {
							this.aliIsAuth = true
						}
						this.$refs.uForm.resetFields()
						setTimeout(function() {
							if (!this.wxIsAuth || !this.aliIsAuth) {
								uni.navigateBack()
							}
						})

					}
				})
			},

			//重新去实名认证
			toAuthAgin() {
				this.merchInfo.state = 30
				if (!this.curNm) {
					this.iswxcome = true;
					this.isalicome = false;
				} else {
					this.iswxcome = false;
					this.isalicome = true;
				}

				this.initAuthInfo(this.params)
			},

			//切换平台
			sectionChange(index) {
				this.bara = ""
				this.curNm = index;
				if (index)
					this.authInfo.contactCorpId = '';
				this.authInfo.contactsTel = ''
				if(!this.isState){
					this.getAuthStatus();
				}else{
					this.getStatus()
				}
				
			},
			//实名认证成功切换平台
			sectionChangeStatus(index) {
				this.bara = ""
				this.curNm = index;
				if (index)
					this.authInfo.contactCorpId = '';
				this.authInfo.contactsTel = ''
				this.getStatus();
			},
			//撤销实名认证
			deleteAuth() {
				var getApi = this.curNm === 0 ? wx_real_name_cancel : ali_real_name_cancel
				var params = {
					apply_no: this.curNm === 0 ? JSON.parse(this.merchInfo.extend).wx_apply_no : JSON.parse(this
						.merchInfo.extend).ali_apply_no,
					//type===0?this.merchInfo.wxAuthNo:this.merchInfo.aliAuthNo
				}
				if (this.curNm === 1) {
					params["merc_id"] = JSON.parse(this.merchInfo.extend).merc_id
				}
				getApi(params).then(r => {
					if (r.code !== 200) {
						this.$u.toast(r.msg)
						return
					} else {
						this.$u.toast('撤销成功')
						uni.navigateBack()
					}
				})
			},
			//获取商家授权状态(查询商户是否已完成实名认证)
			getStatus(n) {
				var getApi = this.curNm === 0 ? wx_auth_status : ali_auth_status
				var params = {
					merc_id: JSON.parse(this.merchInfo.extend).merc_id,
					account_id: this.merchInfo.account_id
				}
				getApi(params).then(r => {
					if (n) {
						this.isState = true
					}
					if (r.code !== 200) {
						this.$u.toast(r.msg)
						return
					} else {
						if (!this.curNm) {
							//已授权
							if (r.data.authStateX == 'AUTHORIZE_STATE_AUTHORIZED') {
								this.success = '实名认证成功'
								this.isAuthwx = true
							} else {
								this.success = '实名认证失败'
								this.isAuthwx = false
								this.getAuthStatus()
							}
						} else {
							//已授权
							if (r.data.authState == '1') {
								this.success = '实名认证成功'
								this.isAuthali = true
							} else {
								this.success = '实名认证失败'
								this.isAuthali = false
								this.getAuthStatus()
							}
						}
						this.$u.toast(r.msg)
					}
				})
			},
			//获取实名认证申请状态
			getAuthStatus() {
				var _this = this
				// uni.showLoading({
				// 	title: '正在查询相关数据',
				// 	mask: true
				// })
				var getApi = this.curNm === 0 ? wx_real_name_status : ali_real_name_detail
				var params = {
					apply_no: this.curNm === 0 ? JSON.parse(this.merchInfo.extend).wx_apply_no : JSON.parse(this
						.merchInfo.extend).ali_apply_no,
					//type===0?this.merchInfo.wxAuthNo:this.merchInfo.aliAuthNo
				}
				console.log(params)
				if (typeof params.apply_no === 'undefined' || params.apply_no === null) {
					uni.hideLoading()
					this.tip = "请先完成实名认证"
					this.authText = "发起实名认证"
					return
				} else {
					this.authText = "重新发起实名认证"
				}
				//支付宝
				if (this.curNm === 1) {
					params["merc_id"] = JSON.parse(this.merchInfo.extend).merc_id
				}
				getApi(params).then(r => {
					console.log(r)
					uni.hideLoading()
					if (r.code !== 200) {
						_this.tip = r.msg
						return
					}
					_this.bara = r.data.qrcodeData
					let key = r.data.applyState
					if (['APPLYMENT_STATE_REJECTED',
							'APPLYMENT_STATE_FREEZED',
							'APPLYMENT_STATE_CANCELED',
							'APPLYMENT_STATE_WAITTING_FOR_CONFIRM_CONTACT',
							'AUDITING',
							'CONTACT_CONFIRM',
							'AUDIT_REJECT',
							'AUDIT_FREEZE'
						].includes(key)) {
						_this.reBtnIsShow = true
					}
					let authMsg = this.ysDict.authResMsg()
					if (['APPLYMENT_STATE_REJECTED', 'AUDIT_REJECT'].includes(key)) {
						_this.tip = "审核被驳回：" + (this.curNm === 0 ? r.data.rejectReason : r.data.channelNote)
					} else {
						_this.tip = authMsg[key]
					}
					console.log(_this.tip);
				})
			},
			afterRead(e) {
				console.log(e);
				const file = e.file;
				const maxSize = 2 * 1024 * 1024; // 2MB
				if (file.size > maxSize) {
					uni.showToast({
						title: '文件大小不能超过 2MB。',
						duration: 2000,
						icon: 'none'
					});
					return; // 终止后续操作
				}
				// 将上传图片处理成base64
				toBase64(e.file.url).then(result => {
						let myVariable = result
						let license = {
							file: 'data:image/png;base64,' + myVariable
						}
						this.uploadFilePromise(license, e)
					})
					.catch(error => {
						console.error('There was an error!', error);
					});
			},
			uploadFilePromise(img, e) {
				uploadImg(img).then((res) => {
					this[`fileList${e.name}`].push({
						url: res.data.url
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},

		}
	}
</script>

<style lang="scss">
	.codeImg {
		height: 300rpx;
		width: 300rpx;

	}

	.wrap {
		padding: 30rpx;

		.u-size-default {
			padding: 0rpx
		}

		.signature .inputs .explain {
			width: 200rpx;
		}
	}

	.authRe {
		padding: 30rpx;

		.u-size-default {
			padding: 0rpx
		}
	}

	.subBtn {
		margin-top: 30rpx;
	}

	.reBtn {
		margin-top: 30rpx;
		width: 90%;
	}

	.tips {
		font-size: 25rpx;
		margin: 20rpx 0 0 13%;
	}

	.imgBox {
		display: flex;
		justify-content: center;
	}
</style>