<template>
  <view class="content">
    <view class="header">
      <view class="title-read">
        <view class="title">
          {{ model.title }}
        </view>
        <view class="read">阅读量 {{ model.read }}</view>
      </view>
      <!-- <view class="header-image">
        <image :src="model.url" alt="" />
      </view> -->
    </view>
    <view class="active-deatil">
      <ul>
        <li>
          <p class="name">活动时间</p>
          <p class="deatil-content">{{ model.date }}</p>
        </li>
        <li>
          <p class="name">活动类型</p>
          <p class="deatil-content">{{ model.type == 1 ? "线上" : "线下" }}</p>
        </li>
        <li>
          <p class="name">主办方</p>
          <p class="deatil-content">{{ model.way }}</p>
        </li>
      </ul>
    </view>
    <view class="rich">
      <activityRichCard :model="textModel" :isFold="true" />
    </view>
    <view class="share-box">
		<view class="share">
			<button class="share" @click="shareActive()" open-type="share">
				<image src="../../static/share_icon.png"></image>
			</button>
			<view class="shareCount">{{ model.share }}</view>
		</view>
      <view class="button">
		  <button v-if="!isJoin"
          @click="subscribeActivity(model.status)"
          :disabled="!(model.status == 0 && model.type == 2)"
          :class="{
            start: model.status == 0 && model.type == 2,
            begun: model.status == 1,
            ended: model.status == 2,
            falseStart: model.status == 0 && model.type == 1,
          }"
        >
          {{ model.activiteState }}
        </button>
		<button disabled="true" class="ended" v-if="isJoin">
		  已报名
		</button>
		</view>
      <!--         "status":"活动状态 0：待开始；1：已开始； 2：已结束
        "type":"活动类型 1:线上;2 线下"} -->
    </view>
  </view>
</template>

