<template>
	<view class="min-page bg-f7 u-font-28">
		<template v-if="loadingFinish">
			<up-form :model="form" :rules="rules" ref="refForm" label-width="auto" label-position="top"
				errorType="toast" :label-style="labelStyle">
				<view class="container">
					<up-form-item label="当前模式">
						<up-radio-group v-model="form.channel">
							<up-radio v-for="(value,key) in channels" :key="key" :name="key" :label="value"></up-radio>
						</up-radio-group>
					</up-form-item>
					<template v-if="form.channel=='native'">
						<up-form-item label="使用信息"
							v-if="shopInfo.shopType!='only'&& !shopInfo.isHeadShop && mainEntryManagerRes">
							<up-radio-group v-model="useInfo">
								<up-radio v-for="(value,key) in useInfos" :key="key" :name="key*1"
									:label="value"></up-radio>
							</up-radio-group>
						</up-form-item>
					</template>

				</view>
				<template v-if="form.channel=='poly'">
					<view class="container">
						<up-form-item label="店铺id" prop="polyMerchantDTO.storeId"
							:required="returnIsRequired('polyMerchantDTO.storeId')">
							<up-input v-model="form.polyMerchantDTO.storeId"></up-input>
						</up-form-item>
						<up-form-item label="商户名称" prop="polyMerchantDTO.merchantName"
							:required="returnIsRequired('polyMerchantDTO.merchantName')">
							<up-input v-model="form.polyMerchantDTO.merchantName"></up-input>
						</up-form-item>
						<up-form-item label="商户应用id" prop="polyMerchantDTO.appId"
							:required="returnIsRequired('polyMerchantDTO.appId')">
							<up-input v-model="form.polyMerchantDTO.appId"></up-input>
						</up-form-item>
						<up-form-item label="商户密钥" prop="polyMerchantDTO.appSecret"
							:required="returnIsRequired('polyMerchantDTO.appSecret')">
							<up-input v-model="form.polyMerchantDTO.appSecret"></up-input>
						</up-form-item>
						<!-- <up-form-item label="支付密码" prop="polyMerchantDTO.payPassword"
						:required="returnIsRequired('polyMerchantDTO.payPassword')">
						<up-input v-model="form.polyMerchantDTO.payPassword"></up-input>
					</up-form-item> -->
					</view>
				</template>
				<template v-else>
					<template v-if="useInfo==0">
						<template v-if="entryManagerRes">
							<view class="container container1">
								<view class="u-flex u-row-between">
									<text class="font-bold">商户号</text>
									<text class="">{{entryManagerRes.merchantCode}}</text>
								</view>
								<view class="u-flex u-row-between u-m-t-24">
									<text class="font-bold">商户类型</text>
									<text class="">{{returnType(entryManagerRes.userType)}}</text>
								</view>
								<view class="status">
									<view class="u-flex u-row-between ">
										<text class="font-bold">支付宝进件状态</text>
										<view class="state" :class="returnStatusClass(entryManagerRes.alipayStatus)">
											{{returnStatusLabel(entryManagerRes.alipayStatus)}}
										</view>
									</view>
									<view v-if="entryManagerRes.alipayStatus==='SIGN'" class="u-m-t-16">
										<my-button @click="showCode(entryManagerRes,'aliPay')">查看签约码</my-button>
									</view>
									<view class="u-m-t-14" v-if="entryManagerRes.alipayErrorMsg">
										<up-alert title="拒绝原因" type="error"
											:description="entryManagerRes.alipayErrorMsg"></up-alert>
									</view>
								</view>

								<view class="status">
									<view class="">
										<view class="u-flex u-row-between">
											<text class="font-bold">微信进件状态</text>
											<view class="state"
												:class="returnStatusClass(entryManagerRes.wechatStatus)">
												{{returnStatusLabel(entryManagerRes.wechatStatus)}}
											</view>
										</view>
										<view v-if="entryManagerRes.wechatStatus==='SIGN'" class="u-m-t-16">
											<my-button @click="showCode(entryManagerRes,'wx')">查看签约码</my-button>
										</view>

									</view>
									<view class="u-m-t-14" v-if="entryManagerRes.wechatErrorMsg">
										<up-alert title="拒绝原因" type="error"
											:description="entryManagerRes.wechatErrorMsg"></up-alert>
									</view>
								</view>
								<view class="u-flex u-row-between u-m-t-24">
									<text class="font-bold">最后提交时间</text>
									<text class="">{{entryManagerRes.updateTime}}</text>
								</view>
								<view class="u-flex u-row-between u-m-t-24">
									<text class="font-bold">创建时间</text>
									<text class="">{{entryManagerRes.createTime}}</text>
								</view>

								<view class="u-flex u-row-right gap-20 u-m-t-32">
									<my-button @click="toEdit(entryManagerRes)">查看详情</my-button>
									<my-button @click="toEdit(entryManagerRes)">修改</my-button>
								</view>

							</view>
						</template>
						<view class="container container1" v-if="!entryManagerRes">
							<view class="color-red font-bold  text-center">您还未申请进件</view>
							<view class="u-m-t-32">
								<my-button @click="toEdit()">去申请</my-button>
							</view>
						</view>
					</template>
					<template v-if="useInfo==1">
						<view class="container container1">
							<view class="u-flex u-row-between u-m-b-24">
								<text class="font-bold">复用信息</text>
								<up-tag type="primary" plain text="复用主店信息"></up-tag>
							</view>
							<view class="u-flex u-row-between">
								<text class="font-bold">商户号</text>
								<text class="">{{mainEntryManagerRes.merchantCode}}</text>
							</view>
							<view class="u-flex u-row-between u-m-t-24">
								<text class="font-bold">商户类型</text>
								<text class="">{{returnType(mainEntryManagerRes.userType)}}</text>
							</view>
							<view class="status">
								<view class="u-flex u-row-between ">
									<text class="font-bold">支付宝进件状态</text>
									<view class="state" :class="returnStatusClass(mainEntryManagerRes.alipayStatus)">
										{{returnStatusLabel(mainEntryManagerRes.alipayStatus)}}
									</view>
								</view>
								<view v-if="mainEntryManagerRes.alipayStatus==='SIGN'" class="u-m-t-16">
									<my-button @click="showCode(mainEntryManagerRes,'aliPay')">查看签约码</my-button>
								</view>
								<view class="u-m-t-14" v-if="mainEntryManagerRes.alipayErrorMsg">
									<up-alert title="拒绝原因" type="error"
										:description="mainEntryManagerRes.alipayErrorMsg"></up-alert>
								</view>
							</view>

							<view class="status">
								<view class="">
									<view class="u-flex u-row-between">
										<text class="font-bold">微信进件状态</text>
										<view class="state"
											:class="returnStatusClass(mainEntryManagerRes.wechatStatus)">
											{{returnStatusLabel(mainEntryManagerRes.wechatStatus)}}
										</view>
									</view>
									<view v-if="mainEntryManagerRes.wechatStatus==='SIGN'" class="u-m-t-16">
										<my-button @click="showCode(mainEntryManagerRes,'wx')">查看签约码</my-button>
									</view>

								</view>
								<view class="u-m-t-14" v-if="mainEntryManagerRes.wechatErrorMsg">
									<up-alert title="拒绝原因" type="error"
										:description="mainEntryManagerRes.wechatErrorMsg"></up-alert>
								</view>
							</view>
							<view class="u-flex u-row-between u-m-t-24">
								<text class="font-bold">最后提交时间</text>
								<text class="">{{mainEntryManagerRes.updateTime}}</text>
							</view>
							<view class="u-flex u-row-between u-m-t-24">
								<text class="font-bold">创建时间</text>
								<text class="">{{mainEntryManagerRes.createTime}}</text>
							</view>
						</view>
					</template>
				</template>

				<!-- <up-form-item label="微信appid" prop="polyMerchantDTO.wechatSmallAppid"
					:required="returnIsRequired('polyMerchantDTO.wechatSmallAppid')">
					<up-input v-model="form.polyMerchantDTO.wechatSmallAppid"></up-input>
				</up-form-item>
				<up-form-item label="微信支付宝appid" prop="polyMerchantDTO.alipaySmallAppid"
					:required="returnIsRequired('polyMerchantDTO.alipaySmallAppid')">
					<up-input v-model="form.polyMerchantDTO.alipaySmallAppid"></up-input>
				</up-form-item> -->

			</up-form>
			<up-popup :show="codeShow" mode="center" @close="codeShow=false" round="16rpx"
				:close-on-click-overlay="true">
				<view style="border-radius: 16rpx;overflow: hidden;" class="u-p-b-30">
					<up-image width="200" height="200" :src="code"></up-image>
					<view class="u-m-t-0 text-center" v-if="codeType=='wx'">请打开微信扫码</view>
					<view class="u-m-t-0 text-center" v-if="codeType=='aliPay'">请打开支付宝扫码</view>
				</view>
			</up-popup>
			<my-bottom-btn-group @cancel="uni.navigateBack()" @save="submit"></my-bottom-btn-group>
		</template>
		<my-page-loading v-else></my-page-loading>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		watch
	} from 'vue'
	import {
		companyChildTypes,
		userTypes,
		statusList
	} from '@/commons/data/entryManager.js'
	import * as shopMerchantApi from '@/http/api/order/shopMerchant.js'
	import {
		getEntryManager
	} from '@/http/api/order/entryManager.js'
	import {
		channels
	} from '../data.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'

	import * as shopInfoApi from '@/http/api/account/shopInfo.js'

	const useInfo = ref(0)

	const useInfos = {
		0: '当前店铺',
		1: '主店'
	}

	function toEdit(shop) {
		console.log(shop)
		if (shop) {
			uni.navigateTo({
				url: '/entryManager/add/add?shopId=' + shop.shopId + '&licenceNo=' + shop.businessLicenceInfo
					.licenceNo
			})
		} else {
			return uni.navigateTo({
				url: '/entryManager/add/add?shopId=' + query.shopId
			})
			// if (mainEntryManagerRes.value) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '是否复用主店信息',
			// 		showCancel: true,
			// 		cancelText: '复用主店信息',
			// 		confirmText: '继续进件',
			// 		success(res) {
			// 			if (res.confirm) {
			// 				uni.navigateTo({
			// 					url: '/entryManager/add/add?shopId=' + query.shopId
			// 				})
			// 			} else {
			// 				mainEntryManagerRes = mainEntryManagerRes.value
			// 			}
			// 		}
			// 	})
			// 	return
			// } else {
			// 	uni.navigateTo({
			// 		url: '/entryManager/add/add?shopId=' + query.shopId
			// 	})
			// }

		}

	}
	const code = ref('')
	const codeShow = ref(false)
	const codeType = ref('')

	function returnStatusLabel(state) {
		const item = statusList.find(v => v.value == state)
		if (item) {
			return item.name
		}
		return ''
	}

	function returnIsRequired(key) {
		if (rules[key] && rules[key].required) {
			return true
		}
		return false
	}


	function returnType(type) {
		if (userTypes[type]) {
			return userTypes[type]
		}
		return ''
	}

	function showCode(item, type) {
		if (type == 'wx') {
			code.value = item.wechatSignUrl
		}
		if (type == 'aliPay') {
			code.value = item.alipaySignUrl
		}
		codeType.value = type
		codeShow.value = true

	}

	function returnStatusClass(state) {
		const item = statusList.find(v => v.value == state)
		if (item) {
			return item.class
		}
		return ''
	}

	const labelStyle = {
		fontWeight: "700"
	}
	const query = reactive({
		shopId: ''
	})
	const rules = reactive({
		"polyMerchantDTO.merchantName": {
			type: 'string',
			required: true,
			message: '请输入商户名称',
			trigger: ['blur', 'change'],
		},
		"polyMerchantDTO.storeId": {
			type: 'string',
			required: true,
			message: '请输入店铺id',
			trigger: ['blur', 'change'],
		},
		"polyMerchantDTO.appId": {
			type: 'string',
			required: true,
			message: '请输入商户应用id',
			trigger: ['blur', 'change'],
		},
		"polyMerchantDTO.appSecret": {
			type: 'string',
			required: true,
			message: '请输入商户密钥',
			trigger: ['blur', 'change'],
		},
		// "polyMerchantDTO.payPassword": {
		// 	type: 'string',
		// 	required: true,
		// 	message: '请输入支付密钥',
		// 	trigger: ['blur', 'change'],
		// },
		// "polyMerchantDTO.wechatSmallAppid": {
		// 	type: 'string',
		// 	required: true,
		// 	message: '请输入微信小程序appid',
		// 	trigger: ['blur', 'change'],
		// },
		// "polyMerchantDTO.alipaySmallAppid": {
		// 	type: 'string',
		// 	required: true,
		// 	message: '请输入支付宝小程序appid',
		// 	trigger: ['blur', 'change'],
		// }

	})
	const form = reactive({
		shopId: 0,
		channel: "native",
		relatedId: "",
		nativeMerchantDTO: {
			wechatMerchantId: "",
			alipayMerchantId: "",
			alipayAuthInfo: {
				user_id: "",
				open_id: "",
				auth_app_id: "",
				app_auth_token: "",
				expires_in: "",
				app_refresh_token: "",
				re_expires_in: "",
				order_no: "",
			},
		},
		polyMerchantDTO: {
			storeId: "",
			merchantName: "",
			appId: "",
			appSecret: "",
			payPassword: "",
			wechatSmallAppid: "",
			alipaySmallAppid: "",
		},
		shopDirectMerchant: {
			shopId: 0,
			shopName: "",
			licenceNo: "",
			alipayAccount: "",
			merchantCode: "",
			userType: "",
			shortName: "",
			merchantBaseInfo: "",
			legalPersonInfo: "",
			businessLicenceInfo: "",
			storeInfo: "",
			settlementInfo: "",
			createTime: "",
			updateTime: "",
			errorMsg: "",
			wechatApplyId: "",
			wechatStatus: "",
			wechatErrorMsg: "",
			wechatSignUrl: "",
			alipayOrderId: "",
			alipayStatus: "",
			alipayErrorMsg: "",
			alipaySignUrl: "",
			alipayAuthInfo: "",
			wechatMerchantId: "",
			alipayMerchantId: "",
		},
	});
	const refForm = ref(null)

	const entryManagerRes = ref(null)


	const mainEntryManagerRes = ref(null)

	const shopInfo = ref(null)

	const shopMerchant = ref(null)
	async function init() {
		const shopInfoRes = await shopInfoApi.getShopDetail({
			id: query.shopId
		})
		shopInfo.value = shopInfoRes
		//不是单店且不是主店
		if (shopInfoRes && shopInfo.shopType != 'only' && !shopInfoRes.isHeadShop) {
			const res = await shopMerchantApi.getMainMerchant({
				shopId: query.shopId
			})
			mainEntryManagerRes.value = res

		}
		const res = await getEntryManager({
			shopId: query.shopId
		})
		entryManagerRes.value = res
		shopMerchantApi.shopMerchant({
			shopId: query.shopId
		}).then(res => {
			if (res) {
				if (res.shopDirectMerchant) {
					useInfo.value = 1
				} else {
					useInfo.value = 0
				}
				shopMerchant.value = res
				if (res.relatedId == shopInfo.value.id) {
					useInfo.value = 0
				}
				if (mainEntryManagerRes.value && res.relatedId == mainEntryManagerRes.value.shopId) {
					useInfo.value = 1
				}
				Object.assign(form, res)

			}
			loadingFinish.value = true
		})
	}

	const loadingFinish = ref(false)
	onLoad((opt) => {
		query.shopId = opt.shopId
		form.shopId = opt.shopId
		init()
	})

	async function save() {
		let res = null
		if (form.channel == 'poly') {
			res = await shopMerchantApi.editShopMerchant({
				shopId: form.shopId,
				channel: form.channel,
				relatedId:shopInfo.value.id,
				polyMerchantDTO: {
					storeId: form.polyMerchantDTO.storeId,
					merchantName: form.polyMerchantDTO.merchantName,
					appId: form.polyMerchantDTO.appId,
					appSecret: form.polyMerchantDTO.appSecret,
				}
			})
		} else {
			if (useInfo.value == 1) {
				//使用主店
			}
			res = await shopMerchantApi.editShopMerchant({
				shopId: form.shopId,
				channel: form.channel,
				relatedId: useInfo.value == 1 ? mainEntryManagerRes.value.shopId : query.shopId,
				// nativeMerchantDTO: {
				// 	wechatMerchantId: form.nativeMerchantDTO.wechatMerchantId,
				// 	alipayMerchantId: form.nativeMerchantDTO.alipayMerchantId,
				// 	alipayAuthInfo: {
				// 		user_id: form.nativeMerchantDTO.alipayAuthInfo.user_id,
				// 		open_id: form.nativeMerchantDTO.alipayAuthInfo.open_id,
				// 		auth_app_id: form.nativeMerchantDTO.alipayAuthInfo.auth_app_id,
				// 		app_auth_token: form.nativeMerchantDTO.alipayAuthInfo.app_auth_token,
				// 		expires_in: form.nativeMerchantDTO.alipayAuthInfo.expires_in,
				// 		app_refresh_token: form.nativeMerchantDTO.alipayAuthInfo.app_refresh_token,
				// 		re_expires_in: form.nativeMerchantDTO.alipayAuthInfo.re_expires_in,
				// 		order_no: form.nativeMerchantDTO.alipayAuthInfo.order_no,
				// 	}
				// }
			})
		}

		if (res) {
			uni.$u.toast('保存成功')
			setTimeout(() => {
				uni.navigateBack()
			}, 1000)
		}

	}

	function submit() {
		if (useInfo.value == 0 && form.channel == 'native' && !entryManagerRes.value) {
			return uni.$u.toast('您还未申请进件，清先申请进件')
		}
		refForm.value.validate().then(valid => {
			console.log('valid', valid);
			if (valid) {
				// uni.$u.toast('校验通过')

				save()
			} else {}
		}).catch(() => {
			// 处理验证错误  
		});
	}

	watch(() => form.channel, (newval) => {
		for (let key in rules) {
			console.log('key', key)
			rules[key].required = newval == 'poly' ? true : false;
		}
		if (newval == 'poly') {
			form.polyMerchantDTO =shopMerchant.value.polyMerchantDTO|| {
				storeId: "",
				merchantName: "",
				appId: "",
				appSecret: "",
				payPassword: "",
				wechatSmallAppid: "",
				alipaySmallAppid: "",
			}
		}

	})
	watch(() => useInfo.value, (newval) => {
		console.log('newval', newval);
		if (newval) {

		} else {

		}
	})
