<template>
  <view class="info">
    <template v-if="login">
      <view class="card">
        <swiper
          :current="level - 1"
          class="card-swiper"
          duration="500"
          previous-margin="29rpx"
          next-margin="29rpx"
          @change="changeLevel"
        >
          <swiper-item v-for="(item, index) in levelList" :key="index">
            <view
              class="swiper-item"
              :style="{
                backgroundImage: `url(${item.cardBackgroundPic})`,
                backgroundSize: '100%'
              }"
            >
              <view class="swiper-content">
                <view class="user-level-badge-pic">
                  <image
                    :src="item.userLevelBadgePic"
                    mode="widthFix"
                    style="width: 100%; height: auto;"
                  />
                </view>
                <view class="info-content">
                  <view class="info-avator">
                    <image :src="avatar || defaultAvatar" class="avator-img" mode="widthFix" />
                  </view>
                  <view class="info-other">
                    <text
                      class="user-name"
                      :style="{
                        color: `#${item.phoneColor}`
                      }"
                      >{{ name || defaultName }}</text
                    >
                    <view class="level-img-content">
                      <image class="level-img" :src="item.userLevelPic" mode="heightFix" />
                    </view>
                  </view>
                </view>
                <view class="grow-info">
                  <view class="grow-info-content">
                    <template v-if="viewLevel == level">
                      <image
                        class="coin-img"
                        src="https://img.lkbang.net/xcx/memberCenter/level_coin.png"
                      />
                      <view class="grow-detail">
                        <view class="progress-text">
                          <text>{{ item.pointTextName }}</text>
                          <text class="current">{{ item.currentPoint }}</text>
                          <text v-if="item.levelLowPoint">/{{ item.levelLowPoint }}</text>
                          <!-- <text class="iconfont icon-arrow"/> -->
                        </view>
                        <view class="progress-container">
                          <view class="progress" />
                          <view
                            class="actual"
                            :style="{
                              width: calcActualWidth(item.currentPoint, item.levelLowPoint)
                            }"
                          />
                        </view>
                      </view>
                    </template>
                  </view>
                  <!-- #ifdef MP-WEIXIN -->
                  <view class="grow-info-operation">
                    <button class="level-up-btn" @click="linkTo(1)">加速升级</button>
                  </view>
                  <!-- #endif -->
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
      </view>
      <view id="levelBox" class="pointer login">
        <!-- <view class="progress-box canvasBox"> -->
        <canvas
          id="levelArcCanvas"
          canvas-id="levelArcCanvas"
          class="progress-canvas canvasBox"
          type="2d"
        />
        <!-- </view> -->
      </view>
    </template>
    <template v-else>
      <view class="unlogin-card">
        <view class="welcome">
          <view class="icon" />
          <view class="desc">
            <text class="desc-text">您好，</text>
            <text class="desc-text">欢迎来到羊小咩</text>
          </view>
        </view>
        <view class="operation">
          <button class="loginBtn" @click="$emit('handleLogin')">立即登录</button>
        </view>
      </view>
      <view class="pointer unlogin" />
    </template>
  </view>
