<template>
  <view class="container" v-if="showDialog">
    <view class="mask"></view>
    <view class="modal_panel">
      <view class="modal_header">
        <text>用户隐私保护指引</text>
      </view>
      <view class="modal_main">
        <view class="content_wrapper">
          <view>欢迎您使用{{ hosName }}小程序！</view>
          <view>
            为了更好保护您的权益，请您在使用我们的产品服务之前，请仔细阅读我们的<text class="link" @click="toViewArticle" :data-articleid="articleId" data-articletitle="隐私政策协议">《隐私政策协议》</text>，以帮助您更好的了解我们对于您的个人信息的保护情况，尤其是以下条款：
          </view>
          <view>
            1. 我们收集、使用、存储和共享您的个人信息的情况，及您所享有的相关权利；
          </view>
          <view>
            2. 我们的产品请求与个人信息相关的设备权限的相关信息；
          </view>
          <view>
            3. 我们的产品接入的第三方SDK相关信息；
          </view>
          <view>
            4. 我们的限制责任、免责条款。
          </view>
          <view>
            若您对以上内容（包括我们的协议）有任何疑问的，您可以通过电话联系我们；若同意以上内容，请点击“同意”，开始使用我们的产品及服务。
          </view>
          <view>
            相关协议：
          </view>
          <view class="link" @click="toViewArticle" :data-articleid="articleId" data-articletitle="隐私政策协议">
            《隐私政策协议》
          </view>
        </view>
      </view>
      <view class="modal_footer">
        <view class="modal_btn" @click="handleCancel">暂不使用</view>
        <view class="modal_btn modal_btn_confirm" @click="handleConfirm">同意</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, getCurrentInstance } from 'vue';
import { common } from '@/utils';

// 1. 获取当前组件实例代理
const { proxy } = getCurrentInstance() as any;

// 2. Props 定义
const props = withDefaults(defineProps<{
  articleId?: string;
  hosName?: string;
  currentUser?: any;
}>(), {
  articleId: '',
  hosName: '',
  currentUser: () => ({})
});

// 3. State
const showDialog = ref(false);

// 4. Methods
const changeDialogShown = () => {
  showDialog.value = !showDialog.value;
};

/**
 * 判断是否展示隐私协议弹窗
 */
const getPrivacySetting = () => {
  let privacySettingList: any = uni.getStorageSync("PrivacySettingList");
  // 未找到同意配置，展示
  if (common.isEmpty(privacySettingList)) {
    return true;
  }
  // 无就诊人信息，展示
  if (common.isEmpty(props.currentUser) || common.isEmpty(props.currentUser.memberId)) {
    return true;
  }
  
  try {
    privacySettingList = JSON.parse(privacySettingList);
  } catch (e) {
    console.error('PrivacySettingList parse error', e);
    // 解析失败视为未同意
    return true; 
  }

  // 未找到当前就诊人授权记录，展示
  const target = privacySettingList.find((item: any) => item.authMemberId === props.currentUser.memberId);
  if (common.isEmpty(target)) {
    return true;
  }
  return false;
};

/**
 * 记录已授权患者
 */
const setPrivacySetting = (memberId: string) => {
  let privacySettingList: any = uni.getStorageSync("PrivacySettingList");
  
  let list = [];
  if (common.isNotEmpty(privacySettingList)) {
      try {
          list = JSON.parse(privacySettingList);
      } catch (e) {
          list = [];
      }
  }
  
  const resPrivacySettingList = [...list, ...[{ authMemberId: memberId }]];
  uni.setStorageSync("PrivacySettingList", JSON.stringify(resPrivacySettingList));
};

/**
 * 确认按钮
 */
const handleConfirm = () => {
  changeDialogShown();
  if (common.isEmpty(props.currentUser)) {
    return;
  }
  setPrivacySetting(props.currentUser.memberId);
};

/**
 * 取消按钮
 */
const handleCancel = () => {
  common.showToast(`您需要同意隐私政策才能享受我们的服务`, () => {}, 2 * 1000);
};

/**
 * 查看政策
 */
const toViewArticle = (e: any) => {
  // 安全访问 dataset
  const dataset = e.currentTarget?.dataset || {};
  const { articleid: articleId, articletitle: articleTitle } = dataset;
  
  const queryBean = {
    articleId,
    articleTitle,
    hosName: props.hosName // 使用 props.hosName
  };
  const url = `/pages/st1/business/otherService/agreementDetail/agreementDetail`;
  common.goToUrl(url, { skipWay: 'navigateTo', data: `&queryBean=${encodeURIComponent(JSON.stringify(queryBean))}` });
};

// 5. Watchers
// 对应原 observer(value)
watch(() => props.currentUser, (newVal) => {
  showDialog.value = getPrivacySetting();
}, { deep: true, immediate: true });

// 6. Expose
defineExpose({
    changeDialogShown
});
</script>

<style lang="scss" scoped>
.container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

.mask {
  width: inherit;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.6);
}

.modal_panel {
  width: 80%;
  min-height: 200upx;
  max-height: 65%;
  background-color: #fff;
  border-radius: 30upx;
  overflow: hidden;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: stretch;
}

.modal_header {
  text-align: center;
  height: 60upx;
  line-height: 60upx;
  font-size: 36upx;
  padding: 0 20upx;
  margin: 40upx 0 30upx;
}

.modal_main {
  min-height: 200upx;
  overflow: auto;
  margin-bottom: 32upx;
  padding: 0 30upx;
  flex: 1;
}

.modal_main .content_wrapper {
  height: fit-content;
}

.modal_main view {
  line-height: 55upx;
  font-size: 30upx;
}

.modal_footer {
  height: 100upx;
  line-height: 100upx;
  display: flex;
  border-top: 2upx solid #ccc;
}

.modal_btn {
  flex: 1;
  text-align: center;
  font-size: 32upx;
  height: inherit;
  line-height: inherit;
  border-right: 2upx solid #ccc;
}

.modal_btn:last-child {
  border-right: none;
}

.modal_btn_confirm {
  color: var(--dominantColor);
}

.link {
  color: var(--dominantColor);
}
</style>