<script>
import md5 from "@/common/md5.js";
import activity_rich_card from "../policy/policy_rich_card";
export default {
  filters: {
    formDateTime(value) {
      if (value) {
        const time = new Date(value * 1000);
        const y = time.getFullYear();
        const m =
          time.getMonth() + 1 < 10
            ? "0" + (time.getMonth() + 1)
            : time.getMonth() + 1;
        const d = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
        // const h = time.getHours()
        // const mm = time.getMinutes();
        // const s = time.getSeconds();
        return y + "." + m + "." + d;
      } else {
        return "";
      }
    },
    formDateTimeSecond(value) {
      if (value) {
        const time = new Date(value * 1000);
        // const y = time.getFullYear();
        // const m = (time.getMonth() + 1) < 10 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1);
        // const d = time.getDate() < 10 ? '0' + time.getDate(): time.getDate();
        const h =
          time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
        const mm =
          time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
        return h + ":" + mm;
      } else {
        return "";
      }
    },
  },
  components: {
    activityRichCard: activity_rich_card,
  },
  data() {
    return {
      id: "",
	  isJoin:false,
      model: {
        title: "",
        read: 123,
        url: "",
        date: "",
        type: 1,
        status: 0,
        way: "",
        share: 0,
        activiteState: "",
      },
      textModel: {
        title: "活动内容",
        text: "",
      },
    };
  },
  onLoad(op) {
    this.id = op.id;
    this.getActivityDeatil();
  },
  methods: {
	  shareRequest() {
	    let md5Sign = md5(
	      "method=" +
	        "user" +
	        "&timestamp=" +
	        getApp().globalData.globalTimestamp +
	        "&secret=" +
	        getApp().globalData.secret
	    );
	    let url =
	      getApp().globalData.shareUrl +
	      "api/api.php" +
	      "?method=user&source=activity&action=repost&timestamp=" +
	      getApp().globalData.globalTimestamp +
	      "&sign=" +
	      md5Sign;
	    uni.request({
	      url: url,
	      method: "POST",
	      header: {
	        "content-type": "application/x-www-form-urlencoded",
	      },
	      data: {
	        openId: getApp().globalData.open_id,
	        source_id: this.id,
	        source: "activity",
	      },
	      success: (res) => {
	        if (res.data.code === 200) {
	          console.log(res);
			  this.model.share = this.model.share + 1;
	        }
	      },
	      fail: () => {
	        console.log("连接失败");
	      },
	    });
	  },
	shareActive(){
		let that = this;
		uni.showShareMenu({
		  title: that.model.title,
		  path: "pages/activity/activity_detail?id=" + that.id,
		  success(res) {
		    that.shareRequest();
		  },
		});
	},
    getActivityDeatil() {
      let md5Sign = md5(
        "method=" +
          "activity" +
          "&timestamp=" +
          getApp().globalData.globalTimestamp +
          "&secret=" +
          getApp().globalData.secret
      );
      let url =
        getApp().globalData.shareUrl +
        "api/api.php" +
        "?method=activity&source=activity&action=info_by_id&timestamp=" +
        getApp().globalData.globalTimestamp +
        "&sign=" +
        md5Sign;
      let postData = {
        id: this.id,
		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) {
            let data = res.data.data;
			this.isJoin = data.active ? true : false;
            this.model.title = data.name;
            this.model.read =
              parseInt(data.base_read_count) + parseInt(data.real_read_count);
            this.model.url = getApp().globalData.shareUrl + data.pic_url;
            let arr = ["start_time", "end_time"];
            let ans = [];
            for (const item of arr) {
              let time = this.$options.filters["formDateTime"](data[item]);
              let timeSecond = this.$options.filters["formDateTimeSecond"](
                data[item]
              );
              ans.push(time + " " + timeSecond);
            }
            this.model.date = ans.join(" - ");
            this.model.type = data.type;
            this.model.status = data.status;
            this.model.way = data.sponsor;
            this.model.share =
              parseInt(data.real_repost_count) +
              parseInt(data.base_repost_count);
            if (data.status == 0) {
              if (data.type == 2) {
                this.model.activiteState = "我要参加";
              } else {
                this.model.activiteState = "活动待开始";
              }
            } else if (data.status == 1) {
              this.model.activiteState = "活动进行中";
            } else {
              this.model.activiteState = "活动已结束";
            }
          }
          this.getRich();
        },
        fail: () => {
          console.log("连接失败");
        },
      });
    },
	replaceImg(html){
			  let result = html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match,capture) {
					return '<img src=' + getApp().globalData.shareUrl + capture +' style="max-width:100%;height:auto;display:block;margin:10px 0;"/>';
			  });
			 return result
	},
    getRich() {
      uni.request({
        url:
          getApp().globalData.shareUrl +
          `content/activity/${Math.floor(this.id / 1000)}/${this.id}.html`,
        method: "GET",
        header: {
          "content-type": "application/x-www-form-urlencoded",
        },

        success: (res) => {
          if (res.statusCode === 200) {
           this.textModel.text = this.replaceImg(res.data);
          }
        },
        fail: () => {
          console.log("连接失败");
        },
      });
    },
	subscribeActivity(status){
		console.log(status)
		let that = this;
		uni.requestSubscribeMessage({
		  tmplIds: ['bSg5tUWHE4qWDeyK31GBejogT1uRgkuBD1_n2I5ptAc','T_ORLiW2C_UM6nZiEerYAokltHgHRGxWCid8eElujus'],
		  success (res) {
			  console.log(res)
			  that.signUpActivity()
		  }
		})
	},
    signUpActivity() {
      let md5Sign = md5(
        "method=" +
          "activity" +
          "&timestamp=" +
          getApp().globalData.globalTimestamp +
          "&secret=" +
          getApp().globalData.secret
      );
      let url =
        getApp().globalData.shareUrl +
        "api/api.php" +
        "?method=activity&source=activity&action=active&timestamp=" +
        getApp().globalData.globalTimestamp +
        "&sign=" +
        md5Sign;
      let postData = {
        openId: getApp().globalData.open_id,
        id: this.id,
      };
      uni.request({
        url: url,
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded",
        },
        data: postData,
        success: (res) => {
          if (res.data.code == 200) {
			this.isJoin = true;
			uni.showToast({
				title:'报名成功',
				icon:'none',
				duration:2500
			})
          }
        },
        fail: () => {
          console.log("连接失败");
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  .header {
    display: flex;
    height: 150rpx;
    padding: 20rpx;

    .title-read {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      .title {
        font-weight: 600;
        letter-spacing: 2rpx;
        font-size: 32rpx;
      }
      .read {
        margin-top: 20rpx;
        font-size: 22rpx;
        color: $uni-text-color-grey;
      }
    }
    .header-image {
      height: 100%;
      width: 50%;
      image {
        width: 100%;
        height: 100%;
        border-radius: 10%;
      }
    }
  }
  .active-deatil {
    padding: 20rpx;
    ul {
      padding: 30rpx;
      box-shadow: 0px 4rpx 32rpx rgba(0, 0, 0, 0.1);
      border-radius: 32rpx;
      li {
        margin-bottom: 30rpx;
        list-style: none;
        .name {
          margin-bottom: 10rpx;
          font-size: 30rpx;
          color: $uni-text-color-grey;
        }
        .deatil-content {
          font-size: 27rpx;
        }
      }
    }
  }
  .rich {
    margin-bottom: 150rpx;
    padding: 20rpx;
  }
  .share-box {
    box-sizing: border-box;
    height: 150rpx;
    width: 100%;
    align-items: center;
    justify-content: space-evenly;
    position: fixed;
    bottom: 0;
    display: flex;
    background: #ffffff;
    .share {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50rpx;
      height: 50rpx;
      position: relative;
	  button::after {
		  border: none;
	  }
      image {
        width: 100%;
        height: 100%;
		position: absolute;
      }
      .shareCount {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: -30%;
        right: -30%;
        color: #ffffff;
        height: 30rpx;
        width: 30rpx;
        padding: 3rpx;
        font-size: 16rpx;
        border-radius: 50%;
        background: #fe3637;
      }
    }
    .button {
      height: 100rpx;
      width: 70%;
      display: flex;
      justify-content: center;
      button {
        width: 80%;
        height: 90%;
        border: 1px solid;
        outline: none;
        background: none;
      }
      .start {
        //待开始
        background-color: #00a8ea;
        color: #ffffff;
        border-color: none;
      }
      .begun {
        //已开始
        border-color: #00a8ea;
        color: #00a8ea;
      }
      .ended {
        //已结束
        color: #aaaaaa;
        border-color: #aaaaaa;
      }
      .falseStart {
        color: #70b603;
        border-color: #70b603;
      }
    }
  }
}
</style>