<template>
	<view class="company">
		<nav-bar title="公司认证" color="#000"></nav-bar>
		<view class="company-content">
			<!-- 营业执照上传 -->
			<view class="company-title">上传公司营业执照</view>
			<view class="company-desc">请上传“{{ companyName }}”的营业执照</view>
			<view class="upload-img">
				<image v-if="filePath" :src="filePath" mode="aspectFit"
					style="height:100%; width:100%; border-radius:8rpx"></image>
				<view v-else class="text-item" @click="chooseImage">
					<u-icon name="plus" color="#999" size="40" style="margin-bottom: 8rpx;"></u-icon>
					上传营业执照
				</view>
				<view v-if="filePath" class="delete-btn" @click="deleteImage">×</view>
			</view>
			<view class="warning-title">注意事项</view>
			<view class="warning-desc">1.请上传所填公司一致的营业执照</view>
			<view class="warning-desc">2.营业执照信息和公章清晰可辨</view>

			<!-- 在职证明上传 -->
			<view class="upload-img">
				<view v-if="pdfFilePath" class="text-item">
					<u-icon name="file-text" color="#016bf6" size="40"></u-icon>
					<text style="margin-top: 8rpx;">已选择 PDF</text>
					<view class="delete-btn" @click="deletePDF">×</view>
				</view>
				<fileSelector v-else :isShowStyle="false" title="上传在职证明" allowType=".pdf" @fileSelected="choosePDF" />
			</view>
			<view class="warning-title">注意事项</view>
			<view class="warning-desc">1.请上传加盖公章的在职证明（仅限 PDF 文件）</view>

			<!-- 公司证明上传 -->
			<view class="upload-group">
				<view v-for="(img, index) in companyProofList" :key="index" class="upload-img">
					<image :src="img" mode="aspectFill" style="width:100%;height:100%;border-radius:8rpx;"></image>
					<view class="delete-btn" @click="deleteCompanyProof(index)">×</view>
				</view>
				<view v-if="companyProofList.length < 4" class="upload-img text-item" @click="chooseCompanyProof">
					<u-icon name="plus" color="#999" size="40" style="margin-bottom: 8rpx;"></u-icon>
					上传公司证明
				</view>
			</view>
			<view class="warning-title">注意事项</view>
			<view class="warning-desc">1.请上传公司前台LOGO照1-2张</view>
			<view class="warning-desc">2.请上传公司办公区照片1-2张</view>
		</view>

		<view class="bottom-btn" @click="goUnderReview">确认并提交</view>
	</view>
</template>

