<template>
  <view class="prayers-list" @click="handleclick">
    <u-navbar
      title="南华云灯会"
      leftIconColor="#fff"
      :titleStyle="{ color: '#fff' }"
      bgColor="transparent"
      :autoBack="true"
    >
    </u-navbar>
    <!-- <u-navbar title="剑未配妥，出门已是江湖" @click-left="onClickBack" @click-right="onClickRight"></u-navbar> -->
    <view class="allList">
      <view class="list">
        <scroll-view
          scroll-x="true"
          class="content-scroll swiper"
          scroll-with-animation
          :scroll-left="scrollLeft"
        >
          <view
            v-for="(item, index) in list"
            :key="index"
            class="scroll-item list"
            :class="
              current == index
                ? `active index${index} ${curIndex == index ? 'fang' : ''}`
                : `index${index}`
            "
            @click="changeTitle(index)"
          >
            <view class="activeItem" v-if="curIndex == index">
              <view class="activetext" v-for="(items, a) in item.list" :key="a">
                {{ items }}
              </view>
            </view>
            <view class="item-text item" v-else>{{ item.name }}</view>
            <view class="source">
              <text style="color: #9c9590">来源</text>
              <text>小阿飞</text>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="tips">
        请选择祈愿类型
        <view v-if="curIndex" class="downButtom flex justify-center">
          <view class="downButtomItem">返回我的祈愿</view>
        </view>
        <view v-else class="downButtom flex justify-center">
          <view class="downButtomItem">祈愿地图</view>
          <view class="downButtomItem" @click="handleShare">分享</view>
        </view>
      </view>
      <view class="img_signal" v-if="!show"></view>

      <u-popup
        :show="shareShow"
        mode="center"
        bgColor="transparent"
        round="10"
        @close="close"
      >
        <view class="mySharepopup planel" ref="addImage" id="capture">
          <!-- <view class="close" @click="close">
            <u--image
              width="42px"
              height="42px"
              src="/static/img/icon_cancel@2x.png"
            ></u--image>
          </view> -->
          <view class="shareItem answer_draw_canvas">
            <view class="activeItem answer_draw_canvas">
              <view
                class="activetext answer_draw_canvas"
                v-for="(items, a) in shareData.list"
                :key="a"
              >
                {{ items }}
              </view>
            </view>
            <!-- <view class="share-page-box" id="box" v-if="shareShow"
              :style="{ width: '180px', height: '600px' }">
              <wxml-to-canvas class="widget" :width="canvasWidth" :height="canvasHeight"></wxml-to-canvas>
            </view> -->
            <view class="shareRight answer_draw_canvas">
              <view class="close" @click="close">
                <u--image
                  width="42px"
                  height="42px"
                  src="/static/img/icon_cancel@2x.png"
                ></u--image>
              </view>
              <view class="downBut" @click="handleDown">
                <view class="img">
                  <view>
                    <u--image
                      width="36px"
                      height="36px"
                      src="https://4dscene.4dage.com/new4dkk/deng/static/img/icon_download@2x.png"
                    ></u--image>
                  </view>
                </view>
              </view>
              <view class="downText" @click="handleDown">下载图片</view>
            </view>
            <view class="codeImg1 answer_draw_canvas">
              <QiyanQrcode
                :size="72"
                background="#fff"
                @click="title1 = '1.现在时间戳：' + Date.now()"
                :text="title1"
              ></QiyanQrcode>
            </view>
            <view class="codeImg2 answer_draw_canvas">
              <QiyanQrcode
                :size="72"
                background="#fff"
                @click="title1 = '1.现在时间戳：' + Date.now()"
                :text="title1"
              ></QiyanQrcode>
            </view>
          </view>
        </view>
      </u-popup>
      <canvas
      canvas-id="answerCanvas"
      class="answerCanvas"
      :style="'width:' + canvasWidth + 'px;height:' + canvasHeight + 'px;'"
    ></canvas>
    </view>
  </view>
</template>

