<template>
  <div class="authorize-hz" v-if="show" catchtouchmove="ture">
    <div class="mid">
      <div class="authorize-box">
        <div class="bold">{{ title }}</div>
        <div class="other">
          感谢您{{ lbsName }}的信任！请您仔细阅读并充分理解我们最新更新的
          <span
            v-if="!privacyReminder"
            style="color: #627ecf"
            @click="gotoProtocol('privacyPolicy')"
            >《{{ brandInfo.privacyPolicyName }}》</span
          >&nbsp;
          <span
            v-if="!protocolReminder"
            style="color: #627ecf"
            @click="gotoProtocol('protocol')"
            >《{{ brandInfo.protocolName }}》</span
          >。
          新的协议政策将不影响您现有的会员权益，您点击“同意”按钮后，将视为同意本次协议更新。
        </div>
      </div>
      <div class="authorize-footer">
        <button class="disagree_btn" @click="handleDisagree">不同意</button>
        <button class="agree_btn" @click="handleConfirm">同意</button>
      </div>
    </div>
  </div>
</template>

<script>
// const app = getApp();
import {
  kipGetBrandInfo,
  kipLogout,
  kipAgreementCheck,
  kipAgreementSave,
} from '@/utils/api-kip.js';
import MemberCacheTool from '@/utils/member-cache-tool.js';
import KipCacheTool from '@/utils/kip-cache-tool.js';
import CacheTool from '@/utils/cache-tool.js';
import { isKOMiniApp } from '@/utils/utils.js';
const YES = '1';
const NO = '0';
export default {
  name: 'my-protocol-modal',
  props: {
    title: {
      type: String,
      default: '亲爱的会员',
    },
  },
  data() {
    return {
      show: false,
      curMarket: null,
      brandInfo: null,
      cacheKey: '',
      privacyReminder: true,
      protocolReminder: true,
    };
  },
  mounted() {},
  computed: {
    lbsName() {
      if (!this.curMarket) {
        return '';
      }
      const lbsName = this.curMarket?.name || '';
      return lbsName ? `对${lbsName}` : '';
    },
  },
  methods: {
    gotoProtocol(type) {
      const brandId = app.globalData.groupId || uni.getStorageSync('groupId');
      const lbsId = app.globalData.mallid || uni.getStorageSync('mallid');
      uni.navigateTo({
        url: `/pages/protocol/protocol?type=${type}&brandId=${brandId}&lbsId=${lbsId}&noBtn=1`,
      });
    },
    handleConfirm() {
      this.saveAgreementAction(YES);
    },
    handleDisagree() {
      this.saveAgreementAction(NO);
    },
    open() {
      // 获取当前商场
      const { brandInfo, curMarket } = app.globalData;
      const mallid = app.globalData.mallid || uni.getStorageSync('mallid');
      const groupId = app.globalData.groupId || uni.getStorageSync('groupId');
      if (!groupId || !mallid) {
        console.warn('===>groupId活mallid不存在');
        this.show = false;
        return;
      }
      // 判断是否已登录
      const member = uni.getStorageSync('member');
      if (!member) {
        console.warn('===>没有登录');
        this.show = false;
        return;
      }
      // 找到商场信息
      if (curMarket) {
        this.curMarket = curMarket;
      }
      // 找到品牌信息
      if (brandInfo && brandInfo.id === groupId) {
        this.brandInfo = brandInfo;
        this.checkVersion();
      } else {
        // 根据brandId和lbsId请求
        const params = {
          id: groupId,
          lbsId: mallid,
        };
        kipGetBrandInfo(params)
          .then((resp) => {
            const result = resp.data;
            if (result && result.code === '000000') {
              const brandArray = result.data;
              if (brandArray && brandArray.length > 0 && brandArray[0]) {
                const brandInfo = brandArray[0].brand;
                // 拿到商场信息,版本号
                this.brandInfo = brandInfo;
                // 请求接口判断是否需要弹出
                this.checkVersion();
                // this.show = true;
              }
            } else {
              uni.showToast({
                title: result.message,
                duration: 2000,
                icon: 'none',
              });
            }
          })
          .catch((err) => {
            this.show = false;
            console.error(err);
            uni.showToast({
              title: '请求错误',
              duration: 2000,
              icon: 'none',
            });
          });
      }
    },
    logout() {
      const member = uni.getStorageSync('member');
      const openid = member ? member.openid : '';
      kipLogout()
        .then((resp) => {
          uni.hideLoading();
          const result = resp.data;
          if (result && (result.code == '000000' || result.code == '300000')) {
            // 用户不同意协议直接静默退出
            // 清除所有缓存，跳转到首页
            MemberCacheTool.cleanMemberCache(app);
            KipCacheTool.cleanKipCache();
            uni.redirectTo({
              url: '/pages/automatic/automaticIndex',
            });
          } else {
            uni.showToast({
              title: result.message,
              duration: 2000,
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          console.error(err);
          uni.showToast({
            title: '请求错误',
            duration: 2000,
            icon: 'none',
          });
        });
    },
    getKeyByMallid(mallid) {
      if (CacheTool.isShenZhenMallid(mallid)) {
        return 'agreeProtocolSZ';
      } else if (CacheTool.isShenYangMallid(mallid)) {
        return 'agreeProtocolSY';
      }
      return '';
    },
    checkVersion() {
      kipAgreementCheck()
        .then((resp) => {
          const result = resp.data;
          if (result && result.code === '000000') {
            const { agreementStatus, privacyReminder, protocolReminder } =
              result.data || {};
            this.privacyReminder = privacyReminder;
            this.protocolReminder = protocolReminder;
            if (privacyReminder && protocolReminder) {
              this.show = false;
            } else {
              this.show = true;
            }
          } else {
            uni.showToast({
              title: result.message,
              duration: 2000,
              icon: 'none',
            });
          }
        })
        .catch((err) => {
          console.error(err);
          uni.showToast({
            title: '请求错误',
            duration: 2000,
            icon: 'none',
          });
        });
    },
    saveAgreementAction(status) {
      const params = {};
      if (!this.protocolReminder) {
        params.protocolStatus = status;
      }
      if (!this.privacyReminder) {
        params.privacyStatus = status;
      }
      kipAgreementSave(params)
        .then((resp) => {
          const result = resp.data;
          if (!result || result.code !== '000000') {
            uni.showToast({
              title: result.message,
              duration: 2000,
              icon: 'none',
            });
          } else {
            // 如果不同意协议则调用退出接口
            this.show = false;
            if (NO === status) {
              this.logout();
            }
          }
        })
        .catch((err) => {
          console.error(err);
          uni.showToast({
            title: '请求错误',
            duration: 2000,
            icon: 'none',
          });
        });
    },
  },
};
</script>

<style lang="less">
// new
.authorize-hz {
  background: rgba(0, 0, 0, 0.6);
  position: fixed;
  z-index: 998;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;

  .mid {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 588rpx;
    background: #fff;
    border-radius: 17rpx;
    padding: 56rpx 44rpx;

    .authorize-box {
      width: 100%;

      .bold {
        text-align: center;
        color: #333333;
        padding-bottom: 44rpx;
      }

      .other {
        color: #666666;
        line-height: 48rpx;
        font-size: 28rpx;
        color: #666666;
        opacity: 1;
      }

      .checkBox {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        margin-top: 40rpx;

        .popup-a {
          color: #4e99ff;
          text-decoration: underline;
        }
      }
    }

    .authorize-footer {
      display: flex;
      justify-content: space-between;
      color: #ffffff;
      margin-top: 56rpx;

      .disagree_btn {
        width: 176rpx;
        height: 68rpx;
        line-height: 68rpx;
        border: 2rpx solid #b3b3b3;
        border-radius: 34rpx;
        color: #999999;
        font-size: 30rpx;
      }

      .agree_btn {
        width: 286rpx;
        height: 68rpx;
        line-height: 68rpx;
        background: linear-gradient(90deg, #662d91 0%, #1b1464 100%);
        opacity: 0.83;
        border-radius: 34rpx;
        color: #ffffff;
        font-size: 30rpx;
      }

      .disabled {
        background: #999999;
      }
    }
  }
}
</style>
