//
//  YHMySettingViewController.swift
//  galaxy
//
//  Created by edy on 2024/2/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SnapKit

class YHMySettingViewController: YHBaseViewController, ConstraintRelatableTarget {
    
    let viewModel: YHLoginViewModel = YHLoginViewModel()
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.register(YHMySettingCell.self, forCellReuseIdentifier: YHMySettingCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var logoutBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("退出登录".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(UIColor(hexString: "#313131"), for: .normal)
        btn.backgroundColor = .contentBkgColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didLogoutBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var registerBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("注销账号".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 13)
        btn.setTitleColor(UIColor.mainTextColor30, for: .normal)
        btn.backgroundColor = .clear
        btn.addTarget(self, action: #selector(clickRegBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var versionLabel: UILabel = {
        let btn = UILabel()
        btn.text = "版本号：V0.1.8测试服"
        btn.textColor = UIColor(hex: 0x949DB5, alpha: 1.0)
        btn.font = UIFont.PFSC_R(ofSize: 13)
        btn.textAlignment = .center
        return btn
    }()
    
    lazy var items: [PersonalModuleItem] = {
        // 是否需要展示版本更新红点
        let isShowVersionRedPoint = YHAppVersionManager.shared.needShowRedPointOfSuggestVersionUpdate()
        
        let myVer = UIDevice.appVersion() + "_" + UIDevice.appBuild()
#if DEBUG
        return [PersonalModuleItem(title: "通知设置".local, type: .notifySettings),
                PersonalModuleItem(title: "权限设置".local, type: .permissionSettings),
                PersonalModuleItem(title: "播放设置".local, type: .playSettings),
                PersonalModuleItem(title: "用户条款".local, type: .userItems),
                PersonalModuleItem(title: "隐私协议".local, type: .privaceAgreement),
                PersonalModuleItem(title: "设备相关".local, type: .deviceInfo),
                PersonalModuleItem(title: "版本 \(myVer)", isShowRedPoint: isShowVersionRedPoint, type: .version) ]
        
#elseif TESTENV
        return [PersonalModuleItem(title: "通知设置".local, type: .notifySettings),
                PersonalModuleItem(title: "权限设置".local, type: .permissionSettings),
                PersonalModuleItem(title: "播放设置".local, type: .playSettings),
                PersonalModuleItem(title: "用户条款".local, type: .userItems),
                PersonalModuleItem(title: "隐私协议".local, type: .privaceAgreement),
                PersonalModuleItem(title: "设备相关".local, type: .deviceInfo),
                PersonalModuleItem(title: "版本 \(myVer)", isShowRedPoint: isShowVersionRedPoint, type: .version)]
#elseif UATENV
        return [PersonalModuleItem(title: "通知设置".local, type: .notifySettings),
                PersonalModuleItem(title: "权限设置".local, type: .permissionSettings),
                PersonalModuleItem(title: "播放设置".local, type: .playSettings),
                PersonalModuleItem(title: "用户条款".local, type: .userItems),
                PersonalModuleItem(title: "隐私协议".local, type: .privaceAgreement),
                PersonalModuleItem(title: "版本 \(myVer)", isShowRedPoint: isShowVersionRedPoint, type: .version)]
#else
        return [PersonalModuleItem(title: "通知设置".local, type: .notifySettings),
                PersonalModuleItem(title: "权限设置".local, type: .permissionSettings),
                PersonalModuleItem(title: "播放设置".local, type: .playSettings),
                PersonalModuleItem(title: "用户条款".local, type: .userItems),
                PersonalModuleItem(title: "隐私协议".local, type: .privaceAgreement),
                PersonalModuleItem(title: "版本 \(myVer)", isShowRedPoint: isShowVersionRedPoint, type: .version)]
#endif
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initView()
    }
    
    func initView() {
        
        self.gk_navTitle = "设置".local
        self.view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(logoutBtn)
        view.addSubview(versionLabel)
        view.addSubview(registerBtn)
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(versionLabel.snp.top).offset(-30)
        }
        
        versionLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(18)
            make.bottom.equalTo(logoutBtn.snp.top).offset(-kMargin)
        }
        
        logoutBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(48.0)
            make.bottom.equalTo(registerBtn.snp.top).offset(-14)
        }
        
        registerBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-54)
            make.height.equalTo(18)
            make.width.equalTo(52)
        }
        
#if DEBUG
        let version = "版本号：V" + UIDevice.appVersion() + "_" + UIDevice.appBuild() + "开发服"
        versionLabel.text = version
#elseif TESTENV
        let version = "版本号：V" + UIDevice.appVersion() + "_" + UIDevice.appBuild() + "测试服"
        versionLabel.text = version
