<template>
	<s-layout class="set-wrap" title="商家入驻" :bgStyle="{ color: '#FFF' }">
		<template v-if="state.canUse">
			<uni-forms :model="state.model" :rules="state.rules" validateTrigger="bind" labelPosition="left" border
				class="form-box" labelWidth='200' ref="merchantFormRef">
				<view class="bg-white ss-p-x-30">
					<uni-forms-item name="name" label="商家名称" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.name" type="name" placeholder="请输入商家名称" :inputBorder="false"
							:placeholderStyle="placeholderStyle" :clearable="false" :disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="contact" label="联络人" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.contact" type="contact" placeholder="请输入联络人"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="contactNumber" label="联络人手机号" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.contactNumber" type="contactNumber" placeholder="请输入联络人手机号"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="legalPerson" label="法人" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.legalPerson" type="legalPerson" placeholder="请输入法人"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="legalPersonNumber" label="法人手机号" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.legalPersonNumber" type="legalPersonNumber"
							placeholder="请输入法人手机号" :inputBorder="false" :placeholderStyle="placeholderStyle"
							:clearable="false" :disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="identityCardFront" label="法人身份证正面" :required="!state.formStatus"
						:errorMessage="state.identityCardFrontError">
						<s-uploader v-model:url="state.model.identityCardFront" fileMediatype="image" limit="1"
							mode="grid" :imageStyles="{ width: '299rpx', height: '168rpx' }"
							:readonly="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="identityCardReverseSide" label="法人身份证反面" :required="!state.formStatus"
						:errorMessage="identityCardReverseSideError">
						<s-uploader v-model:url="state.model.identityCardReverseSide" fileMediatype="image" limit="1"
							mode="grid" :imageStyles="{ width: '299rpx', height: '168rpx' }"
							:readonly="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="areaId" label="所在地" :required="!state.formStatus"
						:errorMessage="state.areaIdError">
						<uni-data-picker v-model="state.model.areaId" :localdata="areaTree"
							:readonly="state.formStatus" />
					</uni-forms-item>

					<uni-forms-item name="email" label="邮箱" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.email" type="email" placeholder="请输入邮箱" :inputBorder="false"
							:placeholderStyle="placeholderStyle" :clearable="false" :disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="address" label="办公地址">
						<uni-easyinput v-model="state.model.address" type="address" placeholder="请输入办公地址"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="complaintsHotline" label="维权电话">
						<uni-easyinput v-model="state.model.complaintsHotline" type="complaintsHotline"
							placeholder="请输入维权电话" :inputBorder="false" :placeholderStyle="placeholderStyle"
							:clearable="false" :disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="customerServiceHotline" label="客服电话" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.customerServiceHotline" type="customerServiceHotline"
							placeholder="请输入客服电话" :inputBorder="false" :placeholderStyle="placeholderStyle"
							:clearable="false" :disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="website" label="官网">
						<uni-easyinput v-model="state.model.website" type="website" placeholder="请输入官网"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="bankName" label="开户银行" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.bankName" type="bankName" placeholder="请输入开户银行"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="accountName" label="账户名称" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.accountName" type="accountName" placeholder="请输入账户名称"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="accountNumber" label="账户号码" :required="!state.formStatus">
						<uni-easyinput v-model="state.model.accountNumber" type="number" placeholder="请输入账户号码"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>

					<uni-forms-item name="logoUrl" label="Logo">
						<s-uploader v-model:url="state.model.logoUrl" fileMediatype="image" limit="1" mode="grid"
							:imageStyles="{ width: '299rpx', height: '168rpx' }" :readonly="state.formStatus" />
					</uni-forms-item>
					<uni-forms-item name="businessLicensePicture" label="营业执照" :required="!state.formStatus"
						:errorMessage="state.businessLicensePictureError">
						<s-uploader v-model:url="state.model.businessLicensePicture" fileMediatype="image" limit="1"
							mode="grid" :imageStyles="{ width: '299rpx', height: '168rpx' }"
							:readonly="state.formStatus" />

					</uni-forms-item>
					<uni-forms-item name="brandLicensing" label="品牌授权书" :required="!state.formStatus"
						:errorMessage="state.brandLicensingError">
						<s-uploader v-model:url="state.model.brandLicensing" fileMediatype="image" limit="1" mode="grid"
							:imageStyles="{ width: '299rpx', height: '168rpx' }" :readonly="state.formStatus" />
						<view class="ss-m-t-20 " style="color: var(--ui-BG-Main);" @click="downloadTemplate"
							v-if="!state.model.brandLicensing">
							下载模板
						</view>

					</uni-forms-item>
					<uni-forms-item name="otherCertificate" label="其他证书">
						<s-uploader v-model:url="state.model.otherCertificate" fileMediatype="image" limit="9"
							mode="grid" :imageStyles="{ width: '299rpx', height: '168rpx' }"
							:readonly="state.formStatus" />

					</uni-forms-item>
					<uni-forms-item name="description" label="简介" :required="!state.formStatus">

						<uni-easyinput v-model="state.model.description" type="description" placeholder="请输入简介"
							:inputBorder="false" :placeholderStyle="placeholderStyle" :clearable="false"
							:disabled="state.formStatus" />
					</uni-forms-item>

					<uni-forms-item name="description" label="状态" v-if="state.userApplyStatus">
						<uni-easyinput v-model="statusName" type="description"  :inputBorder="false"
							:placeholderStyle="placeholderStyle" :clearable="false" :disabled="true" />
					</uni-forms-item>
				</view>
			</uni-forms>
			<su-fixed bottom placeholder bg="none">
				<view class="footer-box ss-p-20 ss-flex">
					<!-- 审核中不允许改 -->
					<!-- 通过后 变动 -->
					<!-- {{"用户是否申请过:"+state.userApplyStatus}}
				{{"当前状态"+state.model.checkStatus}}
				{{"当前状态是否能改动:" + !state.formStatus}} -->
					<button class="ss-rest-button btn" @tap="onSubmit" v-if="!state.userApplyStatus">提交</button>


					<template v-if="[0].includes(state.model.checkStatus)">
						<button class="ss-rest-button btn">审核中</button>
					</template>
					<template v-if="[1,2].includes(state.model.checkStatus)">
						<template v-if="!state.changeIng">
							<button class="ss-rest-button btn-two" @tap="openList">审核记录</button>
							<button class="ss-rest-button btn-two" @tap="onChange">变动</button>
						</template>
						<template v-else>
							<button class="ss-rest-button btn-two" @tap="onCancel">取消</button>
							<button class="ss-rest-button btn-two" @tap="onSave">保存并提交</button>
						</template>
					</template>

				</view>
			</su-fixed>
		</template>
		<template v-if="!state.canUse">
			<view style="position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);text-align:center">当前用户({{userInfo.mobile}})<br/>
