<template>
	<view class="page-content">
    <uni-section title="选择图片分类上传" type="circle">
    </uni-section>
    <view class="section-content">
      <view class="type-choice-comp">
        <view class="type-item uni-secondary-color" v-for="(val, i) in typeList"
              :index="i" :key="i"
              :class="typeCurrent === i ? 'type-active' : ''"
              @click="onClickType({currentIndex: i})"
        >
          <view class="type-text">{{val}}</view>
        </view>
      </view>
      <uni-file-picker limit="9" title="最多选择9张图片"
                       :file-extname="fileExtname" mode="grid"
                       file-mediatype="image"
                       @success="successHandler"
                       @fail="failHandler"
                       @delete="deleteHandler"
                       autoUpload="false"
                       @select="selectHandler"
                       :disabled="checkUpload">
      </uni-file-picker>
      <view class="uploadNum">今日还可上传次数<span class="uploadText"> {{ getUploadNum }} </span>，已上传次数<span class="uploadText"> {{ uploadedNum }} </span></view>
    </view>
    <uni-section title="选择图片标签" subTitle="最多选择3个" type="circle">
    </uni-section>
    <view class="section-content">
      <view class="segmented-control">
        <uni-data-checkbox mode="tag" multiple v-model="signListSelected" :localdata="signList" @change="selectedSign" max="3"></uni-data-checkbox>
      </view>
    </view>
    <button class="upLoadBtn" size="default" :loading="loadingFlag" @click="$noMultipleClicks(saveImg)" :disabled="checkUpload">点击上传</button>
	</view>
</template>

<script>
	import {
		getSignList,listType,insertTiktokImg,queryUploadNum
	} from '@/api/index.js'
	import {
		deleteFile,uploadBatch
	} from '@/api/common.js'
	export default {
		data() {
			return {
				styleType: 'button',
				activeColor: '#007aff',
				typeCurrent: 0,
				typeId: 1,
        fileExtname: "png,jpg,jpeg",
				signList:[],
				signObject:{},
				typeList:[],
				typeIdList:[],
				loadingFlag: false,
				imgList:[],
				signListSelected:[],
				userInfo:{},
				uploadedNum: 0,
				noClick:true, //防止重复提交
			}
		},
		created() {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				console.log('havent userInfo')
				uni.showModal({
					content: '艺术家账户过期,请重新登录！',
					showCancel: false,
					success() {
						//没有缓存则跳转登录页面
						uni.reLaunch({
							url: '/pages/login/login'
						});
					}
				});
			} else {
				this.userInfo = userInfo;
				console.log('have userInfo')
			}
			this.getSignList();
			this.getTypeList();
			this.queryUploadNum();
		},
		computed:{
			//计算可上传次数
			getUploadNum(){
				return 50 - this.uploadedNum
			},
			//动态设置上传组件禁用
			checkUpload(){
				return this.uploadedNum >= 50;
			}
			
		},
		methods: {
			
			//获取标签列表
			async getSignList(){
				let that = this;
				const res = await getSignList({})
				if (res.data.code === 200) {
					for (let s of res.data.data) {
						let signObject = {}
						signObject.text = "#" +s.name
						signObject.value = s.id
						that.signList.push(signObject)
					}
					//console.log('signList',that.signList)
				} else {
					uni.showModal({
						content: '标签列表加载失败！',
						showCancel: false
					});
				}
			},
			
			//获取分类列表
			async getTypeList(){
				let that = this;
				const res = await listType({})
				if(res.data.code === 200){
					for (let s of res.data.data) {
						that.typeList.push(s.typeName);
						that.typeIdList.push(s.id);
					}
					//console.log('分类列表',that.typeList)
					//console.log('分类id列表',that.typeIdList)
				}else{
					uni.showModal({
						content: '分类列表加载失败！',
						showCancel: false
					});
				}
			},
			
			//获取艺术家今日上传图片次数
			async queryUploadNum(){
				let that = this;
				const checkParam = {
					creatorId: that.userInfo.id
				}
				const res = await queryUploadNum(checkParam);
				console.log(res)
				if(res.data.code === 200){
					that.uploadedNum = res.data.data;
				}else{
					uni.showModal({
						content: '获取艺术家上传次数失败！',
						showCancel: false
					});
				}
			},
			//选中分类事件
			onClickType(e2){
				let that = this;
				that.flag = false;
				that.typeCurrent = e2.currentIndex;
				that.typeId = that.typeIdList[e2.currentIndex];
				//console.log('typeId',that.typeId)
				uni.showLoading({
				  title: "加载中",
				  mask: true,
				  complete() {
				    uni.hideLoading();
				  },
				});
			},
			
			//选中标签事件
			selectedSign(e){
				let that = this;
				that.signListSelected = e.detail.value; 
				//console.log('that.signListSelected'+that.signListSelected);
			},
			//文件上传成功监听事件
			successHandler(e){
				console.log('文件上传成功！'+e)
			},
			//選擇文件监听事件
			selectHandler(e){
				console.log('选择了',e)
				let that = this;
				//检查是否可上传文件
				if(that.uploadedNum >=50){
					uni.showModal({
						content: "当日已达上传图片上限,请明日再来！",
						showCancel: false
					});
					return;
				}
				that.uploadHandler(e.tempFilePaths)
			},
			//文件上传失败监听事件
			failHandler(e){
				console.log('文件上传失败！'+e)
			},
			//文件删除监听事件
			deleteHandler(e){
				console.log('文件删除',e.tempFile.url)
				//调用文件删除方法
				const param = {
				  url: e.tempFile.url
				};
				deleteFile(param).then(res =>{
					if(res.data.code != 200){
						uni.showModal({
							content: "删除失败！",
							showCancel: false
						});
					}
				})
			},
			//上传文件监听事件
			    uploadHandler:function(e){
						let that = this;
						uni.showLoading({
							title: "上传中"
						});
						console.log('上传文件：',e)
						const tempFilePaths = e;
						for (var i = 0; i < tempFilePaths.length; i++) {
							//const tempFile = e.tempFiles[i];
							  uni.uploadFile({
								url: 'http://pc2zer.natappfree.cc/file/upload',
								name: 'file',
								// url: 'http://pc2zer.natappfree.cc/file/uploadBatch',
								// name: 'files',
								header:{
									"Content-Type": "multipart/form-data"
								},
								filePath: tempFilePaths[i],
								success:(uploadFileRes) => {
									uni.hideLoading();
									console.log('uploadFileRes',uploadFileRes);
									const back = JSON.parse(uploadFileRes.data);
										console.log("back",back)
										if (back.code == 200) {
											that.imgList.push(back.data);
										}
										 //console.log('imgList',that.imgList);
									},
								fail:() => {
									uni.hideLoading();
									uni.showModal({
										content: "上传失败，请联系客服！"
									});
								},
								complete: function() {
									uni.hideLoading();
								}
							});
						}
					
			},
			//提交表单
			  saveImg(){
				let that = this;
				//判断是否有上传图片
				if(that.imgList.length === 0){
					uni.showModal({
						content: "请选择图片上传！",
						showCancel: false,
					});
					return;
				}
				//检查是否可上传文件
				if(that.uploadedNum >=50){
					uni.showModal({
						content: "当日已达上传图片上限,请明日再来！",
						showCancel: false
					});
					return;
				}else{
					const param = {
							creatorId: that.userInfo.id,
							imgUrl: that.imgList,
							signList: that.signListSelected,
							status: 0,
							typeId: that.typeId
						}
						  insertTiktokImg(param).then(res =>{
							console.log('res',res)
							if(res.data.code === 200){
								uni.showToast({
									title: '上传成功!',
									duration: 2000,
									success:function(){
										setTimeout(function () {
											//返回主页，清空上传列表
											that.imgList = []
											that.signListSelected = []
											that.typeId = 1
											uni.reLaunch({
												url: '../index'
											});
										}, 2000);
									}
								});
							}else {
								uni.showModal({
								content: "艺术家图片上传失败！",
								showCancel: false,
								});
							}
						});
				}
			}
		},
		watch: {
		  typeId(newValue) {
		    if (newValue === 2) { //gif
          this.fileExtname = ".gif";
        } else {
          this.fileExtname =  "png,jpg,jpeg";
        }
      }
    }
	}