#elseif UATENV
        let version = "版本号：V" + UIDevice.appVersion() + "_" + UIDevice.appBuild() + "Uat服"
        versionLabel.text = version
        versionLabel.isHidden = true
#else
        let version = "版本号：V" + UIDevice.appVersion() + "_" + UIDevice.appBuild() + "正式服"
        versionLabel.text = version
        versionLabel.isHidden = true
#endif
    }
    
    @objc func didLogoutBtnClicked() {
        YHCommonAlertView.show("", "您确定要退出登录吗？", "取消", "确定", fullGuestureEnable: false) {

        } callBack: {
            self.logout()
        }
    }
    
    @objc func logout() {
        YHHUD.show(.progress(message: "退出登录中..."))
        self.viewModel.logout {
            [weak self] success, error in
            guard let self = self else { return }
            YHHUD.hide()
            if success {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "退出成功")
                    YHAliYunLogManager.shared.addModuleName(.networkDataType, remark: "logout")
                    YHLoginManager.shared.clearUserInfo()
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
                    // 发送清空所有未读消息通知
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
                return
            }
            
            var msg = "退出失败"
            if let error = error, !error.errorMsg.isEmpty {
                msg = error.errorMsg
            }
            YHHUD.flash(message: msg)
        }
    }
    
    // 点击注销按钮
    @objc func clickRegBtn() {
        YHCommonAlertView.show("风险提示", "您正在进行账号注销操作，一旦完成注销，您将无法再登录\"银河港生活\"APP，并因此无法在APP中继续现有的服务流程。\n \n真心希望您能留下来，继续享受银河港生活为您提供的精彩服务。", "取消", "坚持注销") {
            
            self.unRegisterAPPOp()
        }
    }
    
    private func unRegisterAPPOp() {
        YHHUD.show(.progress(message: "APP注销中..."))
        self.viewModel.unrigisterApp {
            [weak self] success, error in
            guard let self = self else { return }
            YHHUD.hide()
            if success {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "注销成功")
                    YHLoginManager.shared.clearUserInfo()
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didLogoutSuccessNotifiction, object: nil)
                    // 发送清空所有未读消息通知
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didMarkAllMessagesReadedNotifiction, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
                return
            }
            
            var msg = "注销失败,请重试"
            if let error = error, !error.errorMsg.isEmpty {
                msg = error.errorMsg
            }
            YHHUD.flash(message: msg)
        }
    }
}

extension YHMySettingViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMySettingCell.cellReuseIdentifier, for: indexPath) as? YHMySettingCell else { return UITableViewCell() }

        if 0 <= indexPath.row && indexPath.row < items.count {
            let item: PersonalModuleItem = items[indexPath.row]
            cell.titleLabel.text = item.title
            cell.isShowRedPoint = false
            cell.detailLabel.text = ""
            
            if item.type == .version {
                cell.isShowRedPoint = item.isShowRedPoint
                var detailText = "已是最新版"
                var detailColor = UIColor.mainTextColor30
                if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.suggest_updating == true {
                    detailText = "去更新"
                    detailColor = UIColor.brandMainColor
                }
                cell.detailLabel.text = detailText
                cell.detailLabel.textColor = detailColor
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 53.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let item = items[indexPath.row]
            
            if item.type == .notifySettings {
                let vc = YHMyNotifySettingVC()
                self.navigationController?.pushViewController(vc)
                
            } else if item.type == .permissionSettings {
                let vc = YHMyPermissionSettingVC()
                self.navigationController?.pushViewController(vc)
                
            } else if item.type == .playSettings {
                let vc = YHVideoPlaySettingVC()
                self.navigationController?.pushViewController(vc)
                
            } else if item.type == .userItems {
                // 用户条款
                let vc = YHWebViewViewController()
                vc.url = YHBaseUrlManager.shared.curUserItemsUrl()
                vc.navTitle = "银河港生活用户条款"
                UIViewController.current?.navigationController?.pushViewController(vc)
                
            } else if item.type == .privaceAgreement {
                // 隐私政策
                let vc = YHWebViewViewController()
                vc.url = YHBaseUrlManager.shared.curPrivacyAgreementUrl()
                vc.navTitle = "银河港生活隐私协议"
                UIViewController.current?.navigationController?.pushViewController(vc)
                
            } else if item.type == .deviceInfo {
                let vc = YHDeviceInfoViewController()
                self.navigationController?.pushViewController(vc)
                
            } else if item.type == .version {
                
                item.isShowRedPoint = false
                self.tableView.reloadData()
                
                if let configModel = YHConfigManager.shared.reqVM.configModel, configModel.suggest_updating == true {
                    YHAppVersionManager.shared.saveTodayShowSuggestVersionUpdateRedPoint()
                    YHAppVersionManager.shared.goToAppStore()
                }
            }
        }
    }
}
