<template>
  <view class="switch-roles">
    <nav-bar title="公司信息" color="#000"></nav-bar>
    <view class="roles-content">
      <view class="content">
        <view class="progress-num"> <text>7</text>/8 </view>
        <view class="title">
          <view>展示公司照片</view>
        </view>
        <view class="desc">在公司主页上展示亮眼的照片，体现企业氛围与文化魅力；最多上传20张</view>

        <view class="content-index">
          <!-- 多图上传区域 -->
          <view class="upload-section">
            <view class="images-grid">
              <!-- 已上传的图片 -->
              <view
                class="image-item"
                v-for="(image, index) in imageList"
                :key="index"
                @click="previewImage(index)"
              >
                <image :src="image.url" mode="aspectFill" class="preview-image"></image>
                <view class="image-mask">
                  <u-icon name="eye" color="#fff" size="30"></u-icon>
                </view>
                <view class="delete-btn" @click.stop="deleteImage(index)">
                  <u-icon name="close" color="#fff" size="20"></u-icon>
                </view>
              </view>
              
              <!-- 添加图片按钮 -->
              <view
                class="upload-box"
                v-if="imageList.length < maxCount"
                @click="chooseImage"
              >
                <view class="upload-placeholder">
                  <u-icon name="plus" color="#999" size="40"></u-icon>
                  <text class="upload-text">添加照片</text>
                </view>
              </view>
            </view>

            <!-- 上传计数 -->
            <view class="upload-count" v-if="imageList.length > 0">
              已上传 {{ imageList.length }}/{{ maxCount }} 张
            </view>

            <!-- 上传进度 -->
            <view v-if="uploading" class="upload-progress">
              <view class="progress-bar">
                <view
                  class="progress-inner"
                  :style="{ width: uploadProgress + '%' }"
                ></view>
              </view>
              <text class="progress-text">{{ uploadProgress }}%</text>
            </view>
          </view>

          <!-- 注意事项 -->
          <view class="warning-box">
            <view class="warning-title">注意事项：</view>
            <view class="warning-list">
              <view class="warning-item">1. 请上传清晰且完整的图片</view>
              <view class="warning-item"
                >2.
                请上传品牌相关的图片，含有其他内容将无法通过审核（包括但不限于含有水印、招聘信息、联系方式、二维码等相关内容）</view
              >
              <view class="warning-item"
                >3. 上传图片须符合中国相关法律法规，不得含有违法内容或不良信息</view
              >
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="submit-btn" :class="{ disabled: imageList.length === 0 }" @click="goJobPostingSecond"
      >下一步</view
    >
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/index.vue";
export default {
  data() {
    return {
      text: "",
      imageList: [], // 上传的图片列表
      maxCount: 20, // 最大上传数量
      uploading: false, // 是否正在上传
      uploadProgress: 0, // 上传进度
	  companyData:{}
    };
  },
  components: {
    navBar,
  },
  onLoad(options) {
    if (options.companyData) {
      this.companyData = JSON.parse(options.companyData);
    }
  },
  methods: {
    // 选择图片
    chooseImage() {
      const that = this;
      const remainingCount = this.maxCount - this.imageList.length;
      
	  
	      // 1. 先判断系统类型，区分Android/iOS权限
			const systemInfo = uni.getSystemInfoSync();
			const isAndroid = systemInfo.system.includes('Android');
			const permissionType = isAndroid ? 'storage' : 'photos'; // Android=存储，iOS=相册
		  
			// 2. 权限检查（复用之前封装的 checkPermission 函数）
			const hasPermission = this.$queue.checkPermission(
			  permissionType,
			  isAndroid 
				? '选择/拍摄照片需要相机/相册权限，用于上传企业主页照片' // Android 专属提示
				: '选择/拍摄照片需要相机/相册权限，用于上传企业主页照片'
			);
		  
			if (!hasPermission) {
			  uni.showToast({ title: '未获取权限，无法选择照片', icon: 'none' });
			  return;
			}
	  
	  
      uni.chooseImage({
        count: remainingCount, // 最多选择剩余数量
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          
          // 批量上传图片
          that.uploadMultipleImages(tempFilePaths);
        },
        fail: (error) => {
          console.log("选择图片失败:", error);
          uni.showToast({
            title: "选择图片失败",
            icon: "none",
          });
        },
      });
    },

    // 批量上传图片
    uploadMultipleImages(filePaths) {
      const that = this;
      that.uploading = true;
      that.uploadProgress = 0;

      // 模拟上传进度
      // const progressTimer = setInterval(() => {
      //   that.uploadProgress += 10;
      //   if (that.uploadProgress >= 90) {
      //     clearInterval(progressTimer);
      //   }
      // }, 100);

      // 模拟批量上传成功
      // setTimeout(() => {
      //   clearInterval(progressTimer);
      //   that.uploadProgress = 100;

      //   // 将新图片添加到列表
      //   const newImages = filePaths.map(filePath => ({
      //     url: filePath,
      //     // 实际开发中这里应该是服务器返回的URL
      //   }));
        
      //   that.imageList = [...that.imageList, ...newImages];

      //   setTimeout(() => {
      //     that.uploading = false;
      //     uni.showToast({
      //       title: `成功上传${newImages.length}张图片`,
      //       icon: "success",
      //     });
      //   }, 500);
      // }, 1500);

      // 实际开发中应该使用下面的代码：
      let uploadedCount = 0;
      const totalCount = filePaths.length;
      
      filePaths.forEach((filePath, index) => {
		this.$queue.uploadFile(filePath,(path)=>{
				if(path) {
					uploadedCount++;					
					that.imageList.push({
					  url: path
					});
					
					// 更新进度
					that.uploadProgress = Math.floor((uploadedCount / totalCount) * 100);
					
					// 所有图片上传完成
					if (uploadedCount === totalCount) {
					  that.uploading = false;
					  uni.showToast({
					    title: `成功上传${uploadedCount}张图片`,
					    icon: 'success'
					  });
					}
				}
				else {
					uploadedCount++;
					console.log(`第${index + 1}张图片上传失败:`, error);
					if (uploadedCount === totalCount) {
					  that.uploading = false;
					  uni.showToast({
					    title: '部分图片上传失败',
					    icon: 'none'
					  });
					}
				}
		})
        // uni.uploadFile({
        //   url: '你的上传接口地址',
        //   filePath: filePath,
        //   name: 'file',
        //   formData: {
        //     'type': 'company_photo'
        //   },
        //   success: (uploadRes) => {
        //     uploadedCount++;
        //     const data = JSON.parse(uploadRes.data);
        //     if (data.code === 200) {
        //       that.imageList.push({
        //         url: data.data.url
        //       });
        //     }
            
        //     // 更新进度
        //     that.uploadProgress = Math.floor((uploadedCount / totalCount) * 100);
            
        //     // 所有图片上传完成
        //     if (uploadedCount === totalCount) {
        //       that.uploading = false;
        //       uni.showToast({
        //         title: `成功上传${uploadedCount}张图片`,
        //         icon: 'success'
        //       });
        //     }
        //   },
        //   fail: (error) => {
        //     uploadedCount++;
        //     console.log(`第${index + 1}张图片上传失败:`, error);
            
        //     if (uploadedCount === totalCount) {
        //       that.uploading = false;
        //       uni.showToast({
        //         title: '部分图片上传失败',
        //         icon: 'none'
        //       });
        //     }
        //   }
        // });
      });
    },

    // 预览图片
    previewImage(index) {
      if (this.imageList.length > 0) {
        const urls = this.imageList.map(item => item.url);
        uni.previewImage({
          urls: urls,
          current: index,
        });
      }
    },

    // 删除图片
    deleteImage(index) {
      const that = this;
      uni.showModal({
        title: "提示",
        content: "确定要删除这张照片吗？",
        success: (res) => {
          if (res.confirm) {
            that.imageList.splice(index, 1);
            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
          }
        },
      });
    },

    // 下一步
    goJobPostingSecond() {
      if (this.imageList.length === 0) {
        uni.showToast({
          title: "请上传公司照片",
          icon: "none",
        });
        return;
      }

      // 跳转到下一页，传递图片数据
      const imageUrls = this.imageList.map(item => item.url);
	  const companyData = this.companyData
	  companyData.photos=imageUrls.join(',')
      uni.navigateTo({
        url: "/my/renzheng/mainWorkIntro?companyData=" + encodeURIComponent(JSON.stringify(companyData)),
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.switch-roles {
  background-color: #fff;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;

  .roles-content {
    width: 100%;
    flex: 1;
    overflow: hidden;
    overflow-y: auto;

    .content {
      padding: 40rpx;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .progress-num {
        color: #016bf6;
        font-family: DM Sans;
        font-size: 24rpx;
        font-weight: 500;
        width: 100%;
        padding-bottom: 20rpx;
        box-sizing: border-box;
        text {
          font-size: 48rpx;
          font-weight: 700;
        }
      }

      .title {
        color: #333;
        width: 100%;
        font-family: DM Sans;
        font-size: 48rpx;
        font-weight: 700;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;
      }

      .desc {
        color: rgba(102, 102, 102, 1);
        width: 100%;
        font-family: DM Sans;
        font-size: 24rpx;
        font-weight: 400;
        line-height: 32rpx;
        letter-spacing: 0.5%;
        text-align: left;
        box-sizing: border-box;
        margin-bottom: 40rpx;
      }

      .content-index {
        width: 100%;

        .upload-section {
          margin-bottom: 20rpx;
          
          .images-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20rpx;
            margin-bottom: 20rpx;
            
            .image-item {
              width: 142rpx;
              height: 142rpx;
              border-radius: 8rpx;
              position: relative;
              overflow: hidden;
              
              .preview-image {
                width: 100%;
                height: 100%;
              }
              
              .image-mask {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.3);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s;
              }
              
              .delete-btn {
                position: absolute;
                top: 8rpx;
                right: 8rpx;
                width: 30rpx;
                height: 30rpx;
                background: rgba(0, 0, 0, 0.5);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
              }
              
              &:active .image-mask {
                opacity: 1;
              }
            }
            
            .upload-box {
              width: 142rpx;
              height: 142rpx;
              border-radius: 8rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              background: #eee;
              
              .upload-placeholder {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                
                .upload-text {
                  color: #666;
                  font-size: 20rpx;
                  margin-top: 8rpx;
                  font-family: DM Sans;
                }
              }
            }
          }
          
          .upload-count {
            color: #666;
            font-size: 24rpx;
            text-align: center;
            margin-bottom: 20rpx;
          }

          .upload-progress {
            display: flex;
            align-items: center;
            gap: 20rpx;

            .progress-bar {
              flex: 1;
              height: 8rpx;
              background: #f0f0f0;
              border-radius: 4rpx;
              overflow: hidden;

              .progress-inner {
                height: 100%;
                background: #016bf6;
                border-radius: 4rpx;
                transition: width 0.3s;
              }
            }

            .progress-text {
              color: #016bf6;
              font-size: 24rpx;
              min-width: 80rpx;
            }
          }
        }

        .warning-box {
          color: rgba(102, 102, 102, 1);
          font-family: DM Sans;
          font-size: 24rpx;
          font-weight: 400;
          line-height: 32rpx;
          .warning-item{
            margin-top: 8rpx;
          }
        }
      }
    }
  }

  .submit-btn {
    flex-shrink: 0;
    border-radius: 999px;
    background: #ff6600;
    color: rgba(255, 255, 255, 1);
    font-family: DM Sans;
    font-size: 32rpx;
    font-weight: 400;
    line-height: 48rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 24rpx 32rpx;
    box-sizing: border-box;
    margin: 30rpx 40rpx;
    margin-top: 20rpx;

    &.disabled {
      background: #ccc;
      color: #999;
    }
  }
}
</style>