<template>
  <view class="loginPopup-container">
    <uni-popup ref="popup" type="bottom" :mask-click="false" :safe-area="true" :borderRadius="'10px 10x 10px 10px'">
      <view class="popup-box">
        <view class="head-img"></view>
        <view v-if="showCloseIcon" class="uni-icon uni-icon-closeempty" color="#888" @click="close"></view>
        <view class="popup-content">
          <!-- <view class="title"> 微信账号登录小发同城小程序 </view> -->
          <button class="btn-login" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
            <view>手机号快捷登录</view>
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>
<script>
import { mapState, mapMutations, mapGetters } from "vuex";
export default {
  name: "loginPopup",
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    showCloseIcon: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      tmplIds: [
        "kiDj_hSF_ASwD-Dlgxnypi6IJBQZ12a-hEpd3zZ-Uxc",
        // "Lq6_OHOemtmBoWGrd9zvyJ3ultzXB5metmqPtYeV0pc",
      ],
    };
  },
  computed: {
    ...mapState(["showLoginPopup", "Config"]),
  },
  watch: {
    show: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.open();
          // this.getWXLoginCode();
        }
      },
      // deep: true,
      // immediate: true,
    },
  },
  onUnload() { },
  onHide() {
    this.close();
  },
  methods: {
    ...mapMutations([
      "login",
      "logout",
      "getPlantformInfo",
      "forceUserInfo",
      "getUserInfo",
      "reloadUserResource",
    ]),
    open() {
      this.$refs["popup"].open("bottom");
    },
    close() {
      this.$refs["popup"].close();
      this.$emit("close");
    },
    getWXLoginCode() {
      let that = this;

      wx.login({
        success: (res) => {
          // 登录注册接口
          if (res.code) {
            // 调用服务端登录接口，发送 res.code 到服务器端换取 openId, sessionKey, unionId并存入数据库中
            let params = { code: res.code };

            that.$.request({
              url: that.cf.URL.get_miniapp_open_id,
              data: params,
              success: (data, status, msg, code) => { },
              fail: (err, status) => { },
            });
          } else {
            that.$.showModal({
              content: that.__("授权失败"),
              showCancel: false,
            });
          }
        },
      });
    },

    // code 换 openid sessionkey uid
    async getWxOpenId() {
      return new Promise((resolve, reject) => {
        var that = this;
        wx.login({
          success: (res) => {
            if (res.code) {
              that.$.request({
                url: this.Config.URL.wx.get_wx_openid,
                data: {
                  code: res.code,
                },
                dataType: "json",
                success: function (res) {
                  resolve(res.openid);
                },
              });
            }
          },
        });
      });
    },

    // 授权用户信息
    async getUserprofile() {
      return new Promise((resolve, reject) => {
        wx.getUserInfo({
          success: (res) => {
            resolve(res);
          },
        });
      });
    },

    // 授权手机信息 服务端解析返回手机号 并回调一键登录注册
    async getPhoneNumber(e) {
      var that = this;
      if (e.detail.errMsg == "getPhoneNumber:ok") {
        that.$.request({
          url: this.Config.URL.wx.get_wx_phone_number,
          data: {
            code: e.detail.code,
          },
          success: function (res) {
            that.doWxUserRegisterAndLogin(res.phoneNumber);

            setTimeout(() => {
              that.$.showModal({
                title: "订阅提示",
                content: "是否订阅活动消息通知？",
                cancelText: "暂不订阅",
                confirmText: "立即订阅",
                success: async function (n) {
                  if (n.confirm) {
                    wx.requestSubscribeMessage({
                      tmplIds: that.tmplIds,
                      success(rsp) {
                        let acceptCount = 0;
                        let rejectCount = 0;

                        console.log("success res====", rsp);

                        for (const templateId in rsp) {
                          if (that.tmplIds.includes(templateId)) {
                            const result = rsp[templateId];
                            if (result === "accept") {
                              acceptCount++;
                            } else if (
                              result === "reject" ||
                              result === "ban"
                            ) {
                              rejectCount++;
                            }
                          }
                        }

                        if (acceptCount > 0 && rejectCount === 0) {
                          uni.showToast({
                            title: "订阅成功",
                          });
                        } else if (acceptCount === 0 && rejectCount > 0) {
                          uni.showToast({
                            title: "已拒绝订阅",
                          });
                        } else {
                          uni.showToast({
                            title: "已订阅或拒绝",
                          });
                        }
                      },
                      fail(res) {
                        that.$.showModal({
                          content: `${res.errCode}:${res.errMsg}`,
                          showCancel: false,
                          confirmText: "好的",
                        })
                      },
                    });
                  }
                },
              });
            }, 500);
          },
        });
      } else {
        that.$.confirm(that.__("授权失败"));
      }
    },

    // 一键登录注册
    async doWxUserRegisterAndLogin(phoneNumber) {
      const openId = await this.getWxOpenId();
      const {
        userInfo: { nickName, avatarUrl },
      } = await this.getUserprofile();
      const that = this;

      this.$.request({
        url: this.Config.URL.wx.doWxUserRegisterAndLogin,
        data: {
          nickName,
          avatarUrl,
          phoneNumber,
          openId,
        },
        method: "POST",
        header: {
          "Content-Type": "application/json;charset=utf-8",
        },
        dataType: "json",
        success: function (data, status, msg, code) {
          if (status != 200) {
            that.$.confirm(that.__(msg || "登录失败，请重试！"));
            return;
          }

          that.loginSuccess(data);
        },
      });
    },

    // 成功登录回调
    loginSuccess(data) {
      const that = this;

      that.$.setStorageSync("uid", data.user_id);
      that.$.setStorageSync("ukey", data.key);

      // #ifdef H5
      $cookies.set("uid", data.user_id);
      $cookies.set("ukey", data.key);
      // #endif

      that.$.request({
        url: that.Config.URL.user.overview,
        success: function (results, status, msg, code) {
          that.login(data);
          that.reloadUserResource(function (user_info) {
            that.setData({
              UserInfo: user_info,
            });
          });
		// 核心：登录成功后，向父组件发送回调通知
		  that.$emit("loginSuccess"); // 新增这行，通知父组件
          that.close();
        },
		fail: function () {
		      // 即使获取用户详情失败，也触发回调（避免登录后无响应）
		      that.$emit("loginSuccess");
		      that.close();
		      that.$.confirm("登录成功，但获取用户信息失败，请重试");
		    },
      });
    },
  },
};
</script>
<style lang="scss">
.loginPopup-container {
  background: #fff;

  .popup-box {
    // padding: 40rpx;
    position: relative;
    width: 100%;

    border-top-left-radius: 32rpx;
    border-top-right-radius: 32rpx;

    .head-img {
      width: 100%;
      height: 190px;
      background-image: url("https://media-mall-prod-1259811287.cos.ap-guangzhou.myqcloud.com/static/xcxfile/appicon/login-bg.png");
      background-size: 100% 100%;
    }

    .uni-icon-closeempty {
      position: absolute;
      right: 10px;
      top: 10px;
    }

    .popup-content {
      padding: 40rpx;
      width: 90%;
      height: 400rpx;
      background: #fff;
    }

    .title {
      font-size: 18px;
      text-align: center;
      font-weight: 700;
      color: #000;
    }

    .btn-login {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 40rpx;
      margin-top: 80rpx;
      height: 100rpx;
      font-size: 32rpx;
      background: #0787f4;
      border-radius: 40px;
      color: #fff;

      .icon-weixin {
        font-size: 48rpx;
        margin-right: 16rpx;
      }
    }
  }
}
</style>
