<template>
	<div class="app-container">
		<!-- 搜索行 -->
		<el-form
			:model="queryParams"
			ref="queryForm"
			size="small"
			:inline="true"
			v-show="showSearch"
			label-width="68px"
		>
			<!-- <el-form-item>
        <el-select clearable v-model="queryParams.smallPlaceTypeId" @change="handleQuery" placeholder="请选择场所类型">
          <el-option v-for="(item, i) in jiuxiaochangsuoTypeOptions4search" :key="i" :label="item.categoryName"
            :value="Number(item.id)"></el-option>
        </el-select>
      </el-form-item> -->
			<el-form-item>
				<el-select
					clearable
					v-model="queryParams.industryType"
					@change="handleQuery"
					placeholder="请选择行业类型"
				>
					<el-option
						v-for="(item, i) in hangyeTypeOptions"
						:key="i"
						:label="item.industryName"
						:value="Number(item.id)"
					></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="unitName">
				<el-input
					v-model="queryParams.unitName"
					placeholder="请输入单位名称"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					icon="el-icon-search"
					size="mini"
					@click="handleQuery"
					>查询</el-button
				>
			</el-form-item>
		</el-form>
		<!-- 按钮行 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					plain
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
					v-hasPermi="['merchant:add']"
					>新增</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="info"
					plain
					icon="el-icon-upload2"
					size="mini"
					@click="handleImport"
					v-hasPermi="['merchant:import']"
					>导入</el-button
				>
			</el-col>

			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
					v-hasPermi="['merchant:export']"
					>导出</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport2weima"
					v-hasPermi="['merchant:export']"
					>批量导出二维码</el-button
				>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport4yh"
					v-hasPermi="['merchant:export']"
					>导出企业隐患分析</el-button
				>
			</el-col>

			<right-toolbar
				:showSearch.sync="showSearch"
				@queryTable="getList"
			></right-toolbar>
		</el-row>
		<!-- 商铺信息表格 -->
		<el-table
			v-loading="loading"
			style="width: 100%"
			height="700px"
			:data="infoList"
			@selection-change="handleSelectionChange"
		>
			<el-table-column
				label="单位名称"
				align="center"
				width="150"
				prop="unitName"
			/>
			<el-table-column
				label="经营地址"
				align="center"
				width="300"
				prop="businessAddress"
			/>
			<el-table-column
				label="行业类型"
				align="center"
				prop="industryTypeName"
				width="100"
			/>
			<el-table-column
				label="使用性质"
				align="center"
				width="100"
				prop="useNature"
			/>
			<el-table-column
				label="统一社会信用代码"
				align="center"
				width="100"
				prop="unifiedSocialCreditCode"
			/>
			<el-table-column label="建筑面积" align="center" prop="area" width="80" />
			<el-table-column
				label="员工人数"
				align="center"
				prop="employeeCount"
				width="50"
			/>
			<el-table-column
				label="负责人"
				align="center"
				prop="merchantName"
				width="80"
			/>
			<el-table-column
				label="商户联系方式"
				align="center"
				prop="merchantPhone"
				width="120"
			/>
			<el-table-column
				label="所属社区"
				align="center"
				prop="communityName"
				width="80"
			/>
			<el-table-column
				label="所属街道"
				align="center"
				prop="streetName"
				width="80"
			/>
			<el-table-column
				label="所属网格"
				align="center"
				prop="gridName"
				width="80"
			/>
			<el-table-column
				label="网格员姓名"
				align="center"
				prop="gridMemberName"
				width="100"
			/>
			<el-table-column
				label="网格员电话"
				align="center"
				prop="gridMemberPhone"
				width="120"
			/>
			<el-table-column label="备注" align="center" prop="remark" width="80" />
			<el-table-column
				label="操作"
				align="center"
				class-name="small-padding fixed-width"
				fixed="right"
				width="200"
			>
				<template slot-scope="scope">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-download"
						@click="lookQRcode(scope.row)"
						v-hasPermi="['merchant:QRcode']"
						>下载二维码</el-button
					>
					<el-button
						size="mini"
						type="text"
						icon="el-icon-edit"
						@click="handleUpdate(scope.row)"
						v-hasPermi="['merchant:edit']"
						>修改</el-button
					>
					<el-button
						size="mini"
						type="text"
						icon="el-icon-delete"
						@click="handleDelete(scope.row)"
						v-hasPermi="['merchant:remove']"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 10"
			:total="total"
			:page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize"
			@pagination="getList"
		/>

		<!-- 添加或修改商户信息对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="140px">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="单位名称" prop="unitName">
							<el-input v-model="form.unitName" placeholder="请输入单位名称" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="隶属网格" prop="grid">
							<treeselect
								v-model="form.grid"
								:options="deptOptions"
								normalizer1="normalizer"
								placeholder="请选择隶属网格"
							/>
						</el-form-item>
						<!--  -->
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="行业类型" prop="industryType">
							<treeselect
								v-model="form.industryType"
								:options="hangyeTypeOptions"
								:normalizer="industryNormalizer"
								placeholder="请选择行业类型"
								@select="handleIndustryChange"
								:searchable="true"
								:clearable="true"
							/>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
						<el-form-item label="场所类型" prop="smallPlaceTypeId">
							<el-select
								v-model="form.smallPlaceTypeId"
								placeholder="请选择场所类型"
							>
								<el-option
									v-for="(item, i) in jiuxiaochangsuoTypeOptions"
									:key="i"
									:label="item.categoryName"
									:value="Number(item.id)"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col> -->
				</el-row>

				<el-form-item label="经营地址" prop="businessAddress">
					<el-input
						type="textarea"
						:rows="2"
						v-model="form.businessAddress"
						placeholder="请输入经营地址"
					/>
				</el-form-item>

				<el-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode">
					<el-input
						v-model="form.unifiedSocialCreditCode"
						placeholder="请输入统一社会信用代码"
					/>
				</el-form-item>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="员工人数" prop="employeeCount">
							<el-input
								v-model="form.employeeCount"
								placeholder="请输入员工人数"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="使用性质" prop="useNature">
							<el-input v-model="form.useNature" placeholder="请输入使用性质" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<!-- 新增字段容器 -->
					<el-col :span="12">
						<el-form-item label="负责人" prop="owner">
							<el-input
								v-model="form.merchantName"
								placeholder="请输入负责人"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<span style="color: red; font-size: 12px; margin-left: 140px"
							>爱山东商户登录手机号用</span
						>
						<el-form-item label="商户联系方式" prop="merchantPhone">
							<el-input v-model="form.merchantPhone" placeholder="" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12" v-if="form.id">
						<el-form-item label="所属网格员" prop="">
							<el-input v-model="form.gridMemberName" :disabled="true" />
						</el-form-item>
					</el-col>

					<!-- 生茶经营信息 -->
					<el-col :span="12">
						<el-form-item label="生产经营类型" prop="owner">
							<el-select
								clearable
								v-model="form.businessType"
								placeholder="请选择生产经营类型"
							>
								<el-option
									v-for="(item, i) in dict.type.business_type"
									:key="i"
									:label="item.label"
									:value="item.value + ''"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="建筑面积" prop="area">
							<el-input
								v-model="form.area"
								type="number"
								placeholder="请输入建筑面积"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="建筑结构" prop="buildingStructure">
							<el-input
								v-model="form.buildingStructure"
								placeholder="请输入建筑结构"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="产权人" prop="owner">
							<el-input v-model="form.owner" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="产权人电话" prop="owner">
							<el-input v-model="form.ownerPhone" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="经营人" prop="owner">
							<el-input v-model="form.operator" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="经营人电话" prop="owner">
							<el-input v-model="form.operatorPhone" placeholder="" />
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="房屋类型" prop="owner">
							<el-select
								clearable
								v-model="form.houseType"
								placeholder="请选择房屋类型"
							>
								<el-option
									v-for="(item, i) in dict.type.house_type"
									:key="i"
									:label="item.label"
									:value="item.value + ''"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="房屋用途" prop="owner">
							<el-select
								clearable
								v-model="form.houseUsage"
								placeholder="请选择房屋用途"
							>
								<el-option
									v-for="(item, i) in dict.type.house_usage"
									:key="i"
									:label="item.label"
									:value="item.value + ''"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="房东姓名" prop="owner">
							<el-input v-model="form.landlordName" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="房东联系方式" prop="owner">
							<el-input v-model="form.landlordContact" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="备注" prop="remark">
							<el-input
								v-model="form.remark"
								type="textarea"
								placeholder="请输入内容"
							/>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="24">
						<!-- 图片上传组件 -->
						<el-form-item label="平面疏散图片" prop="floorPlanPhotos">
							<imageUpload
								v-model="form.floorEvacuationPlan"
								:limit="4"
							></imageUpload>
						</el-form-item>
						<!-- 图片上传组件 -->
						<el-form-item label="平面图片" prop="floorPlanPhotos">
							<imageUpload
								v-model="form.floorPlanPhotos"
								:limit="4"
							></imageUpload>
						</el-form-item>
						<!-- 图片上传组件 -->
						<el-form-item label="门头图片" prop="storefrontPhotos">
							<imageUpload
								v-model="form.storefrontPhotos"
								:limit="1"
							></imageUpload>
						</el-form-item>
						<!-- 图片上传组件 -->
						<el-form-item label="营业执照" prop="businessLicensePhotos">
							<imageUpload
								v-model="form.businessLicensePhotos"
								:limit="1"
							></imageUpload>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 商铺导入对话框 -->
		<el-dialog
			:title="upload.title"
			:visible.sync="upload.open"
			width="400px"
			append-to-body
		>
			<el-upload
				ref="upload"
				:limit="1"
				accept=".xlsx, .xls"
				:headers="upload.headers"
				:action="upload.url + '?updateSupport=' + upload.updateSupport"
				:disabled="upload.isUploading"
				:on-progress="handleFileUploadProgress"
				:on-success="handleFileSuccess"
				:auto-upload="false"
				drag
			>
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip text-center" slot="tip">
					<div class="el-upload__tip" slot="tip">
						<el-checkbox
							v-model="upload.updateSupport"
						/>是否更新已经存在的用户数据
					</div>
					<span>仅允许导入xls、xlsx格式文件。</span>
					<el-link
						type="primary"
						:underline="false"
						style="font-size: 12px; vertical-align: baseline"
						@click="importTemplate"
						>下载模板</el-link
					>
				</div>
			</el-upload>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFileForm">确 定</el-button>
				<el-button @click="upload.open = false">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 导出条件选择弹窗 -->
		<el-dialog
			title="导出数据"
			:visible.sync="exportDialogVisible"
			width="600px"
			append-to-body
		>
			<el-form :model="exportParams" label-width="100px">
				<el-form-item label="管辖网格">
					<treeselect
						value-consists-of="BRANCH_PRIORITY"
						v-model="exportParams.deptIds"
						:options="deptOptions4search"
						:multiple="true"
						placeholder="请选择隶属网格"
					/>
				</el-form-item>
				<el-form-item label="创建时间">
					<el-date-picker
						v-model="exportParams.createTime"
						style="width: 100%"
						value-format="yyyy-MM-dd"
						type="daterange"
						range-separator="-"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					></el-date-picker>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="exportDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmExport">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listInfo,
	getInfo,
	delInfo,
	addInfo,
	updateInfo,
	getImgUrl,
	deptList,
	getJiuxiaochangsuoTypeList,
	getHangyeTypeList,
} from "@/api/stData/merchantList";
import { exportInfor } from "@/api/tool/gen.js";
import Treeselect from "@riophae/vue-treeselect";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
	name: "MerchantList",
	dicts: ["house_type", "house_usage", "business_type"],

	components: { Treeselect },

	data() {
		return {
			fileList: [], // 存储上传的文件列表
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 商户信息表格数据
			infoList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				unitName: null,
				businessAddress: null,
				smallPlaceTypeId: null,
				useNature: null,
				unifiedSocialCreditCode: null,
				area: null,
				employeeCount: null,
				owner: null,
				merchantPhone: null,
				grid: null,
				street: null,
				industryType: null,
			},
			// 导出弹窗参数
			exportDialogVisible: false,
			// 导出参数
			exportParams: {
				deptIds: [],
				createTime: [],
			},
			// 表单参数
			form: {
				floorEvacuationPlan: [],
				floorPlanPhotos: [], // 新增：存储图片URL数组
				storefrontPhotos: [], // 新增：存储图片URL数
				businessLicensePhotos: [], // 新增：存储图片URL数组
			},
			uploadImgUrl: process.env.VUE_APP_BASE_API + "common/upload", // 图片上传接口地址（需调整）
			// 表单校验
			rules: {
				unitName: [
					{ required: true, message: "请输入单位名称", trigger: "blur" },
				],
				businessAddress: [
					{ required: true, message: "经营地址不能为空", trigger: "blur" },
				],
				industryType: [
					{
						required: true,
						message: "请选择行业类型",
						trigger: "blur",
					},
				],
				useNature: [
					{ required: true, message: "请输入使用性质", trigger: "blur" },
				],
				unifiedSocialCreditCode: [
					{
						required: true,
						message: "请输入统一社会信用代码",
						trigger: "blur",
					},
					{
						pattern: /^[0-9A-Z]{18}/,
						message: "请输入正确的统一社会信用代码",
						trigger: "blur",
					},
				],
				area: [{ required: true, message: "请输入建筑面积", trigger: "blur" }],
				employeeCount: [
					{ required: true, message: "请输入员工人数", trigger: "blur" },
				],
				merchantName: [
					{ required: true, message: "请输入负责人", trigger: "blur" },
				],
				merchantPhone: [
					{ required: true, message: "请输入商户联系方式", trigger: "blur" },
					{
						pattern: /^1[3456789]\d{9}$/,
						message: "手机号码格式不正确",
						trigger: "blur",
					},
				],
				grid: [{ required: true, message: "请输入所属社区", trigger: "blur" }],
				// street: [
				// 	{ required: true, message: "请输入所属街道", trigger: "blur" },
				// ],
			},
			// 所有部门树选项
			deptOptions: undefined,
			// 所有部门树选项
			deptOptions4search: [],
			// 过滤掉已禁用部门树选项
			// enabledDeptOptions: undefined,

			hangyeTypeOptions: [],
			jiuxiaochangsuoTypeOptions: [],
			jiuxiaochangsuoTypeOptions4search: [],

			// 商铺导入参数
			upload: {
				// 是否显示弹出层（用户导入）
				open: false,
				// 弹出层标题（用户导入）
				title: "",
				// 是否禁用上传
				isUploading: false,
				// 是否更新已经存在的用户数据
				updateSupport: 0,
				// 设置上传的请求头部
				headers: { Authorization: "Bearer " + getToken() },
				// 上传的地址
				// url: process.env.VUE_APP_BASE_API + 'gq/merchant/importData', // 确定导入文件
				url: process.env.VUE_APP_BASE_API + "/export/file/upload",
			},
		};
	},
	created() {
		this.getList();
		this.getDeptTree();
		this.getDeptTree4search();
		this.getHangyeTypeList();
		this.getJiuxiaochangsuoTypeList4search();

		// listDept().then((response) => {
		// 	this.wanggeOptions = this.handleTree(response.data, "grid");
		// });
	},
	watch: {
		// 监听导出弹窗关闭事件，清空选择的值
		exportDialogVisible(newVal) {
			if (!newVal) {
				// 弹窗关闭时清空treeselect组件的值
				this.exportParams.deptIds = [];
				this.exportParams.createTime = [];
			}
		},
	},
	methods: {
		/** 确认导出操作 */
		confirmExport() {
			// 关闭弹窗
			this.exportDialogVisible = false;
			// 调用下载方法，传递导出参数
			this.download(
				"/gq/merchant/getQrCodes",
				{
					// 合并导出参数和查询参数中的其他可能需要的字段
					...this.queryParams,
					deptIds: JSON.stringify(this.exportParams.deptIds),
					createTime: JSON.stringify(this.exportParams.createTime),
				},

				`商铺二维码_${this.formatDate(
					new Date(),
					"YYYY年MM月DD日HH时mm分ss秒"
				)}.zip`
			);
		},
		/** 查询部门下拉树结构 */
		getDeptTree4search() {
			deptList().then((response) => {
				this.deptOptions4search = response.data;
			});
		},
		/** 转换行业类型数据结构 */
		industryNormalizer(node) {
			if (node.children && !node.children.length) {
				delete node.children;
			}
			return {
				id: node.id + "",
				label: node.industryName,
				children: node.children,
			};
		},
		// 查询场所类型类型列表
		getJiuxiaochangsuoTypeList4search(param) {
			console.log("pram", param, "查询场所类型类型列表");
			getJiuxiaochangsuoTypeList({
				industryId: "1",
			}).then((response) => {
				this.jiuxiaochangsuoTypeOptions4search = response.data;
			});
		},
		handleIndustryChange(node, instanceId) {
			// treeselect 的 @select 事件传递的是选中的节点对象
			const val = node ? node.id : this.form.industryType;
			console.log("修改", val);
			this.jiuxiaochangsuoTypeOptions = [];
			this.form.smallPlaceTypeId = null;
			if (val) {
				this.getJiuxiaochangsuoTypeList({
					industryId: val,
				});
			}
		},
		// 查询行业类型列表
		getHangyeTypeList() {
			getHangyeTypeList().then((response) => {
				this.hangyeTypeOptions = response.data;
			});
		},
		// 查询场所类型类型列表
		getJiuxiaochangsuoTypeList(param) {
			console.log("pram", param, "查询场所类型类型列表");
			getJiuxiaochangsuoTypeList(param).then((response) => {
				this.jiuxiaochangsuoTypeOptions = response.data;
			});
		},

		/** 查询部门下拉树结构 */
		getDeptTree() {
			deptList().then((response) => {
				this.deptOptions = response.data;
				// this.enabledDeptOptions = this.filterDisabledDept(
				// 	JSON.parse(JSON.stringify(response.data))
				// );
			});
		},
		// 过滤禁用的部门
		filterDisabledDept(deptList) {
			return deptList.filter((dept) => {
				if (dept.disabled) {
					return false;
				}
				if (dept.children && dept.children.length) {
					dept.children = this.filterDisabledDept(dept.children);
				}
				return true;
			});
		},
		/** 查询商户信息列表 */
		getList() {
			this.loading = true;
			listInfo(this.queryParams).then((response) => {
				this.infoList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				unitName: null,
				businessAddress: null,
				smallPlaceTypeId: null,
				useNature: null,
				unifiedSocialCreditCode: null,
				area: null,
				employeeCount: null,
				owner: null,
				merchantPhone: null,
				grid: null,
				street: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				remark: null,
				floorEvacuationPlan: [],
				floorPlanPhotos: [], // 新增：清空图片URL数组
				storefrontPhotos: [], // 新增：清空图片URL数组
				businessLicensePhotos: [], // 新增：清空图片URL数组
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加商户信息";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const id = row.id || this.ids;
			getInfo(id).then((response) => {
				this.form = response.data;
				if (!this.form.industryType) {
					this.form.industryType = null;
				}
				this.open = true;
				this.title = "修改商户信息";
				this.getJiuxiaochangsuoTypeList({
					industryId: row.industryType,
				});
			});
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate((valid) => {
				if (valid) {
					console.log(
						"if(this.form.floorEvacuationPlan",
						this.form.floorEvacuationPlan,
						!this.form.floorEvacuationPlan.length
					);

					if (!this.form.floorEvacuationPlan.length) {
						this.form.floorEvacuationPlan = "";
					}
					if (!this.form.floorPlanPhotos.length) {
						this.form.floorPlanPhotos = "";
					}
					if (!this.form.businessLicensePhotos.length) {
						this.form.businessLicensePhotos = "";
					}
					if (!this.form.storefrontPhotos.length) {
						this.form.storefrontPhotos = "";
					}
					if (this.form.id != null) {
						// 删除对应参数
						delete this.form["floorEvacuationPlanH5"];
						delete this.form["floorPlanPhotosH5"];
						delete this.form["businessLicensePhotosH5"];
						delete this.form["storefrontPhotosH5"];
						updateInfo(this.form).then((response) => {
							this.$modal.msgSuccess("修改成功");
							this.open = false;
							this.getList();
						});
					} else {
						addInfo(this.form).then((response) => {
							this.$modal.msgSuccess("新增成功");
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$modal
				.confirm('是否确认删除商户信息编号为"' + ids + '"的数据项？')
				.then(function () {
					return delInfo(ids);
				})
				.then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				})
				.catch(() => {});
		},
		// 查看二维码
		// 修改背景图片路径和二维码数据处理方式
		lookQRcode(item) {
			// 	const createCanvasImage = (bgUrl, qrUrl) => {
			// 		return new Promise((resolve, reject) => {
			// 			const canvas = document.createElement("canvas");
			// 			const ctx = canvas.getContext("2d");

			// 			// 加载背景图
			// 			const img = new Image();
			// 			img.crossOrigin = "Anonymous"; // 解决跨域问题
			// 			img.src = bgUrl;
			// 			img.onload = () => {
			// 				canvas.width = img.width;
			// 				canvas.height = img.height;
			// 				ctx.drawImage(img, 0, 0);

			// 				// 加载二维码图
			// 				const qrImg = new Image();
			// 				qrImg.src = qrUrl;
			// 				qrImg.onload = () => {
			// 					// 绘制二维码（调整为左下角）
			// 					const qrSize = 610;
			// 					// 在lookQRcode方法中修改二维码定位坐标
			// 					ctx.drawImage(
			// 						qrImg,
			// 						(canvas.width - qrSize) / 2, // 水平居中
			// 						(canvas.height - qrSize) / 2 + 40, // 垂直居中
			// 						qrSize,
			// 						qrSize
			// 					);
			// 					// 转换画布为可下载格式
			// 					canvas.toBlob((blob) => {
			// 						resolve(URL.createObjectURL(blob));
			// 					}, "image/png");
			// 				};
			// 				qrImg.onerror = () => reject("二维码加载失败");
			// 			};
			// 			img.onerror = () => reject("背景图加载失败");
			// 		});
			// 	};

			// 	getImgUrl(item.id).then(async (res) => {
			// 		if (res.code === 200) {
			// 			try {
			// 				// 修正背景图路径（需要将图片放入public目录）
			// 				const bgPath = "/img/erweimabg.png";
			// 				// 生成带前缀的base64数据
			// 				const qrData = res.data;

			// 				const mergedUrl = await createCanvasImage(bgPath, qrData);

			// 				// 创建下载链接
			// 				const aLink = document.createElement("a");
			// 				aLink.download = `${item.unitName}_合成二维码.png`;
			// 				aLink.href = mergedUrl;
			// 				document.body.appendChild(aLink); // 需要临时添加到DOM
			// 				aLink.click();
			// 				document.body.removeChild(aLink);
			// 				URL.revokeObjectURL(mergedUrl); // 释放内存
			// 			} catch (error) {
			// 				console.error("图片合成失败:", error);
			// 				this.$message.error("下载失败，请检查控制台");
			// 			}
			// 		}
			// 	});
			// },

			getImgUrl(item.id).then((res) => {
				if (res.code === 200) {
					let base64 = res.data.toString();
					let byteCharacters = atob(
						base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
					);
					let byteNumbers = new Array(byteCharacters.length);
					for (let i = 0; i < byteCharacters.length; i++) {
						byteNumbers[i] = byteCharacters.charCodeAt(i);
					}
					let byteArray = new Uint8Array(byteNumbers);
					let blob = new Blob([byteArray], {
						type: undefined,
					});
					let aLink = document.createElement("a");
					aLink.download = `${item.unitName}.png`; //这里写保存时的图片名称
					aLink.href = URL.createObjectURL(blob);
					aLink.click();
				}
			});
		},
		exportData() {
			exportInfor().then((res) => {
				let url = window.URL.createObjectURL(res);
				let a = document.createElement("a");
				document.body.appendChild(a);

				a.href = url;
				a.download = "失败数据列表.xlsx";
				a.click();

				window.URL.revokeObjectURL(url);
			});
		},
		// 文件上传中处理
		handleFileUploadProgress(event, file, fileList) {
			this.upload.isUploading = true;
		},
		// 文件上传成功处理
		handleFileSuccess(response, file, fileList) {
			this.upload.open = false;
			this.upload.isUploading = false;
			this.$refs.upload.clearFiles();
			this.$alert(
				"<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
					"导入成功：" +
					response.data.success +
					"条<br/>" +
					"导入失败：" +
					response.data.error +
					"条<br/>" +
					"</div>",
				"导入结果",
				{
					dangerouslyUseHTMLString: true,
					callback: () => {
						this.exportData();
					},
				}
			);
			this.getList();
		},
		// 提交上传文件
		submitFileForm() {
			this.$refs.upload.submit();
		},
		/** 下载模板操作 */
		importTemplate() {
			this.download(
				"gq/merchant/importTemplate",
				{},
				`商铺信息模版_${this.formatDate(
					new Date(),
					"YYYY年MM月DD日 HH时mm分ss秒"
				)}.xlsx`
			);
		},
		/** 导入按钮操作 */
		handleImport() {
			this.upload.title = "用户导入";
			this.upload.open = true;
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"/gq/merchant/export",
				{
					...this.queryParams,
				},
				`商铺信息列表_${this.formatDate(
					new Date(),
					"YYYY年MM月DD日HH时mm分ss秒"
				)}.xlsx`
			);
		},
		handleExport2weima() {
			// 打开导出弹窗，而不是直接导出
			this.exportDialogVisible = true;
		},

		handleExport4yh() {
			this.download(
				"/gq/hiddenDanger/exportHidden",
				{
					...this.queryParams,
				},
				`企业隐患分析_${this.formatDate(
					new Date(),
					"YYYY年MM月DD日HH时mm分ss秒"
				)}.xlsx`
			);
		},

		// 修改后的日期格式化方法
		formatDate(date, format) {
			const pad = (n) => (n < 10 ? "0" + n : n);
			return format
				.replace("YYYY", date.getFullYear())
				.replace("MM", pad(date.getMonth() + 1))
				.replace("DD", pad(date.getDate()))
				.replace("HH", pad(date.getHours()))
				.replace("mm", pad(date.getMinutes()))
				.replace("ss", pad(date.getSeconds()))
				.replace("年", "年") // 保持中文年字符
				.replace("月", "月") // 保持中文月字符
				.replace("日", "日") // 保持中文日字符
				.replace("时", "时") // 保持中文单位
				.replace("分", "分")
				.replace("秒", "秒");
		},
	},
};
</script>
<style scoped lang="scss">
::v-deep .vue-treeselect__menu-container {
	width: auto !important;
	min-width: 100% !important;
}

::v-deep .vue-treeselect__menu {
	width: 100% !important;
}
</style>
