<template>
	<div v-if="isshow">
		<el-form ref="ruleForm" :model="forminfo" :rules="ruleAddData" label-width="130px" class="demo-ruleForm">
			<el-row :gutter="20">
				<el-col v-if="!item.ishow" :style="iscopy?'display: flex;align-items: center;':''"
					:span="item.width == '50%（半行）'?12:item.width == '100%（一行）'?24:12" v-for="(item,index) in list1"
					:key="index">
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '单行文本'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-input v-model="item.value" placeholder="请输入" :maxlength="item.length?item.length:200"
							@input="e=>inputvalue(e,item.key)"></el-input>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '联系电话'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-input v-model="item.value" placeholder="请输入" :maxlength="item.length?item.length:200"
							@input="inputphone(index, $event,item.key)"></el-input>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '银行账号'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-input v-model="item.value" placeholder="请输入" :maxlength="item.length?item.length:200"
							@input="inputmo(index, $event,item.key)"></el-input>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '单行数字文本'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-input v-model.number="item.value" placeholder="请输入" :maxlength="item.length?item.length:200"
							@input="validateNumber(index, $event,item.key)"></el-input>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '多行文本'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-input show-word-limit rows="4" v-model="item.value" placeholder="请输入" type="textarea"
							:maxlength="item.length?item.length:200" @input="e=>inputvalue(e,item.key)" />
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '下拉选择'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-select v-model="item.value" clearable placeholder="请选择" style="width: 100%;"
							@change="e=>changexl(e,item.key)">
							<el-option v-for="(item1,index1) in item.list" :key="index1" :label="item1.label"
								:value="item1.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '日期'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-date-picker @change="e=>changetime(e,item.key)" v-model="item.value" type="date"
							value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%;"></el-date-picker>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '付款日'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-select v-model="item.value" placeholder="请选择" style="width: 100%;"
							@change="e=>changexl(e,item.key)">
							<el-option :label="val+'号'" :value="val+'号'" v-for="val in 31"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '商家'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<el-select v-model="item.value" placeholder="请选择" style="width: 100%;"
							@change="e=>changexl(e,item.key)">
							<el-option v-for="(item,index) in shopList" :key="index"
								:label="item.name+ ' ' + item.phone" :value="item.id+''" />
						</el-select>
					</el-form-item>
					<el-form-item :label="item.name" :prop="item.key" v-if="item.type == '附件'"
						:style="iscopy?'width: calc(100% - 35px)':''">
						<upfile :accept="'.docx,.doc'" filePath="mb" :inputtype="item.name" :value="item.value"
							@changimg="e=>changimg(e,index,item.key)"></upfile>
					</el-form-item>
					<i v-if="iscopy && item.type != '资源'" class="el-icon-copy-document greens tableBtn iterem"
						@click.stop="copytit(item.name)"></i>
					<el-form-item label="绑定资源" :prop="item.key" v-if="item.type == '资源' " style="width: 100%;">
						<div style="border: 1px solid #E5E5E5;padding: 1px" id="huodong">
							<div v-if="!iscopy && item.list.length != 1"
								style="font-size: 14px;border-bottom: 1px solid #E5E5E5;display: flex;justify-content: space-between;line-height:20px;background:#F2F3F5;">
								<div></div>
								<div style="color: #3F9B6A;padding:10px;" @click="mingShow(index,item.key)">
									添加
								</div>
							</div>
							<div style="padding: 15px;">
								<div style="padding: 0px 20px 0px 0px">
									<el-table :data="iscopy?[{}]:item.list"
										:header-cell-style="{fontSize: '14px',color:'#0009',fontWeight: 'normal',backgroundColor:'#F2F3F5'}">
										<el-table-column label="序号">
											<template slot-scope="scope">
												{{scope.$index + 1}}
											</template>
										</el-table-column>
										<el-table-column label="资源名称" show-overflow-tooltip>
											<template slot-scope="scope">
												<div style="display: flex;" v-if="iscopy">
													<div>资源名称</div>
													<i class="el-icon-copy-document greens tableBtn iterem"
														style="height: 0;" @click.stop="copytit('资源名称')"></i>
												</div>
												<div v-else>
													{{scope.row.shopName?scope.row.shopName:scope.row.advertisingName?scope.row.advertisingName:scope.row.venueName}}
												</div>
											</template>
										</el-table-column>
										<el-table-column label="资源类型" show-overflow-tooltip>
											<template slot-scope="scope">
												<div style="display: flex;" v-if="iscopy">
													<div>资源类型</div>
													<i class="el-icon-copy-document greens tableBtn iterem"
														style="height: 0;" @click.stop="copytit('资源类型')"></i>
												</div>
												<div v-else>
							{{scope.row.shopName ? '商铺' : scope.row.advertisingType?scope.row.advertisingType:'场地'}}
												</div>
											</template>
										</el-table-column>
										<el-table-column label="详细地址" show-overflow-tooltip>
											<template slot-scope="scope">
												<div style="display: flex;" v-if="iscopy">
													<div>详细地址</div>
													<i class="el-icon-copy-document greens tableBtn iterem"
														style="height: 0;" @click.stop="copytit('详细地址')"></i>
												</div>
												<div v-else> {{scope.row.shopName ? scope.row.detailedLocation :'-' }}</div>
											</template>
										</el-table-column>

										<el-table-column prop="notes" label="实际使用面积">
											<template slot-scope="scope">
												<div style="display: flex;" v-if="iscopy">
													<div>实际使用面积</div>
													<i class="el-icon-copy-document greens tableBtn iterem"
														style="height: 0;" @click.stop="copytit('实际使用面积')"></i>
												</div>
												<div v-else>
													{{scope.row.actualArea ? scope.row.actualArea :  scope.row.actualUsableArea?scope.row.actualUsableArea:'-'}}
												</div>
											</template>

										</el-table-column>

										<el-table-column label="操作" v-if="!iscopy && isdel == ''">
											<template slot-scope="scope">
												<div @click="MingDelete(scope.$index)" class="tableBtn greens">删除</div>
											</template>
										</el-table-column>
									</el-table>
								</div>
							</div>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-dialog :visible.sync="addcl" title="选择策略" width="65%" append-to-body center :close-on-click-modal="false"
			:close-on-press-escape="false" :show-close="false">
			<cl v-if="addcl" @minSev="minSevcl" @mingClose="mingClosecl"></cl>
		</el-dialog>
		<el-dialog :visible.sync="addzy" title="选择资源" width="65%" append-to-body center :close-on-click-modal="false"
			:close-on-press-escape="false" :show-close="false">
			<zy :maxSelection="1" publishStatus="2" v-if="addzy" @mingClose="mingClosezy" @minSev="minSevzy"></zy>
		</el-dialog>
	</div>