已存在商户账号<br/>
请更换账号申请！
			</view>
		</template>
	</s-layout>
</template>


<script setup>
	import {
		computed,
		reactive,
		onBeforeMount,
		ref,
		unref,
		watch 
	} from 'vue';
	import sheep from '@/sheep';
	import {
		clone
	} from 'lodash';
	import {
		onLoad
	} from '@dcloudio/uni-app';

	import SaleApi from '@/sheep/api/sale/sale';
	import AreaApi from '@/sheep/api/system/area'
	import {
		email
	} from '@/sheep/validate/form';
	import {
		showAuthModal
	} from '@/sheep/hooks/useModal';
	const userInfo = computed(() => sheep.$store('user').userInfo);
	const state = reactive({
		canUse: true, //用户是否可以打开页面true 可以，false不行
		userApplyStatus: false, //用户是否已经申请过false未无 true为有
		formStatus: false, // 当前表单是否可以修改
		changeIng: false, //当前是否在修改
		model: {
			checkStatus: undefined,
			id: undefined,
			name: undefined,
			status: undefined,
			description: undefined,
			contact: undefined,
			address: undefined,
			contactNumber: undefined,
			website: undefined,
			createTime: undefined,
			complaintsHotline: undefined,
			customerServiceHotline: undefined,
			email: undefined,
			businessLicensePicture: undefined,
			expireTime: undefined,
			areaId: undefined,
			accountName: undefined,
			accountNumber: undefined,
			bankName: undefined,
			logoUrl: undefined,
			brandLicensing: undefined,
			otherCertificate: [],
			legalPerson: undefined,
			legalPersonNumber: undefined,
			identityCardFront: undefined,
			identityCardReverseSide: undefined,
		},
		areaIdError: '',
		businessLicensePictureError: '',
		brandLicensingError: '',
		identityCardFrontError: '',
		identityCardReverseSideError: '',
		rules: {
			name: {
				rules: [{
					required: true,
					errorMessage: '商户名称不能为空',
				}, ],
			},
			description: {
				rules: [{
					required: true,
					errorMessage: '简介不能为空',
				}, ],
			},
			contact: {
				rules: [{
					required: true,
					errorMessage: '联络人不能为空',
				}, ],
			},
			contactNumber: {
				rules: [{
					required: true,
					errorMessage: '联络人手机号不能为空',
				}, ],
			},

			customerServiceHotline: {
				rules: [{
					required: true,
					errorMessage: '客服电话不能为空',
				}, ],
			},
			email,
			legalPerson: {
				rules: [{
					required: true,
					errorMessage: '法人不能为空',
				}, ],
			},
			legalPersonNumber: {
				rules: [{
					required: true,
					errorMessage: '法人电话不能为空',
				}, ],
			},
			accountName: {
				rules: [{
					required: true,
					errorMessage: '账户名称不能为空',
				}, ],
			},
			accountNumber: {
				rules: [{
					required: true,
					errorMessage: '账户号码不能为空',
				}, ],
			},
			bankName: {
				rules: [{
					required: true,
					errorMessage: '开户银行不能为空',
				}, ],
			},
		}
	});
	const placeholderStyle = 'color:#BBBBBB;font-size:28rpx;line-height:normal';

	const statusName = computed(() => {
		const status = state.model.checkStatus;
		if (status === 0) {
			return '审核中';
		} else if (status === 1) {
			return '通过';
		} else if (status === 2) {
			return '拒绝';
		} else {
			return '';
		}
	});



	// 下载模板
	const downloadTemplate = () => {
		// console.log('下载模板')
		const fileUrl =
			'https://zxgz.newfeifan.cn/static/file/%E9%9D%9E%E7%8B%AC%E5%AE%B6%E5%93%81%E7%89%8C%E6%8E%88%E6%9D%83%E4%B9%A6.docx'
		// 创建并触发下载链接
		const a = document.createElement('a');
		a.href = fileUrl;
		a.download = '非独家品牌授权书.docx'; // 下载文件的名称（可以修改为你希望的名称）
		document.body.appendChild(a);
		a.click();

		// 移除下载链接
		document.body.removeChild(a);
	}
	// 校验联络人是否已经申请入驻，如果已经入驻，那就不给提交
	const checkNumber = () => {
		const {
			data,
			code
		} = SaleApi.checkContactNumber({
			mobile: state.model.contactNumber
		});
	}
	// 提交审核
	const merchantFormRef = ref(null);
	const onSubmit = async () => {
		// 参数校验
		const validate = await unref(merchantFormRef)
			.validate()
			.catch((error) => {
				console.log('error: ', error);
			});
		if (!validate) {
			return;
		}
		if (!state.model.areaId) {
			state.areaIdError = '请选择所在地';
			return;
		}
		if (!state.model.identityCardFront) {
			state.identityCardFrontError = '请选择上传法人身份证正面(国徽面)';
			return;
		}
		if (!state.model.identityCardReverseSide) {
			state.identityCardReverseSideError = '请选择上传法人身份证背面(人像面)';
			return;
		}
		if (!state.model.businessLicensePicture) {
			state.businessLicensePictureError = '请上传营业执照';
			return;
		}
		if (!state.model.brandLicensing) {
			state.brandLicensingError = '请上传品牌授权书';
			return;
		}


		const {
			data,
			code
		} = await SaleApi.createMerchant(state.model);
		if (code === 0) {
			await getInfo()
		}
	}

	// 修改
	const onChange = () => {
		state.formStatus = false;
		state.changeIng = true;
	}
	// 取消修改
	const onCancel = () => {
		state.formStatus = true;
		state.changeIng = false;
	}
	const openList = () => {
		sheep.$router.go('/pages/public/merchantApplyList', {
			merchantApplyId: state.model.id
		})
	}
	// 保存并提交
	const onSave = async () => {
		// 参数校验
		const validate = await unref(merchantFormRef)
			.validate()
			.catch((error) => {
				console.log('error: ', error);
			});
		if (!validate) {
			return;
		}

		const {
			data,
			code
		} = await SaleApi.updateMerchant(state.model);
		if (code === 0) {
			state.formStatus = true;
			state.changeIng = false;
			await getInfo()
		}

	}



	// 地区树
	const areaTree = ref([])

	function format(data) {
		return data.map((item) => ({
			text: item.name, // 显示的文本
			value: item.id, // 值
			children: item.children.length ? format(item.children) : null // 子项
		}));
	}
	const getInfo = async () => {
		const {
			data,
			code
		} = await SaleApi.getMerchant();
		if (code === 0 && data) {
			// 如果能查到东西就证明当前用户已经申请了商户,只需要展示即可
			state.model = data;
			state.userApplyStatus = true;

			state.formStatus = true;
		} else {
			state.userApplyStatus = false;
			state.formStatus = false;
		}
	}
	
	const isLogin = computed(() => sheep.$store('user').isLogin);
	// 监听到在这个页面登陆，并刷新页面
	watch(
		() => isLogin.value,
		(newVal) => {
			if (newVal) {
				window.location.reload()
			}
		}, {
			deep: true, // 深度监听
		},
	);
	
	onLoad(async (options) => {
		if (!isLogin.value) {
			showAuthModal();
		}else{
			await SaleApi.checkSystemUser().then(res => {
				console.log(!res.data)
				state.canUse = !res.data;
			})
			await AreaApi.getAreaTree().then(res => {
				areaTree.value = format(res.data)
			})

			await getInfo();
		}
	});