</script>

<style lang="scss" scoped>
	.min-page {
		padding: 32rpx 28rpx;
	}

	.container {
		background-color: #fff;
		padding: 12rpx 28rpx;
		border-radius: 16rpx;
		margin-bottom: 32rpx;

		&.container1 {
			padding: 32rpx 28rpx;
		}
	}

	:deep(.input-placeholder) {
		font-size: 28rpx;
	}

	:deep(.u-form-item__body) {
		padding: 10px 0 0 0;
	}

	.status {
		margin-top: 24rpx;
		background-color: #f7f7f7;
		padding: 24rpx 28rpx;
		border-radius: 4rpx;

		.state {
			padding: 8rpx 18rpx;
			border-radius: 8rpx;
			border: 2rpx solid #333;

			&.success {
				border-color: rgba(123, 209, 54, 1);
				color: rgba(123, 209, 54, 1);
				background: rgba(123, 209, 54, 0.12);
			}

			&.warning {
				border-color: rgba(255, 141, 40, 1);
				color: rgba(255, 141, 40, 1);
				background: rgba(255, 141, 40, 0.12);
			}

			&.error {
				border-color: #FF1C1C;
				color: #FF1C1C;
				background: rgba(255, 28, 28, 0.18);
			}

			&.gray {
				color: #bbb;
				background-color: #f7f7f7;
				border-color: #bbb;
			}
		}
	}

	:deep(.u-alert__content__desc) {
		word-break: break-all;
	}
</style>