</template>
<script>
	import upfile from "@/components/fujianUpload/fujianList"
	import upimg from "@/components/ImageUpload/index"
	import cl from "@/components/change/cl"
	import zy from "@/components/change/zy"
	import {
		cerePlatformMerchant,
	} from '@/api/newly.js'
	export default {
		components: {
			upfile,
			upimg,
			cl,
			zy
		},
		props: {
			isdel: {
				type: String,
				default:''
			},
			list1: {
				type: Array,
				default: []
			},
			iscopy: {
				type: Boolean,
				default: false
			},

		},
		data() {
			return {
				keyon: '',
				addcl: false,
				addzy: false,
				shopId: '',
				shopList: [],
				ruleAddData: {

				},
				onindex: null,
				forminfo: {},
				isshow: false
			}
		},
		watch: {
			list1(val) {
				this.isshow = false
				if (this.list1.length > 0) {
					let c1 = {}
					let info1 = {}
					for (let index = 0; index < this.list1.length; index++) {
						const element = this.list1[index];
						if (element.isrequired == '是') {
							c1[element.key] = [{
								required: true,
								message: '请填写' + element.name,
								trigger: 'change'
							}]

						}
						info1[element.key] = element.value + ''
					}
					this.forminfo = info1
					this.ruleAddData = c1
					this.isshow = true
					// this.$updateRules(this.ruleAddData)
					console.error(this.ruleAddData)
					console.error({
						...this.forminfo
					})
				}
			},
		},
		async created() {
			await cerePlatformMerchant({
				checkState: '2',
				pageNumber: 0,
				pageSize: 1000,
			}).then(res => {
				this.shopList = res.data.content
				// console.error(this.shopList)
			})
			this.isshow = false
			if (this.list1.length > 0) {
				let c1 = {}
				let info1 = {}
				for (let index = 0; index < this.list1.length; index++) {
					const element = this.list1[index];
					if (element.isrequired == '是') {
						c1[element.key] = [{
							required: true,
							message: '请填写' + element.name,
							trigger: 'change'
						}]

					}
					info1[element.key] = element.value + ''
				}
				this.forminfo = info1
				this.ruleAddData = c1
				this.isshow = true
				// this.$updateRules(this.ruleAddData)
				console.error(this.ruleAddData)
				console.error({
					...this.forminfo
				})
			}

		},
		methods: {
			MingDelete(item) {
				this.list1[this.onindex].list = []
			},
			// 验证输入框
			async yanzhen() {
				let c1 = false
				await this.$refs.ruleForm.validate(async (valid) => {
					if (valid) {
						c1 = true
					} else {
						this.$message({
							type: 'error',
							message: '请填写必填项'
						})
						c1 = false
					}
				})
				return c1
			},

			inputvalue(e, onindex) {
				this.forminfo[onindex] = e
			},
			inputnumvalue(e, onindex) {
				this.forminfo[onindex] = e
			},
			changetime(e, onindex) {
				this.forminfo[onindex] = e
			},
			changexl(e, onindex) {
				this.forminfo[onindex] = e
			},
			async copytit(content) {
				// 复制结果
				let copyResult = true
				// 设置想要复制的文本内容
				const text = content || '复制内容为空哦~';
				// 判断是否支持clipboard方式
				if (!!window.navigator.clipboard) {
					// 利用clipboard将文本写入剪贴板（这是一个异步promise）
					await window.navigator.clipboard.writeText(text).then((res) => {
						console.log('复制成功');
					}).catch((err) => {
						console.log('复制失败--采取第二种复制方案', err);
						// clipboard方式复制失败 则采用document.execCommand()方式进行尝试
						copyResult = copyContent2(text)
					})
				} else {
					// 不支持clipboard方式 则采用document.execCommand()方式
					copyResult = copyContent2(text)
				}
				// 返回复制操作的最终结果
				return copyResult;
			},
			inputphone(index, value, onindex) {
				// 允许数字和短横线
				const cleanValue = value.replace(/[^\d-]/g, '');

				// 限制最大长度（手机11位，带区号座机最大13位如：0371-12345678）
				const truncatedValue = cleanValue.slice(0, 13);

				this.list1[index].value = truncatedValue;
				this.forminfo[onindex] = truncatedValue;
			},
			inputmo(index, value, onindex) {
				// 优化1：移除非数字字符（银行账号不需要小数点）
				const cleanValue = value.replace(/\D/g, '');

				// 优化2：限制最大长度19位
				const truncatedValue = cleanValue.slice(0, 19);

				// 优化3：仅更新值（去掉无效的正则判断）
				this.list1[index].value = truncatedValue;
				this.forminfo[onindex] = truncatedValue;

				// 优化4：添加格式美化（每4位空格分隔）
				// 如果需要显示格式可以启用（但存储值保持纯数字）：
				// this.$nextTick(() => {
				//     const formatted = truncatedValue.replace(/(\d{4})(?=\d)/g, '$1 ');
				//     if (formatted !== value) {
				//         this.list1[index].value = formatted;
				//     }
				// });
			},
			validateNumber(index, value, onindex) {
				// 使用正则表达式确保输入的是数字，并且可以包含最多两位小数
				const regex = /^\d+(\.\d{1,2})?$/;
				if (!regex.test(value)) {
					this.list1[index].value = value.replace(/[^\d.]/g, '').replace(/(\.\d{2}).*$/, '$1');

				}
				this.forminfo[onindex] = this.list1[index].value
			},
			changimg(e, type, onindex) {
				this.list1[type].value = e
				this.forminfo[onindex] = e
			},
			// changeRelatedMerchants(e) {
			//   this.shopId = e
			// },
			async mingShow(index, key) {
				this.addzy = true
				this.onindex = index
				this.keyon = key
			},
			// 处理策略对话框的确认操作
			minSevcl(data) {
				// 处理策略选择后的数据
				console.log('策略选择确认:', data);
				this.addcl = false; // 关闭策略对话框
			},
			// 处理策略对话框的关闭操作
			mingClosecl() {
				this.addcl = false; // 关闭策略对话框
			},
			// 处理资源对话框的确认操作
			minSevzy(data) {
				// 处理资源选择后的数据
				console.log('资源选择确认:', data);
				const filteredAddData = this.list1[this.onindex].list.filter(itemAdd => {
					// 使用 some 方法检查 this.multipleSelection 中是否存在具有相同 id 的元素
					return !data.some(itemMultiple => itemMultiple.id === itemAdd.id);
				});

				console.error(this.list1[this.onindex].list)
				//刷新渲染层
				this.$nextTick(() => {
					this.list1[this.onindex].list = filteredAddData.concat(data)
					this.list1[this.onindex].value = this.list1[this.onindex].list[0]
				})
				this.forminfo[this.keyon] = data[0].id
				this.addzy = false; // 关闭资源对话框
			},
			// 处理资源对话框的关闭操作
			mingClosezy() {
				this.addzy = false; // 关闭资源对话框
			}
		}
	}
</script>
<style lang="css">
	.el-upload {
		display: block;
		text-align: left;
	}

	.el-dialog__header {
		background-color: #F2F3F5;
		text-align: left;
	}

	.el-dialog__title {
		line-height: 30px;
		font-size: 15px;
		color: #303133;
	}

	.iterem {
		z-index: 99;
		margin-left: 10px;
		height: 40px;
		line-height: 25px;
	}
</style>