import { commonConstants } from "main_layout/src/main/ets/constants/CommonConstants";
import { common } from "@kit.AbilityKit";
import { FILING_NO, USER_INFO, USER_PROFILE, WXAPPID } from "@ohos/common/src/main/ets/constants/AppConstants";
import { KVStore } from "@ohos/common/src/main/ets/utils/KVStore";
import { StringUtils } from '@ohos/common/src/main/ets/utils/StringUtils';
import { openAppStore,getAppVersion } from '@ohos/common/src/main/ets/utils/AppUtils';
import { MainService } from "main_layout/src/main/ets/viewmodel/MainService";
import { ServiceProfile } from "main_layout/src/main/ets/viewmodel/DataBean";
import { routerLogin } from '@ohos/common/src/main/ets/router/RouterManager';
import { UserInfo, UserProfile } from "@ohos/common/src/main/ets/viewmodel/DataBean";
import { emitter } from "@kit.BasicServicesKit";
import * as wxopensdk from '@tencent/wechat_open_sdk';
import { EVT_USER_INFO } from "@ohos/common/src/main/ets/constants/EventConstants";
import { UpdateTipsDialog } from "@ohos/common/src/main/ets/dialog/UpdateTipsDialog";
import { ToastUtils } from "@ohos/common/src/main/ets/dialog/ToastUtils";
import BuildProfile from "BuildProfile";

@Component
export struct MineComponent {
  @Consume('pageInfos') pageStack: NavPathStack;
  @State appVersion: string = '';
  @State targetVersion: string = '';
  @State userInfo: UserInfo | undefined = undefined;
  @State userProfile: UserProfile | undefined = undefined;
  @State serviceProfile: ServiceProfile | undefined = undefined;
  @State isUpdate: boolean = false;
  @State buildTime: string = '';

  context = getContext(this) as common.UIAbilityContext;

  appUpdateTipsController: CustomDialogController = new CustomDialogController({
    builder: UpdateTipsDialog({
      title: '新版本提示',
      version: 'v' + this.targetVersion,
      desc: this.userProfile?.config?.versionEntity?.description?? '',
      confirmText: '立即更新',
      cancelText: '暂不',
      cancel: () => { console.info('用户点击取消') },
      confirm: () => {
        openAppStore(this.context)
      }
    }),
    alignment: DialogAlignment.Center,          // 居中显示
    customStyle: true,                          // 使用自定义样式，去掉系统默认背景
    autoCancel: true                            // 点击遮罩层可关闭
  })