<script>
	import navBar from "@/components/nav-bar/index.vue";
	import configdata from '../../common/config.js';
	// 引入组件
	import fileSelector from '@/uni_modules/zhouquan-fileSelector/components/zhouquan-fileSelector/file-selector.vue';

	export default {
		data() {
			return {
				companyName: "",
				companyId: "",
				filePath: "", // 营业执照本地路径
				licenseUrl: "", // 营业执照上传后URL

				pdfFilePath: "", // 在职证明本地路径
				employmentVerification: "", // PDF 上传后URL

				companyProofList: [], // 公司证明本地预览图
				companyProofUrls: [], // 上传后URL列表

				action: configdata.APIHOST1 + '/alioss/upload'
			};
		},
		components: { navBar,fileSelector},
		onLoad(options) {
			if (options.companyName) this.companyName = decodeURIComponent(options.companyName);
			if (options.companyId) this.companyId = options.companyId;
		},
		methods: {
			// 通用上传
			async uploadSingleFile(path) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.action,
						filePath: path,
						name: 'file',
						success: (res) => {
							const data = JSON.parse(res.data);
							if (data.code === 0 && data.data) resolve(data.data);
							else reject(data.msg || '上传失败');
						},
						fail: (err) => reject(err)
					});
				});
			},

			// ======= 营业执照上传 =======
			async chooseImage() {
				uni.chooseImage({
					count: 1,
					success: async (res) => {
						let tempFilePath = res.tempFilePaths[0];

						// HEIC 转换
						if (tempFilePath.toLowerCase().endsWith('.heic')) {
							try {
								tempFilePath = await this.convertHeicToJpg(tempFilePath);
							} catch (e) {
								return uni.showToast({ title: 'HEIC 转换失败，请使用 JPG/PNG', icon: 'none' });
							}
						}
						this.filePath = tempFilePath;

						// 自动上传
						uni.showLoading({ title: '上传营业执照中...' });
						try {
							this.licenseUrl = await this.uploadSingleFile(tempFilePath);
							uni.showToast({ title: '上传成功', icon: 'success' });
						} catch (e) {
							uni.showToast({ title: '上传失败', icon: 'none' });
						} finally {
							uni.hideLoading();
						}
					}
				});
			},
			deleteImage() {
				this.filePath = "";
				this.licenseUrl = "";
			},

			// ======= 在职证明上传 (PDF) =======
			async choosePDF(e) {
				var that = this
				const validExtensions = ['pdf', 'doc', 'docx'];
				const ext = e.name.split('.').pop().toLowerCase();
				if (!validExtensions.includes(ext)) {
					this.$queue.showToast('仅支持PDF/DOC/DOCX格式')
					return;
				}
				uni.getFileInfo({
					filePath: e.path,
					success: (info) => {
						let attachment_size = (info.size / 1024).toFixed(1)
						that.$queue.uploadFile(e.path, function (path) {
							if (path){
								that.pdfFilePath = path;
								that.employmentVerification = path;
							}else
								that.$queue.showToast('文件上传失败')
						})
					},
					fail: (err) => {
						console.error('获取失败', err);
					}
				});
			},
			deletePDF() {
				this.pdfFilePath = "";
				this.employmentVerification = "";
			},

			// ======= 公司证明上传（多图） =======
			async chooseCompanyProof() {
				if (this.companyProofList.length >= 4) {
					return uni.showToast({ title: '最多上传4张图片', icon: 'none' });
				}
				uni.chooseImage({
					count: 4 - this.companyProofList.length,
					success: async (res) => {
						const imgs = res.tempFilePaths;
						for (let img of imgs) {
							this.companyProofList.push(img);
							uni.showLoading({ title: '上传中...' });
							try {
								const url = await this.uploadSingleFile(img);
								this.companyProofUrls.push(url);
							} catch (e) {
								uni.showToast({ title: '部分图片上传失败', icon: 'none' });
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},
			deleteCompanyProof(index) {
				this.companyProofList.splice(index, 1);
				this.companyProofUrls.splice(index, 1);
			},

			// ======= HEIC 转 JPG =======
			convertHeicToJpg(path) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: path,
						success: (img) => {
							const ctx = uni.createCanvasContext('myCanvas', this);
							ctx.drawImage(path, 0, 0, img.width, img.height);
							ctx.draw(false, () => {
								uni.canvasToTempFilePath({
									canvasId: 'myCanvas',
									fileType: 'jpg',
									quality: 0.9,
									success: (res) => resolve(res.tempFilePath),
									fail: (err) => reject(err)
								}, this);
							});
						},
						fail: (err) => reject(err)
					});
				});
			},

			// ======= 提交 =======
			async goUnderReview() {
				if (!this.licenseUrl) return uni.showToast({ title: '请上传营业执照', icon: 'none' });
				if (!this.employmentVerification) return uni.showToast({ title: '请上传在职证明PDF', icon: 'none' });
				if (this.companyProofUrls.length === 0) return uni.showToast({ title: '请上传公司证明图片', icon: 'none' });

				const data = {
					companyId: this.companyId,
					companyCertification: this.licenseUrl,
					employmentVerification: this.employmentVerification,
					companyVerification: this.companyProofUrls.join(',')
				};
				uni.showLoading({ title: '提交中...' });
				try {
					const res = await this.$Request.postJson("/app/company/updateCompany", data);
					uni.hideLoading();
					if (res.code === 0) {
						uni.showToast({ title: '提交成功', icon: 'success' });
						uni.navigateTo({ url: "/package/jobIntention/completeMsg" });
					} else {
						uni.showToast({ title: res.msg || '提交失败', icon: 'none' });
					}
				} catch (e) {
					uni.hideLoading();
					console.error('提交失败', e);
					uni.showToast({ title: '网络异常，请重试', icon: 'none' });
				}
			}
		}
	};
</script>

<canvas canvas-id="myCanvas" style="width:1px;height:1px;position:absolute;top:-1000rpx"></canvas>

<style scoped lang="scss">
	.company {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		font-family: DM Sans;

		.company-content {
			flex: 1;
			padding: 40rpx;
			box-sizing: border-box;
			overflow-y: auto;

			.company-title {
				color: #333;
				font-size: 40rpx;
				font-weight: 600;
				margin-bottom: 20rpx;
			}

			.company-desc {
				color: #666;
				font-size: 24rpx;
				line-height: 32rpx;
			}

			.upload-img {
				width: 142rpx;
				height: 142rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 20rpx;
				position: relative;
			}

			.upload-group {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
				margin-top: 20rpx;
			}

			.text-item {
				width: 142rpx;
				height: 142rpx;
				color: #666;
				font-size: 16rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				background: #eee;
				border-radius: 12rpx;
			}

			.delete-btn {
				position: absolute;
				top: 0;
				right: 0;
				width: 36rpx;
				height: 36rpx;
				line-height: 36rpx;
				text-align: center;
				background: rgba(0, 0, 0, 0.5);
				color: #fff;
				border-radius: 50%;
				font-size: 28rpx;
				z-index: 10;
			}

			.warning-title {
				color: #666;
				font-size: 24rpx;
				margin-top: 20rpx;
				font-weight: 500;
			}

			.warning-desc {
				color: #666;
				font-size: 24rpx;
				margin-top: 8rpx;
			}
		}

		.bottom-btn {
			border-radius: 999px;
			background: #016bf6;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 32rpx;
			padding: 16rpx 32rpx;
			margin: 20rpx;
			margin-bottom: 110rpx;
		}
	}
</style>
