<template>
	<view class="page-container page-divider-color">
		<view class="content-box">
			<view class="content-container">
				<view class="info-title">受让人信息</view>
				<!-- 第一部分 -->
				<view class="section">
					<view class="item">
						<text class="label star">类别</text>
						<view class="select-content-item">
							<picker mode="selector" style="flex:1;" :range="personType" range-key="dataName"
								@change="bindChangePersonType">
								<view class="select-time" :class="{'value-hint': !selPersonType}">
									{{selPersonType ? selPersonType.dataName : '请选择类别'}}
								</view>
							</picker>
							<view style="display: flex;flex-direction: row;">
								<view v-if="selPersonType" @tap="clearPersonType" class="icon-clear-line size-32">
								</view>
								<view v-else class="icon-arrow-solid"></view>
							</view>
						</view>
					</view>
					<view class="item">
						<text class="label star">姓名或机构名称</text>
						<view class="select-content-item">
							<input class="value" :class="{'v-select': orgName}" placeholder="请输入姓名或机构名称"
								style="flex:1;align-self: center;" v-model="orgName" @input="inputOrgName" />
						</view>
					</view>
					<view class="item">
						<text class="label star">省市</text>
						<view class="select-content-item">
							<view @tap="onShowArea" class="select-time" :class="{'value-hint': !selArea}">
								{{selArea && selCity ? selArea.areaName + '/' + selCity.areaName : '请选择所在省市'}}
							</view>
							<view style="display: flex;flex-direction: row;">
								<view v-if="selArea" @tap="clearArea" class="icon-clear-line size-32"></view>
								<view v-else class="icon-arrow-solid"></view>
							</view>
						</view>
					</view>
					<view class="item">
						<text class="label star">联系电话</text>
						<view class="select-content-item">
							<input class="value" :class="{'v-select': orgPhone}" placeholder="请输入联系电话"
								style="flex:1;align-self: center;" v-model="orgPhone" @input="inputOrgPhone" />
							<view v-if="orgPhone.length>0" @tap="doClearPhone" class="icon-clear-line size-32"></view>
						</view>
					</view>
					<view class="item">
						<text class="label star">证件类型</text>
						<view class="select-content-item">
							<picker mode="selector" style="flex:1;" :range="creType" range-key="dataName"
								@change="bindChangeCreType">
								<view class="select-time" :class="{'value-hint': !selCreType}">
									{{selCreType ? selCreType.dataName : '请选择证件类型'}}
								</view>
							</picker>
							<view style="display: flex;flex-direction: row;">
								<view v-if="selCreType" @tap="clearCreType" class="icon-clear-line size-32"></view>
								<view v-else class="icon-arrow-solid"></view>
							</view>
						</view>
					</view>
					<view class="item">
						<text class="label star">证件号码</text>
						<view class="select-content-item" style="border-bottom: none;">
							<input class="value" :class="{'v-select': cardNumber}" placeholder="请输入证件号码"
								style="flex:1;align-self: center;" v-model="cardNumber" @input="inputCardNumber" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom-fixed-footer">
			<view class="bottom-btn-blue" @tap="doSave">上报</view>
		</view>
		<uni-popup ref="areaDialog" type="bottom" background-color="#fff" border-radius="15rpx 15rpx 0rpx 0rpx">
			<view class="bottom-dialog-container">
				<view class="dialog-title-box">
					<view class="icon-close size-48" @click="closeDialog"></view>
					<view class="dialog-title-txt has-icon">选择省市</view>
				</view>
				<view style="height: 600rpx;" class="mt-10">
					<picker-view class="area-picker-box" @change="areaChange">
						<picker-view-column>
							<view class="area-picker-item" v-for="(item,index) in areaList" :key="index">
								{{item.areaName}}
							</view>
						</picker-view-column>
						<picker-view-column>
							<view class="area-picker-item" v-for="(item,index) in cityList" :key="index">
								{{item.areaName}}
							</view>
						</picker-view-column>
					</picker-view>
					<view class="bottom-btn-green" @click="closeDialog">确定</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup type="message" ref="msg">
			<uni-popup-message :type="msgType" :duration="2000" :message="msgHint"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	import Shop from '@/common/js/net/shop.js'
	import {
		isValidPhone
	} from '@/common/js/validator.js'
	export default {
		setup() {},
		data() {
			return {
				personType: [{
					dataName: '自然人',
					dataId: '1'
				}, {
					dataName: '法人',
					dataId: '2'
				}, {
					dataName: '非法人组织或其他',
					dataId: '3'
				}],
				selPersonType: null,
				creType: [],
				areaList: [], //省
				cityList: [], //市
				orgName: '', //著作权人姓名
				orgPhone: '', //联系电话
				cardNumber: '', //证件号码
				selRightType: [], //选中分类
				rightPrice: '', //售价
				rightStopDate: '', //停止日期
				selCreType: null, //选中证件类型
				showArea: false,
				prevValue: [0, 0], // 用于存储上一次的值
				selArea: null,
				selCity: null,
				msgHint: '',
				msgType: 'info',
				msgShow: false,
				showType: false,
				orderId: '',
			};
		},
		onLoad(options) {
			uni.setNavigationBarTitle({
				title: "受让人信息",
			});
			uni.setNavigationBarColor({
				frontColor: "#000000",
				backgroundColor: "#FFFFFF",
				animation: {
					duration: 500,
					timingFunc: "easeIn",
				},
			});
			var orderId = options.orderId
			if (orderId && orderId != '') {
				this.orderId = orderId
				this.selPersonType = this.personType[0]
				this.getDic()
			} else {
				this.msgHint = '数据有误,请稍后重试'
				this.msgType = 'error'
				this.$refs.msg.open()
				setTimeout(() => {
					uni.navigateBack()
				}, 1200);
			}
		},
		methods: {
			inputRightName(e) {
				this.rightName = e.detail.value;
			},

			doClearRightName() {
				this.rightName = '';
			},

			inputRightPrice(e) {
				this.rightPrice = e.detail.value;
			},

			doClearPrice() {
				this.rightPrice = 0;
			},

			inputOrgName(e) {
				this.orgName = e.detail.value;
			},

			inputCardNumber(e) {
				this.cardNumber = e.detail.value;
			},

			// 著作权人类别
			bindChangePersonType(e) {
				this.selPersonType = this.personType[e.detail.value];
			},

			clearPersonType() {
				this.selPersonType = null;
			},

			// 证件类型
			bindChangeCreType(e) {
				this.selCreType = this.creType[e.detail.value];
			},

			clearCreType() {
				this.selCreType = null;
			},

			// 选择软著分类
			onShowRightType() {
				this.showType = true;
			},

			// 选择软著分类
			bindChangeRightType(e) {
				const selectedIds = e.detail.value;
				const selectedItems = [];

				this.rightType.forEach(item => {
					item.checked = selectedIds.includes(item.dataId);
					if (item.checked) {
						selectedItems.push(item);
					}
				});

				this.rightType = [...this.rightType];
				this.selRightType = selectedItems;
			},

			clearRightType() {
				this.rightType.forEach(item => {
					item.checked = false;
				});

				this.selRightType = [];
				this.rightType = [...this.rightType];
			},

			confirmSelRightType() {
				this.showType = false;
			},

			// 显示地区选择
			onShowArea() {
				this.$refs.areaDialog.open()
			},
			closeDialog() {
				this.$refs.areaDialog.close()
			},
			clearArea() {
				this.selArea = null;
				this.selCity = null;
			},
			confirmSelArea() {
				this.showArea = false;
			},

			inputOrgPhone(e) {
				this.orgPhone = e.detail.value;
			},

			doClearPhone() {
				this.orgPhone = '';
			},

			// 获取字典
			async getDic() {
				try {
					const [right, area] = await Promise.all([
						Shop.doGetGoodsDic('ce3ded65-68ed-4f42-89da-de1b813b8f7e'), // 证件类型
						Shop.doGetAreaList('0')
					]);

					if (right && area) {
						this.creType = right;
						this.areaList = area;

						// 默认加载第一个area
						this.selCreType = this.creType[0];
						this.selArea = this.areaList[0];
						this.doGetArea(this.selArea.areaId);
					}
				} catch (err) {
					this.msgHint = '数据加载错误,请稍后重试';
					this.msgType = 'error';
					this.$refs.msg.open();

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			},

			// 获取区域
			async doGetArea(pId) {
				uni.showLoading({
					title: '加载中...',
				});

				try {
					const res = await Shop.doGetAreaList(pId);
					uni.hideLoading();

					if (res) {
						this.cityList = res;
						this.selCity = res[0];
					}
				} catch (err) {
					uni.hideLoading();
					this.msgHint = '数据加载错误,请稍后重试';
					this.msgType = 'error';
					this.$refs.msg.open();
				}
			},

			// 选中省市
			areaChange(e) {
				const currentValue = e.detail.value;
				const prevValue = this.prevValue;
				this.prevValue = currentValue;

				for (let i = 0; i < currentValue.length; i++) {
					if (currentValue[i] !== prevValue[i]) {
						if (i === 0) {
							// 获取city
							const area = this.areaList[currentValue[0]];
							this.selArea = area;
							this.doGetArea(area.areaId);
						} else {
							const city = this.cityList[currentValue[1]];
							this.selCity = city;
						}

						break;
					}
				}
			},

			// 校验参数
			checkParams() {
				const rules = [{
						field: 'selPersonType',
						message: '请选择受让人类别',
						validator: v => v !== null
					},
					{
						field: 'orgName',
						message: '请输入姓名或机构名称',
						validator: v => typeof v === 'string' && v.trim().length > 0
					},
					{
						field: ['selArea', 'selCity'],
						message: '请选择所在省市',
						validator: (_, data) => data.selArea !== null && data.selCity !== null
					},
					{
						field: 'orgPhone',
						message: '请输入合法的联系电话',
						validator: v => typeof v === 'string' && v.trim().length > 0 && isValidPhone(v.trim())
					},
					{
						field: 'selCreType',
						message: '请选择证件类型',
						validator: v => v !== null
					},
					{
						field: 'cardNumber',
						message: '请输入证件号码',
						validator: v => typeof v === 'string' && v.trim().length > 0
					}
				];

				for (const rule of rules) {
					let isValid;

					if (Array.isArray(rule.field)) {
						// 多字段联合验证
						isValid = rule.validator(null, this);
					} else {
						// 单字段验证
						const value = this[rule.field];
						isValid = rule.validator(value, this);
					}

					if (!isValid) {
						this.msgType = 'error';
						this.msgHint = rule.message;
						this.$refs.msg.open();
						return false;
					}
				}

				return true;
			},

			buildParams() {
				const {
					selArea,
					selCity
				} = this;
				return {
					buyCity: `${selArea.areaId},${selCity.areaId}`,
					buyIdcard: this.cardNumber,
					buyIdcardType: this.selCreType.dataId,
					buyName: this.orgName,
					buyPhone: this.orgPhone,
					buyType: this.selPersonType.dataId
				};
			},

			backPageRefresh() {
				const pages = getCurrentPages();
				const beforePage = pages[pages.length - 2];
				beforePage.$vm.needRefresh = true;
				uni.navigateBack();
			},

			// 提交
			async doSave() {
				try {
					const isLegal = this.checkParams();
					if (isLegal) {
						uni.showLoading({
							title: '上报中...',
						});

						const data = this.buildParams();
						console.log(data)
						await Shop.doSaveBuyPersonInfo(this.orderId, data);

						uni.hideLoading();
						this.msgHint = '上报成功';
						this.msgType = 'success';
						this.$refs.msg.open();
						setTimeout(() => {
							this.backPageRefresh();
						}, 1200);
					}
				} catch (err) {
					console.log(err)
					uni.hideLoading();
					this.msgHint = err.msg || '网络错误,请稍后重试';
					this.msgType = 'error';
					this.$refs.msg.open();
				}
			}
		},
	};
</script>

<style lang="scss" scoped>
	.page-divider-color {
		background-color: $divider-color;
	}

	.content-box {
		border-radius: 20rpx;
		margin-top: -10rpx;
	}

	.upload-img-box {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.content-container {
		margin: 0rpx -30rpx 30rpx -30rpx;
		background-color: white;
		display: flex;
		flex-direction: column;
		padding: 30rpx;
		height: 100vh;
	}

	.info-title {
		font-size: 36rpx;
		font-weight: bold;
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.info-title::before {
		content: "";
		width: 10rpx;
		height: 36rpx;
		margin-right: 5rpx;
		border-left: 15rpx solid $blue-color;
		vertical-align: middle;
	}

	.section {
		margin-bottom: 15rpx;
		margin-left: 20rpx;
	}

	.item {
		display: flex;
		flex-direction: column;
		margin-bottom: 10rpx;
		padding: 20rpx 10rpx;
		font-size: 28rpx;
	}

	.label {
		color: $text-color;
		font-weight: bold;
	}

	.select-content {
		margin-top: 15rpx;
		display: flex;
		height: 70rpx;
		flex-direction: row;
		border-radius: 5rpx;
		background-color: $bg-gray-input-color;
		padding: 0rpx 10rpx;
	}

	.select-content-no-h {
		margin-top: 15rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		min-height: 70rpx;
		flex-direction: row;
		border-radius: 5rpx;
		padding: 0rpx 15rpx 10rpx 0rpx;
		border-bottom: 1rpx solid $divider-color;
	}

	.select-content-item {
		margin-top: 15rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 70rpx;
		flex-direction: row;
		border-radius: 5rpx;
		padding: 0rpx 15rpx 10rpx 0rpx;
		border-bottom: 1rpx solid $divider-color;
	}

	.select-item-box {
		flex: 1;
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		padding: 5rpx;
	}

	.select-item-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: $divider-color;
		padding: 5rpx 15rpx;
		border-radius: 5rpx;
		font-size: 24rpx;
		margin-right: 15rpx;
		margin-top: 5rpx;
		color: $text-color;
	}

	.desc {
		flex: 1;
		color: #999;
		text-align: left;
		padding-left: 20rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		padding-right: 10px;
		align-items: center;
	}

	.select-time {
		color: $text-color;
		flex: 1;
		font-size: 28rpx;
		text-align: left;
	}

	.clear-icon {
		width: 20px;
		height: 20px;
		margin-right: 20rpx;
	}

	.value {
		flex: 1;
		text-align: left;
		font-size: 28rpx;
	}

	.value-hint {
		color: $text-gray-hint-color;
	}

	.v-select {
		color: $text-color;
	}

	.v-normal {
		color: $text-gray-hint-color
	}

	.custom-dialog {
		background-color: $white-color;
	}

	.custom-tips {
		margin-top: 80px;
	}

	.area-picker-box {
		width: 100%;
		height: 500rpx;
	}

	.area-picker-item {
		text-align: center;
		align-items: center;
		font-size: 28rpx;
	}

	/* 上传图片 */
</style>