</template>
<script>
export default {
  props: {
    avatar: {
      type: String,
      default: ""
    },
    name: {
      type: String,
      default: ""
    },
    login: {
      type: Boolean,
      default: false
    },
    level: {
      // 实际的等级
      type: [String, Number],
      default: "" || 0
    },
    viewLevel: {
      // 浏览的等级
      type: [String, Number],
      default: "" || 0
    },
    levelList: {
      // 等级列表
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultName: "", // 默认手机号
      dpr: 0, // 屏幕像素比率
      canvasHeight: 0, // canvas画布高度
      canvansWidth: 0, // canvas画布宽度
      defaultAvatar: "https://img.lkbang.net/xcx/memberCenter/default-avatar.png"
    };
  },
  watch: {
    levelList() {
      this.$nextTick(() => {
        this.draw();
      });
    },
    /* #ifdef MP-BAIDU */
    viewLevel() {
      // 由于百度props传递值有延迟，解决兼容
      this.draw();
    }
    /* #endif */
  },
  created() {
    let phone = uni.getStorageSync("phone") || "";
    if (phone) {
      try {
        let matching = /(\d{3})\d*(\d{4})/;
        this.defaultName = phone.replace(matching, "$1****$2");
      } catch (e) {
        console.log(e);
        this.defaultName = phone;
      }
    }
  },
  methods: {
    calcActualWidth(current, level) {
      if (isNaN(current) || isNaN(level) || level == "0") {
        return "0%";
      } else {
        const percent = (parseFloat(current) / parseFloat(level)).toFixed(4) * 100;
        return percent >= 100 ? "100%" : percent + "%";
      }
    },
    changeLevel(e) {
      this.$emit("updateViewLevel", this.levelList[e.detail.current].level);
      /* #ifdef MP-WEIXIN */
      this.draw(); // 由于百度props有延迟，所以百度在watch中处理，其他平台正常走此逻辑
      /* #endif */
    },
    linkTo(type) {
      // type: 1-> 成长值攻略
      const urlMap = {
        1: "/subPackages/common/member/growStrategy"
      };
      if (urlMap[type]) {
        uni.navigateTo({
          url: urlMap[type]
        });
      }
    },
    async draw() {
      let query = uni.createSelectorQuery();
      /* #ifdef MP-WEIXIN */
      query = query.in(this);
      /* #endif */
      query
        .select("#levelArcCanvas")
        .fields({ node: true, size: true })
        .exec(res => {
          console.log("res.node====================>", res);
          try {
            let ctx = null;
            /* #ifdef MP-BAIDU */
            this.dpr = 1;
            /* #endif */
            /* #ifndef MP-BAIDU */
            this.dpr = uni.getSystemInfoSync().pixelRatio; // 获取屏幕像素比
            /* #endif */

            this.canvansWidth = res[0].width * this.dpr;
            this.canvasHeight = res[0].height * this.dpr;
            /* #ifndef MP-BAIDU */
            const canvas = res[0].node;
            ctx = canvas.getContext("2d");
            canvas.width = this.canvansWidth;
            canvas.height = this.canvasHeight;
            /* #endif */
            /* #ifdef MP-BAIDU */
            ctx = uni.createCanvasContext("levelArcCanvas");
            /* #endif */

            // 绘制等级圆弧
            ctx.clearRect(0, 0, this.canvansWidth, this.canvasHeight);
            this.drawLevelArc(ctx);
            /* #ifdef MP-WEIXIN */
            ctx.scale(this.dpr, this.dpr);
            /* #endif */
            ctx.save();
            /* #ifdef MP-BAIDU */
            ctx.draw();
            /* #endif */
          } catch (e) {
            console.log(e);
            console.info("未登录状态，不进行绘制");
          }
        });
    },
    drawLevelArc(ctx) {
      // 绘制等级弧线
      ctx.beginPath();
      /* #ifdef MP-BAIDU */
      ctx.setStrokeStyle("#F8EBEB");
      ctx.setLineWidth(3 * this.dpr);
      /* #endif */
      /* #ifndef MP-BAIDU */
      ctx.strokeStyle = "#F8EBEB";
      ctx.lineWidth = 3 * this.dpr;
      /* #endif */
      ctx.moveTo(0, 0);
      ctx.quadraticCurveTo(this.canvansWidth / 2, this.canvasHeight, this.canvansWidth, 0);
      ctx.stroke();
      ctx.save();
      // 获取圆弧平分点位集合
      const point = this.createBezierPoints(
        [
          { x: 0, y: 0 },
          {
            x: this.canvansWidth / 2,
            y: this.canvasHeight
          },
          {
            x: this.canvansWidth,
            y: 0
          }
        ],
        this.levelList.length + 1
      );
      point.shift();
      ctx.save();
      this.drawCurLevelArc(ctx, point[this.level - 1], this.level == this.levelList.length);
      ctx.restore();
      this.drawPoint(ctx, point); // 绘制等级点位
    },
    drawPoint(ctx, points) {
      for (let i = 0; i < points.length; i++) {
        // 根据浏览的等级和实际等级设定圆点指示器的大小
        let outsideCircleRadius = (this.viewLevel == i + 1 ? 6 : 5) * this.dpr; // 外圈圆半径
        let insideCircleRadius = (this.viewLevel == i + 1 ? 3 : 2) * this.dpr; // 内圈圆半径
        let outsideCircleColor =
          this.level >= i + 1 || this.viewLevel == i + 1 ? "#FF3243" : "#fff"; // 外圈圆颜色
        let insideCircleColor = this.level >= i + 1 || this.viewLevel == i + 1 ? "#fff" : "#FFBEAE"; // 内圈圆颜色
        let levelNameFontSize = (this.viewLevel == i + 1 ? 14 : 12) * this.dpr; // 等级名称字号大小
        let levelNameOffsetTop = (this.viewLevel == i + 1 ? 22 : 20) * this.dpr; // 等级名称与圆点之间的顶部偏移量
        let levelName = this.levelList[i].levelName; // 等级名称
        let bold = this.viewLevel == i + 1 ? "bold" : "normal"; // 当前浏览的等级文字加粗
        ctx.beginPath();
        /* #ifdef MP-BAIDU */
        ctx.setShadow(0, 1 * this.dpr, 2 * this.dpr, "rgba(255,75,70,0.18)");
        ctx.setFillStyle(outsideCircleColor);
        /* #endif */
        /* #ifndef MP-BAIDU */
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 1 * this.dpr;
        ctx.shadowBlur = 2 * this.dpr;
        ctx.shadowColor = "rgba(255,75,70,0.18)";
        ctx.fillStyle = outsideCircleColor;
        /* #endif */
        ctx.arc(points[i].x, points[i].y, outsideCircleRadius, 0, 2 * Math.PI);
        ctx.fill();
        // 绘制内圈淡红色圆
        ctx.beginPath();
        /* #ifdef MP-BAIDU */
        ctx.setShadow(0, 0, 0);
        ctx.setFillStyle(insideCircleColor);
        /* #endif */
        /* #ifndef MP-BAIDU */
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        ctx.shadowBlur = 0;
        ctx.fillStyle = insideCircleColor;
        /* #endif */
        ctx.arc(points[i].x, points[i].y, insideCircleRadius, 0, 2 * Math.PI);
        ctx.fill();
        // 绘制等级名称
        ctx.beginPath();
        const fillStyle =
          this.level >= this.levelList[i].level || this.viewLevel == i + 1 ? "#FF3643" : "#FFBEAE";
        /* #ifdef MP-BAIDU */
        ctx.setFontSize(levelNameFontSize);
        ctx.setFillStyle(fillStyle);
        /* #endif */
        /* #ifndef MP-BAIDU */
        ctx.font = `${bold} ${levelNameFontSize}px PingFangSC-Regular`;
        ctx.fillStyle = fillStyle;
        /* #endif */
        ctx.fillText(
          levelName,
          points[i].x - ctx.measureText(levelName).width / 2,
          points[i].y + levelNameOffsetTop
        );
        ctx.fill();
      }
    },
    drawCurLevelArc(ctx, point, isHighestLevel) {
      const endPoint = isHighestLevel
        ? { x: this.canvansWidth, y: this.canvansWidth }
        : { x: point.x, y: this.canvasHeight };
      // 先根据当前等级点进行区域裁剪，然后在区域裁剪部分，绘制完整的贝塞尔曲线，裁剪区域内的曲线则是当前等级跨越的曲线
      ctx.beginPath();
      ctx.rect(0, 0, endPoint.x, endPoint.y);
      ctx.clip();
      ctx.beginPath();
      /* #ifndef MP-BAIDU */
      ctx.strokeStyle = "#f00";
      ctx.lineWidth = 2 * this.dpr;
      /* #endif */
      /* #ifdef MP-BAIDU */
      ctx.setStrokeStyle("#f00");
      ctx.setLineWidth(2 * this.dpr);
      /* #endif */
      ctx.moveTo(0, 0);
      ctx.quadraticCurveTo(this.canvansWidth / 2, this.canvasHeight, this.canvansWidth, 0);
      ctx.stroke();
    },
    createBezierPoints(anchorpoints, pointsAmount) {
      let points = [];
      for (let i = 0; i < pointsAmount; i++) {
        let point = this.multiPointBezier(anchorpoints, i / pointsAmount);
        points.push(point);
      }
      return points;
    },
    multiPointBezier(points, t) {
      let len = points.length;
      let x = 0;
      let y = 0;
      let erxiangshi = function(start, end) {
        let cs = 1;
        let bcs = 1;
        while (end > 0) {
          cs *= start;
          bcs *= end;
          start--;
          end--;
        }
        return cs / bcs;
      };
      for (let i = 0; i < len; i++) {
        let point = points[i];
        x += point.x * Math.pow(1 - t, len - 1 - i) * Math.pow(t, i) * erxiangshi(len - 1, i);
        y += point.y * Math.pow(1 - t, len - 1 - i) * Math.pow(t, i) * erxiangshi(len - 1, i);
      }
      return { x, y };
    }
  }
};
</script>
<style scoped lang="scss">
@import "@/style/var.scss";
.info {
  position: relative;
  // height: 392rpx;
  width: 100%;
  margin: $padding-md 0 0;
  .unlogin-card {
    width: 672rpx;
    height: 212rpx;
    margin: 0 auto;
    background-image: url("https://img.lkbang.net/xcx/memberCenter/unlogin_bg.png?a=1");
    background-size: cover;
    display: flex;
    justify-content: space-between;
    padding: 36rpx 64rpx 0 24rpx;
    .welcome {
      display: flex;
      // width: 96rpx;
      height: 96rpx;
      align-items: center;
      .icon {
        width: 96rpx;
        height: 100%;
        background-image: url("https://img.lkbang.net/xcx/memberCenter/member.png");
        background-size: cover;
        margin-right: $padding-xs;
      }
      .desc {
        display: flex;
        flex-direction: column;
        &-text {
          font-weight: $font-weight-bold;
          @include text-size(28);
          color: #814500;
        }
      }
    }
    .operation {
      display: flex;
      height: 96rpx;
      align-items: center;
      .loginBtn {
        width: 144rpx;
        height: 56rpx;
        padding: 0;
        border: 2rpx solid #2d3148;
        border-radius: 38rpx;
        @include text-size(24);
        line-height: 56rpx;
        color: #2d3148;
        text-align: center;
        background: transparent;
        font-weight: $font-weight-bold;
      }
    }
  }
  .card {
    width: 750rpx;
    height: 360rpx;
    margin: 0 auto;
    // padding: 0 39rpx;
    .card-swiper {
      width: 100%;
      height: 100%;
      .swiper-item {
        height: 100%;
        padding: 0 10rpx;
        margin: 0 10rpx;
      }
      .swiper-content {
        position: relative;
        width: 100%;
        height: 100%;
        padding: 36rpx 14rpx;
        .user-level-badge-pic {
          width: 130rpx;
          position: absolute;
          top: 0;
          right: 54rpx;
        }
        .info-content {
          width: 75%;
          height: 98rpx;
          display: flex;
          align-items: center;
          padding-top: $padding-unit;
          .info-avator {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 96rpx;
            height: 96rpx;
            flex-shrink: 0;
            .avator-img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
          .info-other {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            padding-top: $padding-unit;
            .user-name {
              padding-left: $padding-xs;
              font-weight: bold;
              @include text-size(28);
              color: #814500;
            }
            .level-img-content {
              display: flex;
              align-items: flex-end;
              padding-left: $padding-unit;
              margin-top: $padding-unit;
              .level-img {
                height: 56rpx;
                width: auto;
              }
            }
          }
        }
        .grow-info {
          width: 100%;
          height: 78rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-right: 30rpx;
          margin-top: $padding-sm;
          &-content {
            height: 100%;
            display: flex;
            align-items: center;
            .coin-img {
              width: 62rpx;
              height: 78rpx;
              margin-right: 24rpx;
            }
            .grow-detail {
              display: flex;
              flex-direction: column;
              align-items: flex-start;
              .progress-text {
                @include text-size(24);
                color: $black;
                display: flex;
                align-items: center;
                align-content: center;
                .current {
                  margin-left: $padding-unit;
                  font-weight: $font-weight-bold;
                  font-size: 28rpx;
                }
                .iconfont {
                  margin-left: 20rpx;
                  font-size: 18rpx;
                }
              }
              .progress-container {
                position: relative;
                width: 240rpx;
                height: 8rpx;
                .progress {
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  height: 100%;
                  background: $white;
                  border-radius: 6rpx;
                }
                .actual {
                  z-index: 2;
                  position: absolute;
                  top: 0;
                  left: 0;
                  border-radius: 6rpx;
                  height: 8rpx;
                  background-image: linear-gradient(269deg, #ff1900 12%, #ff651f 85%);
                }
              }
            }
          }
          &-operation {
            .level-up-btn {
              width: 144rpx;
              height: 56rpx;
              padding: 0;
              border: 2rpx solid #2d3148;
              border-radius: 38rpx;
              @include text-size(24);
              line-height: 56rpx;
              color: #2d3148;
              text-align: center;
              background: transparent;
              font-weight: $font-weight-bold;
            }
          }
        }
      }
    }
  }
  .pointer {
    position: relative;
    width: 100vw;
    background-image: url("https://img.lkbang.net/xcx/pointer-bg.5deea12c.png");
    background-size: 100%;
    position: absolute;
    bottom: -8rpx;
    left: 0;
    min-height: 88rpx;
    &.unlogin {
      min-height: 68rpx;
    }
    &.login {
      min-height: 136rpx;
      padding-top: 30rpx;
      padding-bottom: 10rpx;
      box-sizing: border-box;
      /* .progress-box {
        width: 100%;
        height: 98rpx;
      } */
      .progress-canvas {
        width: 100%;
        height: 98rpx;
        /* width: 100%;
        height: 100%; */
      }
    }
  }
}
</style>
