<template>
  <view class="page">
    <u-navbar title="广告图设置" :border-bottom="false" :background="bgc" back-icon-color="#262B37" title-color='#262B37'
      title-size='36' height='36' id="navbar"></u-navbar>

    <view class="container">
      <!-- 广告图列表 -->
      <view class="ad-list">
        <view class="ad-item" v-for="(item, index) in adImages" :key="index">
          <image :src="item" mode="aspectFill" class="ad-image"></image>
          <view class="delete-btn" @click="deleteImage(index)">
            <u-icon name="close" color="#fff" size="24"></u-icon>
          </view>
        </view>
        
        <!-- 添加按钮 -->
        <view class="add-btn" @click="addImage" v-if="adImages.length < maxCount">
          <u-icon name="plus" size="48" color="#C7CDD3"></u-icon>
          <text class="add-text">添加广告图</text>
        </view>
      </view>
      
      <!-- 提示信息 -->
      <view class="tips">
        最多可上传{{maxCount}}张广告图，建议上传横屏图片
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <u-button 
          type="default" 
          shape="circle" 
          @click="handleCancel"
          custom-style="button-cancel"
        >
          取消
        </u-button>
        <u-button 
          type="primary" 
          shape="circle" 
          @click="handleSave"
          custom-style="button-save"
        >
          保存设置
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      bgc: {
        backgroundColor: "#fff",
      },
      adImages: [],
      maxCount: 1, // 最大上传数量
      hasChanges: false,
	  token:'',
	  userImgs:'',
	  flag:'',
	  adId:'',
	  areaId:''
    }
  },
  onLoad() {
    // 加载已有广告图
    this.loadAdImages()
  },
  onShow() {
  	this.getQiniuToken()
  },
  methods: {
	// 获取七牛云token
	getQiniuToken() {
		this.$u.get("/common/qiniuToken").then((res) => {
			if (res.code == 200) {
				this.token = res.data
			}
		})
	},
	 // 加载已有广告图
    loadAdImages() {
	  this.areaId = uni.getStorageSync('adminAreaid')
      this.$u.get(`/bst/ad/list?areaId=${this.areaId}`).then(res => {
		  if(res.code == 200) {
			  this.adId = res.rows[0].adId
			   if(res.rows.length > 0){
			   		this.flag = 2
			   		if(res.rows[0].picture){
						let picture = res.rows[0].picture.split(',')
						picture.forEach(item =>{
							this.adImages.push(item)
						})
					}
			   }else{
			   		 this.flag = 1
			   }
		  }
      })
    },
    addImage() {
	  let _this = this
	  const math = 'static/' + this.$u.guid(20)
      uni.chooseImage({
        count: this.maxCount - this.adImages.length, // 最多可选数量
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
            const tempFilePaths = res.tempFiles
            wx.uploadFile({
            	url: 'https://up-z2.qiniup.com',
            	name: 'file',
            	filePath: tempFilePaths[0].path,
            	formData: {
            		token: _this.token, //后端返回的token
            		key: 'smartmeter/img/' + math
            	},
            	success: function(res) {
            		let str = JSON.parse(res.data)
            		_this.userImgs = 'https://api.ccttiot.com/' +  str.key 
            		console.log(_this.userImgs)
					_this.adImages.push(_this.userImgs)
            	}
            })
        }
      })
    },
    deleteImage(index) {
      uni.showModal({
        title: '提示',
        content: '确定删除这张广告图吗？',
        success: (res) => {
          if (res.confirm) {
            this.adImages.splice(index, 1)
          }
        }
      })
    },
    handleCancel() {
      if (this.hasChanges) {
        uni.showModal({
          title: '提示',
          content: '您有未保存的修改，确定要取消吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    handleSave() {
      uni.showLoading({
        title: '保存中...',
        mask: true
      })
      // 这里替换为实际保存广告图的API
      // 示例：
	  let arr = this.adImages.join(',')
	  let data = {
		  picture:arr,
		  adId:this.adId,
		  areaId:this.areaId
	  }
	  if(this.flag == 1){
	  	this.$u.post(`/bst/ad`,data).then(res => {
	  	    if(res.code == 200){
	  	  	  uni.hideLoading()
	  	  	  uni.showToast({ title: '保存成功' })
	  	  	  setTimeout(() => uni.navigateBack(), 1500)
	  	    }else{
	  	  	  uni.showToast({
	  	  	  	title: res.msg,
	  	  	  	icon: 'none'
	  	  	  })
	  	    }
	  	})	  
	  }else{
		  this.$u.put(`/bst/ad`,data).then(res => {
		      if(res.code == 200){
		    	  uni.hideLoading()
		    	  uni.showToast({ title: '保存成功' })
		    	  setTimeout(() => uni.navigateBack(), 1500)
		      }else{
		    	  uni.showToast({
		    	  	title: res.msg,
		    	  	icon: 'none'
		    	  })
		      }
		  })
	  }
    },
  }
}
</script>

<style lang="scss">
page {
  background: #F7F8FA;
}

.container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  height: calc(20vh - 100rpx);
}

.ad-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 30rpx;
  
  .ad-item, .add-btn {
    width: 100%;
    height: 360rpx;
    margin-bottom: 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
    position: relative;
    background: #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  }
  
  .ad-image {
    width: 100%;
    height: 100%;
  }
  
  .delete-btn {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    width: 48rpx;
    height: 48rpx;
    background: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .add-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border: 2rpx dashed #C7CDD3;
    
    .add-text {
      margin-top: 16rpx;
      font-size: 28rpx;
      color: #C7CDD3;
    }
  }
}

.tips {
  font-size: 24rpx;
  color: #909090;
  text-align: center;
  margin-bottom: 40rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: auto;
  
  .u-button {
    width: 48%;
    height: 90rpx;
    font-size: 32rpx;
  }
  
  .button-cancel {
    background: #F0F2F5 !important;
    color: #6B7785 !important;
    border: none !important;
  }
  
  .button-save {
    background: linear-gradient(90deg, #4C97E7, #4297F3) !important;
    color: #fff !important;
    border: none !important;
    box-shadow: 0 4rpx 12rpx rgba(66, 151, 243, 0.3);
    
    &[disabled] {
      opacity: 0.6 !important;
    }
  }
}
</style>