</script>

<style lang="scss" scoped>
	.icon {
		display: flex;
		align-items: center;
		margin-right: 7rpx
	}

	.icon image {
		width: 35rpx;
		height: 35rpx;
	}

	:deep() {

		.file-picker__progress {
			height: 0 !important;
		}

		.uni-list-item__content-title {
			font-size: 28rpx !important;
			color: #333333 !important;
			line-height: normal !important;
		}

		.uni-icons {
			font-size: 40rpx !important;
		}

		.is-disabled {
			color: #333333;
		}
	}

	:deep(.disabled) {
		opacity: 1;
	}

	.gender-name {
		font-size: 28rpx;
		font-weight: 500;
		line-height: normal;
		color: #333333;
	}

	.title-box {
		font-size: 28rpx;
		font-weight: 500;
		color: #666666;
		line-height: 100rpx;
	}

	.btn {
		width: 710rpx;
		height: 80rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		border-radius: 40rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: $white;
	}

	.btn-two {
		width: 310rpx;
		height: 80rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		border-radius: 40rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: $white;
	}

	.radio-dark {
		filter: grayscale(100%);
		filter: gray;
		opacity: 0.4;
	}

	.content-img {
		border-radius: 50%;
	}

	.header-box-content {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		overflow: hidden;
		border-radius: 50%;
	}

	.avatar-action {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		bottom: 0;
		z-index: 1;
		width: 160rpx;
		height: 46rpx;
		background: rgba(#000000, 0.3);

		.avatar-action-btn {
			width: 160rpx;
			height: 46rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: #ffffff;
		}
	}

	// 绑定项
	.account-list {
		background-color: $white;
		height: 100rpx;
		padding: 0 20rpx;

		.list-img {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}

		.list-name {
			font-size: 28rpx;
			color: #333333;
		}

		.info {
			.avatar {
				width: 38rpx;
				height: 38rpx;
				border-radius: 50%;
				overflow: hidden;
			}

			.name {
				font-size: 28rpx;
				font-weight: 400;
				color: $dark-9;
			}
		}

		.bind-box {
			width: 100rpx;
			height: 50rpx;
			line-height: normal;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;

			.bind-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: #f4f4f4;
				color: #999999;
			}

			.relieve-btn {
				width: 100%;
				height: 100%;
				border-radius: 25rpx;
				background: var(--ui-BG-Main-opacity-1);
				color: var(--ui-BG-Main);
			}
		}
	}

	.list-border {
		font-size: 28rpx;
		font-weight: 400;
		color: #333333;
		border-bottom: 2rpx solid #eeeeee;
	}

	image {
		width: 100%;
		height: 100%;
	}
</style>