<template>
  <view class="content">
    <view class="supplyInfo">
      <view class="flex">
        <label>公司名称：</label>
        <input type="text" v-model="supplyInfo.name" class="input card" />
      </view>
      <view class="flex">
        <label>活动人数：</label>
        <input type="number" v-model="supplyInfo.nums" class="input card" />
      </view>
      <view class="update_photo">
        <view class="title"></view>
        <view style="margin-bottom: 20rpx;">上传资料：</view>
        <view class="update_container card upload-parent-box">
          <view class="update_button display-flex">
            <view class="upload-box" @click="getImage('album')">
              <view class="img">
                <image src="/static/appeal/photo.png" class="photo"></image>
              </view>
              <view class="txt">上传</view>
            </view>
            <view
              class="display-flex upload-box-photo"
              v-for="(item, index) in uploadList"
              :key="index"
            >
              <image
                :src="item"
                mode="aspectFit"
                style="width: 100%; height: 100%"
                @click="showLarge(item)"
              />
              <image
                src="../../static/del.png"
                class="del-icon"
                mode="aspectFit"
                style="width: 30rpx; height: 30rpx"
                @click="delPhoto(index)"
              ></image>
            </view>
          </view>
        </view>
        <view class="approve-box">
			<view class="approve-title">请下载格式审批单，填写信息并加盖企业公章后上传</view>
			<view class="approve-content">格式审批单下载：<text @click="()=>openFile(areaObj.file_path)">{{areaObj.file_name}}</text></view>
		</view>
	  </view>
    </view>
    <view class="info">
      <view class="title">联系信息</view>
      <view class="name flex">
        <label>联系人：</label>
        <input type="text" class="card input" v-model="company.name" />
      </view>
      <view class="tel flex">
        <label>联系电话：</label>
        <input type="text" class="card input" v-model="company.tel" />
      </view>
    </view>
    <button class="submit" @tap="submit">提交</button>
  </view>