</script>

<style lang="scss" scoped>
  .page-content {
    min-height: 100vh;
    background: $uni-bg-color;
    width: 750rpx;

    ::v-deep .uni-section {
      background: none !important;
      margin-top: 0 !important;
      color: $uni-white;
    }

    ::v-deep .uni-section__content-title {
      color: $uni-white !important;
      font-size: 28rpx !important;
    }

    .section-content {
      width: 654rpx;
      margin: 0 auto;

    }

    .type-choice-comp {
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
      overflow: scroll;
      padding-top: 20rpx;
      padding-bottom: 20rpx;

      .type-item {
        font-size: 24rpx;
        line-height: 40rpx;
        height: 40rpx;
        padding: 0 20rpx;
        border-radius: 20rpx;
        flex-shrink: 0;

        .type-text {

        }

      }

      .type-active {
        background: $uni-primary;
        color: $uni-white !important;

      }

    }

    ::v-deep .file-title {
      color: $uni-white !important;
      font-size: 24rpx !important;
    }

    ::v-deep .file-count {
      color: $uni-white !important;
      font-size: 24rpx !important;
    }

    ::v-deep .file-picker__box-content {
      border-color: $uni-secondary-color !important;
    }
    ::v-deep .icon-add {
      background-color: $uni-secondary-color !important;
    }

    .uploadNum{
      color: $uni-white;
      font-size: 24rpx;
      margin-top: 20rpx;
      margin-bottom: 20rpx;

      .uploadText{
        color: $uni-primary;
        font-weight: 600;
      }
    }

    .segmented-control {

      ::v-deep .checklist-box {
        border: none !important;
        background: none !important;
        margin-right: 0 !important;
      }

      ::v-deep .checklist-text {
        color: $uni-secondary-color !important;
        font-size: 24rpx !important;
      }

      ::v-deep .is-checked .checklist-text {
        color: $uni-primary !important;
        font-size: 24rpx !important;
      }

      ::v-deep .is-disable .checklist-text {
        color: $uni-base-color !important;
        font-size: 24rpx !important;
      }

    }

    .upLoadBtn{
      width: 654rpx;
      height: 100rpx;
      line-height: 100rpx;
      background: linear-gradient(180.00deg, $uni-white 0%, $uni-white 100%);
      margin: 60rpx auto;
      color: $uni-btn-text-color;
      border-radius: 20rpx;
      font-size: 28rpx;
    }

  }


</style>