<script>
// import uNavbar from "uview-ui/components/u-navbar/u-navbar.vue";
import { wxml, style } from './DomData';
import QiyanQrcode from "@/components/qiyan-qrcode/qiyan-qrcode.vue";
import Wxml2Canvas from "wxml2canvas";
import html2canvas from "html2canvas";
export default {
  components: {
    // uNavbar
    QiyanQrcode,
  },
  data() {
    return {
      active: "婚姻祈愿1",
      title1: "1.现在时间戳：" + Date.now(),
      show: false,
      shareShow: false,
      scrollLeft: 0, // 横向滚动条位置
      current: 2,
      curIndex: null,
      province: "请选择",
      provinceShow: false,
      shareData: {},
      list: [
        {
          name: "学业祈愿1",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
        {
          name: "学业祈愿2",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
        {
          name: "学业祈愿3",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
        {
          name: "学业祈愿4",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
        {
          name: "学业祈愿5",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
        {
          name: "学业祈愿6",
          list: ["知识的殿堂中闪耀属于你的光芒。", "愿你学业精进，成绩辉煌，"],
        },
      ],
      canvasWidth: 180, // 默认canvas宽高
      canvasHeight: 700,
      screenWidth: null, // 设备宽度
      screenHeight: null, // 设备高度
      // name: '',
      // pic: '',
      // chapter1: '',
      // chapter2: '',
      widget: null,
      msg: '加载中，请稍等...', // 提示语
    };
  },
  mounted() {
    // 获取标题区域宽度，和每个子元素节点的宽度
    this.getScrollW();
  },
  onLoad() {
  },
  methods: {
    renderInit(){
    // 获取设备信息
      wx.getSystemInfo({
        success: (res) => {
          console.log("屏幕", res);
          this.screenWidth = 180;
          this.canvasWidth = this.screenWidth;
          this.canvasHeight = 600;
          console.log("海报高度：", this.canvasHeight);

          this.show = true;
          // 数字容器宽度 动态设置
          setTimeout(() => {
            wx.showLoading({ title: "海报加载中..." });
            this.widget = this.selectComponent(".widget");
            this.renderToCanvas();
          }, 1000);
        },
      });
    },
    // 获取标题区域宽度，和每个子元素节点的宽度以及元素距离左边栏的距离
    getScrollW() {
      const query = uni.createSelectorQuery().in(this);

      query
        .select(".content-scroll")
        .boundingClientRect((data) => {
          // 拿到 scroll-view 组件宽度
          this.contentScrollW = data.width;
        })
        .exec();

      query
        .selectAll(".scroll-item")
        .boundingClientRect((data) => {
          let dataLen = data.length;
          for (let i = 0; i < dataLen; i++) {
            //  scroll-view 子元素组件距离左边栏的距离
            this.list[i].left = data[i].left;
            //  scroll-view 子元素组件宽度
            this.list[i].width = data[i].width;
          }
        })
        .exec();
    },

    // 选择标题
    changeTitle(index) {
      if (index == this.current && this.curIndex != index) {
        this.curIndex = index;
      } else {
        this.curIndex = null;
      }
      this.current = index;
      console.log("changeTitle", index);
      this.scrollLeft = (index - 1) * 118;
    },
    handleHome() {
      console.log("开启云上观灯", uni);
      uni.$u.route("/pages/home/home");
    },
    handleclick() {
      this.show = true;
    },
    handleShare() {
      console.log("handleShare");
      this.shareShow = true;
      this.shareData = this.list[this.current];
      setTimeout(()=>{
        // this.renderInit();
      },500)
    },
    close() {
      this.shareShow = false;
      console.log("handleShare", this.shareShow);
    },
    changeswiper(e) {
      // 得加上这个方法！！！
      this.currentswiper = e.detail.current;
    },
    confirm(val) {
      console.log("confirm", val);
      this.province = val.value[0];
      this.provinceShow = false;
    },
    handleDown() {
      // this.renderInit();
      // this.extraImage()
      this.draw();
    },
    // wxml 转 canvas
    renderToCanvas() {
      console.log('canvasStyle.widget', this.shareData)
      const _wxml = wxml(this.shareData);
      console.log('this.widget', this.widget)
      const _style = style(this.screenWidth, this.canvasWidth, this.canvasHeight) //this.canvasHeight
      const p1 = this.widget.renderToCanvas({ wxml: _wxml, style: _style })
      console.log('renderToCanvas', p1)
      p1.then((res) => {
        console.log('海报生成成功', res);
        wx.hideLoading()
      }).catch((err) => {
        console.log('生成失败', err)
      })
    },
    // 保存到朋友圈
    extraImage() {
      if (!this.show) {
        wx.showToast({ title: '海报生成失败，无法分享到朋友圈', icon: 'none' })
        return
      }
      wx.showLoading({ title: '海报生成中...' })
      const p2 = this.widget.canvasToTempFilePath({ fileType:'jpg', quality :0.5})
      let that = this;
      p2.then(result => {
        let path = result.tempFilePath
        wx.getSetting({
          success: res => {
            wx.hideLoading()
            // 非初始化且未授权的情况，需要再次弹窗提示授权
            if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting['scope.writePhotosAlbum'] != true) {
              wx.showModal({
                title: '是否授权相册权限',
                content: '需要获取相册权限，请确认授权，否则无法使用相关功能',
                success: res => {
                  if (res.confirm) {
                    wx.openSetting({
                      success: dataAu => {
                        if (dataAu.authSetting["scope.writePhotosAlbum"] == true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'none',
                            duration: 1000
                          });
                          that.saveIMg(path);
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          });
                        }
                      }
                    });
                  }
                }
              });
            } else {
              // 初始化且未授权，系统默认会弹窗提示授权
              // 非初始化且已授权，也会进入这里
              that.saveIMg(path);
            }
          }
        });
      })
    },
    
    draw() {
      let that = this;
      //创建wxml2canvas对象
      let drawImage = new Wxml2Canvas(
        {
          element: "answerCanvas", // canvas节点的id,
          obj: that, // 在组件中使用时，需要传入当前组件的this
          width: 180, // 宽 自定义
          height: 700, // 高 自定义
          background: "#fff", // 默认背景色 设置背景色
          progress(percent) {
            // 绘制进度
            console.log(percent);
          },
          finish(url) {
            uni.saveImageToPhotosAlbum({
              filePath: url,
              success() {
                uni.hideLoading();
              },
              fail() {
                uni.hideLoading();
              },
            });
          },
          error(res) {
            console.log(res);
            // uni.hideLoading()
            // 画失败的原因
          },
        },
        this
      );
      //传入数据，画制canvas图片
      let data = {
        //直接获取wxml数据
        list: [
          {
            type: "wxml",
            class: ".planel .answer_draw_canvas", // answer_canvas这边为要绘制的wxml元素跟元素类名， answer_draw_canvas要绘制的元素的类名（所有要绘制的元素都要添加该类名）
            limit: ".mySharepopup", // 这边为要绘制的wxml元素跟元素类名,最外面的元素
            x: 0,
            y: 0,
          },
        ],
      };
      drawImage.draw(data, that);
    },
    // 保存到相册
    async saveIMg(tempFilePath) {
      wx.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: async (res) => {
          wx.showModal({
            content: '图片已保存，分享给好友吧！',
            showCancel: false,
            confirmText: '好的',
            confirmColor: '#333',
            success: function (res) {
              wx.navigateBack({
                //返回
                delta: 1
              });
            },
            fail: function (res) {
              console.log('res', res);
            }
          });
        },
 
        fail: function (res) {
          wx.showToast({
            title: '您取消了授权',
            icon: 'none',
            duration: 2000
          })
        }
      });
    },
  },
};
</script>
// <script lang="renderjs" module="canvasImage">
// import html2canvas from 'html2canvas'
// export default {
//   methods: {
//     // 生成图片需要调用的方法
//     handleDown(){
//       // const query = uni.createSelectorQuery().in(this);
//       const dom = this.$refs.addImage;//query.select('#capture'); // 需要生成图片内容的 dom 节点
//       html2canvas(dom).then(canvas => {
//       this.imgs= canvas.toDataURL()    //base64字符串   放到图片标签上
//       });
//     }
//   }
// }
// </script>