</template>
<script>
import md5 from "@/common/md5.js";
export default {
  data() {
    return {
      supplyInfo: {
        name: "",
        nums: "",
      },
      company: {
        name: uni.getStorageSync("supply_name") || "",
        tel: uni.getStorageSync("supply_tel") || "",
      },
      uploadList: [],
      imgIdList: [],
	  timeObj:{},
	  areaObj:{},
    };
  },
  onLoad(option) {
    this.timeObj = option;
	this.id = option.id
	this.getAreaDeatil(option.id);
	console.log(this.timeObj)
  },
  methods: {
	openFile(files){
				uni.showLoading({
					mask:true,
					title:'加载中...',
					icon:'none'
				})  
				uni.downloadFile({
					url: getApp().globalData.shareUrl + files,
					success: function(res) {
						var filePath = res.tempFilePath;
						//打开文件有效值 doc, xls, ppt, pdf, docx, xlsx, pptx
						uni.openDocument({
							filePath:filePath,
							showMenu:true,
							success: function(res) {
								uni.hideLoading();
								//that.downloadFile_onoff = true;
							},
							fail(res) {
								uni.showToast({
									title: '暂不支持此类型',
									icon:'none',
									duration: 2000
								});
								uni.hideLoading();
								//that.downloadFile_onoff = true;
							}
						}); 
						}
					});
	},  
	getAreaDeatil(areaId) {
	  let md5Sign = md5(
	    "method=" +
	      "area" +
	      "&timestamp=" +
	      getApp().globalData.globalTimestamp +
	      "&secret=" +
	      getApp().globalData.secret
	  );
	  let url =
	    getApp().globalData.shareUrl +
	    "api/api.php" +
	    "?method=area&source=area&action=info_by_id&timestamp=" +
	    getApp().globalData.globalTimestamp +
	    "&sign=" +
	    md5Sign;
	  let postData = {
	    area_id: areaId,
	  };
	  uni.request({
	    url: url,
	    method: "POST",
	    header: {
	      "content-type": "application/x-www-form-urlencoded",
	    },
	    data: postData,
	    success: (res) => {
	      if (res.data.code == 200) {
	        this.areaObj = res.data.data;
	      }
	    },
	    fail: () => {
	      console.log("连接失败");
	    },
	  });
	},  
    submit() {
		if (
		  !this.company.name || 
		  !this.company.tel 
		){
		  uni.showToast({
		    title: "联系信息不完善！",
		    icon: "error",
		  });
		  return;
		}
		
		if ( !this.supplyInfo.name){
		  uni.showToast({
		    title: "公司信息不完善！",
		    icon: "error",
		  });
		  return;
		}
		
		if (!Number(this.supplyInfo.nums)) {
		  uni.showToast({
		    title: "请正确填写活动人数！",
		    icon: "error",
		  });
		  return;
		}
		
		if (!this.imgIdList.join()){
		  uni.showToast({
		    title: "资料未上传！",
		    icon: "error",
		  });
		  return;
		}
		
		this.subscribeFn()
    },
	subscribeFn(){ //订阅通知消息
		let that = this;
		uni.requestSubscribeMessage({
		  tmplIds: [
		  //"XQcYMt2Tz4OZnrpXMTjetRIwPVftkJeM_XUkNPBtu8c",
		  //"ctLFsDd_HZ-lemoovoRPZAqjS8-1Gh2ELFSVz4FYtUY"    //第一次上线的时候把这两个都放开，然后再去掉这一条
		   "iZ3IABacOX7-EjGIyKnPtX2x3eJoYcwVqsOdEdRGvqU",//测试环境模板id
		  ],
		  success(res) {
		    that.submitFieldRequest();
		  },
		});
	},
	submitFieldRequest(){
		let md5Sign = md5(
		  "method=" +
		    "area" +
		    "&timestamp=" +
		    getApp().globalData.globalTimestamp +
		    "&secret=" +
		    getApp().globalData.secret
		);
		let url =
		  getApp().globalData.shareUrl +
		  "api/api.php" +
		  "?method=area&source=area&action=order&timestamp=" +
		  getApp().globalData.globalTimestamp +
		  "&sign=" +
		  md5Sign;
		let postData = {
		  area_id:this.timeObj.id, 
		  date:this.timeObj.day || getApp().globalData.nowTime,               //预约日期
		  hours:this.timeObj.hour,                       //预约时段，多个时段之间用,隔开
		  company_name :this.supplyInfo.name,
		  number  : this.supplyInfo.nums,
		  contact_name : this.company.name,
		  contact_phone : this.company.tel,
		  file_atttach_id : this.imgIdList.join(),
		  openId: getApp().globalData.open_id,
		};
		uni.request({
		  url: url,
		  method: "POST",
		  header: {
		    "content-type": "application/x-www-form-urlencoded",
		  },
		  data: postData,
		  success: (res) => {
		    if (res.data.code === 200) {
		      uni.showToast({
		        title: "提交成功",
		        icon: "none",
		        duration: 2000,
		      });
			  console.log(postData)
		      uni.setStorageSync("supply_name", this.company.name);
		      uni.setStorageSync("supply_tel", this.company.tel);
		      setTimeout(() => {
		        uni.navigateTo({
		          url: "/pages/makeField/viewDetail?id=" + this.timeObj.id,
		        });
		      }, 1500);
		    } else {
		      uni.showToast({
		        title: res.data.msg,
		        icon: "none",
		        duration: 2500,
		      });
		    }
		  },
		  fail: () => {
		    console.log("连接失败");
		  },
		});
	},
    getImage(type) {
      let that = this;
      if (that.uploadList.length >= 3) {
        uni.showToast({
          title: "最多上传3张图片",
          icon: "none",
          duration: 2500,
        });
        return;
      }
      uni.chooseImage({
        sourceType: [type],
        count: 3 - that.uploadList.length,
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        success: (res) => {
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            that.uploadList.push(res.tempFilePaths[i]);
            that.uploadFileRequest(res.tempFilePaths[i]);
          }
        },
      });
    },
    uploadFileRequest(fileVal) {
      uni.showLoading({
        title: "上传中",
        mask: true,
      });
      let that = this;
      let md5Sign = md5(
        "method=" +
          "upload" +
          "&timestamp=" +
          getApp().globalData.globalTimestamp +
          "&secret=" +
          getApp().globalData.secret
      );
      let url =
        getApp().globalData.shareUrl +
        "api/api.php" +
        "?method=upload&source=area&timestamp=" +
        getApp().globalData.globalTimestamp +
        "&sign=" +
        md5Sign;
      uni.uploadFile({
        url: url, //需要设置为全局
        filePath: fileVal,
        name: "file",
        formData: {
          file: fileVal,
        },
        success: (res) => {
          let tmpres = JSON.parse(res.data);
          console.log(tmpres);
          uni.hideLoading();
          that.imgIdList.push(tmpres.data.id);
        },
        fail: (res) => {
          console.log("上传请求失败");
          console.log(res);
        },
      });
    },
    delPhoto(idx) {
      this.uploadList.splice(idx, 1);
      this.imgIdList.splice(idx, 1);
    },
    showLarge(src) {
      uni.previewImage({
        urls: [src],
        longPressActions: {
          itemList: ["发送给朋友", "保存图片"],
          success: function (data) {},
          fail: function (err) {
            console.log(err.errMsg);
          },
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-parent-box {
  height: 150rpx;
  padding-top: 25rpx;
  padding-left: 20rpx;
}
.upload-box {
  display: flex;
  flex-flow: column;
  width: 25%;
  background-color: #e0e0e0;
  height: 140rpx;
  border-radius: 10rpx;
  padding-top: 15rpx;
  color: #000;
  image {
    width: 60rpx !important;
    height: 60rpx !important;
  }
}
.upload-box-photo {
  width: 25%;
  height: 110rpx;
  border-radius: 10rpx;
  padding-top: 15rpx;
  position: relative;
}
.del-icon {
  position: absolute;
  right: 0;
  width: 30rpx;
  height: 30rpx;
}

.update_button {
  text-align: center;
  display: flex;
}
.content {
  font-size: 28rpx;
  font-weight: 200;
  padding: 1% 2%;
  .title {
    font-size: 30rpx;
    margin: 4% 0;
	color: #000;
  }
  label {
    display: inline-block;
    width: 25%;
    vertical-align: middle;
	color: #7f7f7f;
  }
  .card {
    background-color: rgb(248, 247, 247);
    border-radius: 10rpx;
  }
  .flex {
    display: flex;
    align-items: center;
    margin-bottom: 2%;
  }
  .input {
    padding: 0 2%;
    margin: 2% 0;
    display: inline-block;
    width: 80%;
    height: 70rpx;
  }
  .supplyInfo {
    border-radius: 40rpx;
    padding: 4%;
    box-shadow: rgba(100, 100, 111, 0.2) 14rpx 14rpx 40rpx 14rpx;
	margin: 30rpx 0 30rpx 0;
	color: #7f7f7f;
	font-weight: 300;
    .area {
      height: 200rpx;
      padding: 20rpx;
      box-sizing: border-box;
    }
    .picker {
      width: 80%;
      height: 70rpx;
      background: rgb(248, 247, 247);
      display: flex;
      align-items: center;
      position: relative;
      .pick {
        width: 100%;
      }
      .picker_title {
        display: flex;
        width: 100%;
        margin-left: 30rpx;
        align-items: center;
        justify-content: space-between;
        .triangle-down {
          width: 0;
          height: 0;
          border-top: 15rpx solid rgb(173, 173, 173);
          border-left: 15rpx solid transparent;
          border-right: 15rpx solid transparent;
          position: absolute;
          right: 10rpx;
        }
      }
    }
    .upload-box {
      width: 25%;
      background-color: #e0e0e0;
      height: 110rpx;
      border-radius: 10rpx;
      padding-top: 15rpx;
    }
    .upload-box-photo {
      width: 25%;
      height: 110rpx;
      border-radius: 10rpx;
      padding-top: 15rpx;
      position: relative;
    }
    .del-icon {
      position: absolute;
      right: 0;
      width: 30rpx;
      height: 30rpx;
    }
    image {
      width: 60rpx;
      height: 60rpx;
    }
    .update_button {
      text-align: center;
      display: flex;
    }
  }
  .approve-box {
		  width: 100%;
		  font-size: 24rpx;
		  margin-top: 25rpx;
		  padding-left: 20rpx;
	  .approve-content {
			display: flex;
		    margin: 20rpx 0 30rpx 0;
				text{
					color:#00a7f0;
					cursor: pointer;
				}
	  }
  }
  .info {
    margin-top: 2%;
    border-radius: 40rpx;
    padding: 2% 4%;
    box-shadow: rgba(100, 100, 111, 0.2) 14rpx 14rpx 40rpx 14rpx;
	color: #7f7f7f;
	font-weight: 300;
  }
  .submit {
    color: white;
    font-weight: normal;
    width: 70%;
    border-radius: 20rpx;
    background-color: #02a7f0;
    margin: 50rpx auto;
  }
}
</style>