  updateData(){
    KVStore.getInstance().get(USER_PROFILE, '{}').then(profileJson => {
      this.userProfile = JSON.parse(profileJson) as UserProfile;
      this.targetVersion = this.userProfile?.config?.versionEntity?.version??'0.0.0';

      if(!StringUtils.checkVersionLegal(this.appVersion, this.targetVersion) || !StringUtils.isNewVersionAvailable(this.appVersion, this.targetVersion)){
        this.isUpdate = false;
      }else{
        this.isUpdate = true;
      }
    })
    KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
      this.userInfo = JSON.parse(userJson) as UserInfo;
    })
    MainService.getService().then(res => {
      this.serviceProfile = res;
    });
  }

  aboutToAppear() {
    getAppVersion().then(v => this.appVersion = v);
    this.updateData()
    this.buildTime = BuildProfile.DEBUG?BuildProfile.BUILD_TIME:'';

    // 事件监听
    emitter.on({ eventId: EVT_USER_INFO }, (eventData: emitter.EventData) => {
      const payload = eventData.data;
      if (payload) {
        const result = payload["result"] as boolean;
        if (result === true) {
          //记得一定要延迟更新，否则接口未请求完成
          setTimeout(() => {
            this.updateData()
          }, 1000);
        }
      }
    });
  }

  build() {
    NavDestination() {
      Stack() {
        Image($r('app.media.ic_mine_top_mask_layer')).width('100%')

        Column() {
          //头像部分
          Row() {
            Image(this.userInfo ? this.userInfo.avater : $r('app.media.ic_mine_user_normal'))
              .width(66)
              .height(66)
              .borderRadius(66)
              .alt($r('app.media.ic_mine_user_normal'))

            Column(){
              Text(this.userInfo === undefined ? '游客' : (this.userInfo.name || '大白兔'))
                .width('100%')
                .fontSize(18)
                .fontColor('#FF1A1A1A')
                .textAlign(TextAlign.Start)
                .margin({ top: 8})
                .borderRadius(12)

              Row(){
                Row(){
                  Text(this.userInfo !== undefined ? 'ID:' + this.userInfo?.user_id : '登录体验更多功能哦~')
                    .fontSize(14)
                    .fontColor('#FF767676')
                    .textAlign(TextAlign.Start)
                    .margin({ top: 8})
                    .borderRadius(12)

                  if(this.userInfo !== undefined){
                    Image($r('app.media.ic_mine_copy'))
                      .width('14vp')
                      .height('14vp')
                      .margin({ left: 8, top: 8})
                  }
                }
                .onClick(() =>{
                  //复制ID
                  StringUtils.copyText(this.userInfo?.user_id??'', true);
                })
              }
              .width('100%')
              .align(Alignment.Start)
              .justifyContent(FlexAlign.Start)
            }
            .padding({ left: 10})
            .onClick(() => {
              // 跳转登录
              if(this.userInfo === undefined || this.userInfo.temp === true){
                routerLogin('mine',true)
              }
            })
          }
          .width(commonConstants.rowWidth)
          .height($r('app.float.arrow_item_height'))

          //列表部分
          Column() {
            Row() {
              Image($r('app.media.ic_mine_feedback')).width('19.5vp').height('21.51vp')
              Text('意见反馈')
                .fontSize(16)
                .fontColor('#FF1A1A1A')
                .textAlign(TextAlign.Start)
                .borderRadius(12)
                .fontWeight(1)
                .align(Alignment.Center)
                .padding({ left: 14})
                .layoutWeight(1)

              Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8})
            }
            .width('100%')
            .height('52vp')
            .padding({ left: 14, right: 14})
            .onClick(() => {
              this.pageStack.pushPathByName("FeedbackLayout", null);
            })

            Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

            Row() {
              Image($r('app.media.ic_mine_customer')).width('19.5vp').height('21.51vp')
              Text('在线客服')
                .fontSize(16)
                .fontColor('#FF1A1A1A')
                .textAlign(TextAlign.Start)
                .borderRadius(12)
                .fontWeight(1)
                .align(Alignment.Center)
                .padding({ left: 14})
                .layoutWeight(1)

              Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8})
            }
            .width('100%')
            .height('52vp')
            .padding({ left: 14, right: 14})
            .onClick(() => {
              // 跳转客服
              const context = getContext(this) as common.UIAbilityContext;
              jumpToWeChatCustomerService(context, this.serviceProfile?.corpid??'', this.serviceProfile?.address??'')
            }).visibility(this.userInfo?.show_contact_menu ? Visibility.Visible : Visibility.None)

            Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14}).visibility(this.userInfo?.show_contact_menu ? Visibility.Visible : Visibility.None)

            Row() {
              Image($r('app.media.ic_mine_update')).width('19.5vp').height('21.51vp')
              Text('版本更新')
                .fontSize(16)
                .fontColor('#FF1A1A1A')
                .textAlign(TextAlign.Start)
                .borderRadius(12)
                .fontWeight(1)
                .align(Alignment.Center)
                .padding({ left: 14})
                .layoutWeight(1)

              Row(){

                if(this.isUpdate){
                  Badge({
                    value: '',
                    style: {
                      badgeSize: 8,
                      badgeColor: Color.Red
                    },
                    position: BadgePosition.RightTop
                  }) {
                    Text(BuildProfile.DEBUG?'V' + this.appVersion + '-' + 'debug' + '-' + this.buildTime + ' ' : 'V' + this.appVersion  + ' ')
                      .fontSize(14)
                      .fontColor('#FF767676')
                      .textAlign(TextAlign.Center)
                      .borderRadius(12)
                      .padding({ right: 4, top: 4 })
                  }
                }else{
                  Text(BuildProfile.DEBUG?'V' + this.appVersion + '-' + 'debug' + '-' + this.buildTime : 'V' + this.appVersion)
                    .fontSize(14)
                    .fontColor('#FF767676')
                    .textAlign(TextAlign.Center)
                    .borderRadius(12)
                }

                Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8})
              }
            }
            .width('100%')
            .height('52vp')
            .padding({ left: 14, right: 14})
            .onClick(() => {
              // 更新：1.有更新弹出更新提示确认框 2.没更新则提示无更新
              if(!StringUtils.checkVersionLegal(this.appVersion, this.targetVersion) || !StringUtils.isNewVersionAvailable(this.appVersion, this.targetVersion)){
                ToastUtils.normalToast({
                  message: '已是最新版本',    // 提示文字
                  duration: 2000,           // 显示时长 (ms)，默认 1500
                  bottom: '50%'
                });
              }else{
                this.appUpdateTipsController.open()
              }
            })

            Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

            Row() {
              Image($r('app.media.ic_mine_setting')).width('19.5vp').height('21.51vp')
              Text('设置')
                .fontSize(16)
                .fontColor('#FF1A1A1A')
                .textAlign(TextAlign.Start)
                .borderRadius(12)
                .fontWeight(1)
                .align(Alignment.Center)
                .padding({ left: 14})
                .layoutWeight(1)

              Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8})
            }
            .width('100%')
            .height('52vp')
            .padding({ left: 14, right: 14})
            .onClick(() => {
              this.pageStack.pushPathByName("SettingLayout", null);
            })
          }
          .backgroundColor(Color.White)
          .width('100%')
          .borderRadius(12)
          .margin({ top: 30})
          .padding({ top: 6, bottom: 6})

          Blank()

          //备案号
          Text(FILING_NO)
            .width('100%')
            .height(40) // 【核心修复 2】：高度改为固定值或 wrap_content，不能是 100%
            .fontSize(10)
            .fontColor('#FFAAAAAA')
            .textAlign(TextAlign.Center)
            .margin({ bottom: 86 }) // 留出底部边距，避免贴边
        }
        .height('100%')
        .padding({ left: 16, right: 16})
        .margin({ top: 88 })
      }
      .alignContent(Alignment.TopStart)
      .width('100%')
      .height('100%')
      .backgroundColor('#FFF9F9F9')
    }
    .hideTitleBar(true)
  }
}

/**
 * 跳转微信客服
 * @param context UIAbilityContext 上下文
 * @param corpId 企业ID
 * @param kfUrl 客服URL
 */
function jumpToWeChatCustomerService(context: common.UIAbilityContext, corpId: string, address: string) {
  const wxApi = wxopensdk.WXAPIFactory.createWXAPI(WXAPPID);
  let req = new wxopensdk.OpenCustomerServiceChatReq();
  req.corpId = corpId;
  req.url = address;

  wxApi.sendReq(context as common.UIAbilityContext, req)
}