<style lang="scss" scoped>
.prayers-list {
  background: rgba(32, 21, 10, 0.7);
  border-radius: 0px 0px 0px 0px;
  height: 100vh;
  padding-top: 100px;
  .img_signal {
    width: 76px;
    height: 106px;
    background: url(https://4dscene.4dage.com/new4dkk/deng/static/img/img_signal@2x.png)
      100% 100% no-repeat;
    background-size: cover;
    position: absolute;
    right: 50px;
    bottom: 30px;
    animation: handleAni 1s linear infinite;
    transition: all 1s;
  }
  .mySharepopup {
    // width: 330px;
    // height: 537px;
    padding: 19px 17px 0px 17px;
    .close {
      position: absolute;
      right: -24px;
      top: -20px;
      width: 42px;
      height: 42px;
    }
    .shareItem {
      width: 150px;
      height: calc(100% - 512px);
      padding: 160px 0px;
      display: inline-block;
      background-size: 100% 100%;
      font-size: 12px;
      color: #303030;
      line-height: 18px;
      display: flex;
      writing-mode: vertical-lr;
      text-align: left;
      justify-content: center;
      flex-direction: column;
      background: url(https://4dscene.4dage.com/new4dkk/deng/static/img/img_label@2x.png)
        100% 100% no-repeat;
      background-size: contain;
      position: relative;
      top: 44px;
      font-weight: 400;
      font-size: 16px;
      color: #303030;
      line-height: 24px;
      .activetext {
        margin: 0 9px;
      }
    }
    .shareRight {
      position: absolute;
      right: -50px;
      .img {
      }
    }
    .downBut {
      position: absolute;
      right: -20px;
      bottom: -70px;
    }
    .downText {
      position: absolute;
      right: -34px;
      bottom: -90px;
      font-weight: 400;
      font-size: 16px;
      color: #ffffff;
      line-height: 19px;
      width: 64px;
      writing-mode: rl;
    }
    .codeImg1 {
      position: absolute;
      right: -90px;
      bottom: 50px;
      padding: 3px;
      background: #fff;
    }
    .codeImg2 {
      position: absolute;
      right: -90px;
      bottom: 150px;
      padding: 3px;
      background: #fff;
    }
    .qrcode {
      position: absolute;
      right: -50px;
      .codeImg {
        width: 100%;
      }
    }
  }
  .tips {
    width: 100%;
    text-align: center;
    margin-top: 27px;
    color: #fff;
    font-size: 14px;
    line-height: 21px;

    .downButtom {
      padding-top: 20px;
      .downButtomItem {
        width: 140px;
        height: 42px;
        background: url(https://4dscene.4dage.com/new4dkk/deng/static/img/btn01@2x.png)
          100% 100% no-repeat;
        background-size: cover;
        font-weight: 400;
        font-size: 16px;
        color: #ffffff;
        line-height: 19px;
        font-style: normal;
        margin: 0 5px;
        line-height: 42px;
        text-align: center;
      }
    }
  }
  .list {
    height: 555px;
    width: 100%;
    // margin-top: 50rpx;
    box-sizing: border-box;
    .content-scroll {
      height: 500px;
      white-space: nowrap;
      display: flex;
      text-align: center;
      justify-content: center;
      flex-direction: column;
      .scroll-item {
        height: 500px;
        width: 118px;
        padding: 0 20rpx;
        display: inline-block;
        text-align: center;
        position: relative;
        transition: all 0.3s;
        .source {
          display: none;
          font-weight: 400;
          font-size: 12px;
          color: #fff9b1;
          line-height: 18px;
          writing-mode: vertical-lr;
          position: absolute;
          bottom: 23%;
          right: -10px;
        }
        .item-text {
          // transform: rotateY(180deg);
          font-size: 30rpx;
          line-height: 100rpx;
          position: absolute;
          top: calc(50% - 133px);
          left: calc(50% - 34px);
          &.active {
            color: #1468ff;
          }
        }
        .activeItem {
        }
      }
      .fang {
        transform: rotateY(180deg);
        transition: all 0.5s;
        .item-text {
          transform: rotateY(0deg);
        }
        .source {
          display: block;
          transform: rotateY(180deg);
        }
      }
      .active {
        .item-text {
          top: calc(50% - 226px);
          left: calc(50% - 50px);
        }
        .item {
          width: 50px;
          height: 453px;
          background-size: 100% 100%;
          font-size: 27px;
          color: #8c4042;
          line-height: 41px;
        }
        .activeItem {
          transform: rotateY(180deg);
          width: 100px;
          height: 263px;
          padding: 95px 0px;
          display: inline-block;
          background-size: 100% 100%;
          font-size: 12px;
          color: #303030;
          line-height: 18px;
          display: flex;
          writing-mode: vertical-lr;
          text-align: left;
          justify-content: center;
          flex-direction: column;
          background: url(https://4dscene.4dage.com/new4dkk/deng/static/img/img_label@2x.png)
            100% 100% no-repeat;
          background-size: 100% 100%;
          position: relative;
          top: 44px;
        }
      }
    }
    .swiper {
      padding: 0 10px;
      // .listitem {
      //   text-align: center;
      //   padding: 0 20px;
      .item {
        margin: 20px auto;
        width: 18px;
        height: 267px;
        background: url(https://4dscene.4dage.com/new4dkk/deng/static/img/label@2x.png)
          100% 100% no-repeat;
        background-size: cover;
        writing-mode: tb-rl;
        text-align: center;
        padding: 0 25px;
        position: relative;
        display: flex;
        writing-mode: vertical-lr;
        text-align: center;
        justify-content: center;
        flex-direction: column;
      }
      // .active {
      //   &:after {
      //     content: "";
      //     box-shadow: 0px 2px 18px 11px #fff86c,
      //       inset 0px 1px 1px 0px rgba(177, 156, 125, 0.7);
      //     position: absolute;
      //     height: 71%;
      //     width: 80%;
      //     top: 32px;
      //     left: 8px;
      //     border-radius: 25px;
      //     z-index: -1;
      //   }
      // }
      // }
    }
  }
}

@keyframes handleAni {
  from {
    right: 50px;
  }
  to {
    right: 30px;
  }
}
</style>
