//
//  YHPlanTestViewController.swift
//  galaxy
//
//  Created by Dufet on 2025/3/25.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView

class YHPlanTestViewController: YHBaseViewController {

    let viewModel = YHPlanViewModel()
    
    var shareUrl: String = ""
    var pdfCreateUrl: String = ""
    var pdfDownloadUrl: String = ""
    
    var infoArr: [String] = ["", "", "", "", "", ""]
    var analyzeArr: [YHPlanAnalyzeModel] = [YHPlanAnalyzeModel(),
                                            YHPlanAnalyzeModel(),
                                            YHPlanAnalyzeModel(),
                                            YHPlanAnalyzeModel()]
    var policyArr: [YHPlanCaseModel] = []
    var caseArr: [YHPlanCaseModel] = []
    
    let headerViewHeight = 146.0
    let topScrollHeight = 146.0-44.0
    var contentOffSetChangeBig = false
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.bounces = false
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedSectionHeaderHeight = 1.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(YHPlanAnalyzeInfoCell.self, forCellReuseIdentifier: YHPlanAnalyzeInfoCell.cellReuseIdentifier)
        tableView.register(YHPlanScoreCell.self, forCellReuseIdentifier: YHPlanScoreCell.cellReuseIdentifier)
        tableView.register(YHPlanCustomerCaseListCell.self, forCellReuseIdentifier: YHPlanCustomerCaseListCell.cellReuseIdentifier)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.tableHeaderView = headerView
        return tableView
    }()
    
    lazy var whiteBackBtn: UIButton = {
        let v = UIButton()
        v.setImage(UIImage(named: "nav_back_white"), for: .normal)
        v.addTarget(self, action: #selector(backItemClick(_:)), for: .touchUpInside)
        return v
    }()
    
//    lazy var shareBtn: UIButton = {
//        let v = UIButton()
//        v.setImage(UIImage(named: "plan_nav_share"), for: .normal)
//        v.addTarget(self, action: #selector(didShareBtnClicked), for: .touchUpInside)
//        return v
//    }()
    
    @objc func didShareBtnClicked() {
        let vc = YHPlanShareViewController()
        vc.shareUrl = self.shareUrl
        vc.pdfCreateUrl = self.pdfCreateUrl
        vc.pdfDownloadUrl = self.pdfDownloadUrl
        self.navigationController?.pushViewController(vc)
    }
    
    lazy var headerView: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: headerViewHeight))
        v.addSubview(titleImgView)
        v.addSubview(descLabel)
        v.addSubview(revalueBtn)
        
        segmented1View.dataSource = segmented1DataSource
        v.addSubview(segmented1View)
        
        titleImgView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.width.equalTo(268)
            make.height.equalTo(42)
            make.top.equalTo(16)
        }
        
        descLabel.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(titleImgView.snp.bottom).offset(4)
            make.height.equalTo(16)
        }
        
        revalueBtn.snp.makeConstraints { make in
            make.top.equalTo(titleImgView).offset(16)
            make.right.equalTo(-16)
            make.width.equalTo(68)
            make.height.equalTo(28)
        }
        
        segmented1View.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(30)
            make.bottom.equalTo(-10)

        }
        return v
    }()
    
    lazy var bgImgView: UIImageView = {
        let v = UIImageView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenWidth))
        v.image = UIImage(named: "plan_list_head_bg")
        return v
    }()
    
    lazy var titleImgView: UIImageView = {
        let v = UIImageView()
        v.image = UIImage(named: "plan_list_title")
        return v
    }()
    
    lazy var descLabel: UILabel = {
        let lable = UILabel()
        lable.textColor = UIColor.init(hex: 0xFFFFFF, alpha: 0.6)
        lable.textAlignment = .left
        lable.font = UIFont.PFSC_R(ofSize: 12)
        lable.text = "具体方案您可以联系专属顾问和生活管家深入咨询"
        return lable
    }()
    
    lazy var revalueBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .clear
        btn.setTitle("重新评估", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 11)
        btn.addTarget(self, action: #selector(didRevalueBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        btn.layer.borderWidth = 0.5
        btn.layer.borderColor = UIColor.init(hex: 0xFFFFFF, alpha: 0.2).cgColor
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    let segmentTitles = ["综合", "工作", "生活", "投资", "逗留"]
    
    lazy var segmented1View: JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 30))
        view.backgroundColor = .clear
        view.delegate = self

        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = UIColor.white
        view.indicators = [indicator]
        
        return view
    }()
    
    lazy var segmented1DataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = segmentTitles
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 16)
        dataSource.titleNormalColor = UIColor.init(hex: 0xFFFFFF, alpha: 0.6)
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleSelectedColor = .white
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = (KScreenWidth-16.0*2.0)/Double(segmentTitles.count)
        dataSource.itemSpacing = 0.0
        return dataSource
    }()
    
    lazy var segmented2View: JXSegmentedView = {
       let view = JXSegmentedView(frame: CGRect(x: 0, y: k_Height_safeAreaInsetsTop(), width: KScreenWidth, height: 48))
        view.backgroundColor = .clear
        view.delegate = self
        // 配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.indicatorHeight = 2
        indicator.indicatorCornerRadius = 0.0
        indicator.indicatorColor = .mainTextColor
        view.indicators = [indicator]
        view.dataSource = segmented2DataSource
        return view
    }()
    
    lazy var segmented2DataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = segmentTitles
        dataSource.titleNormalFont = UIFont.PFSC_R(ofSize: 16)
        dataSource.titleNormalColor = UIColor.init(hex: 0x6A7586)
        dataSource.titleSelectedFont = UIFont.PFSC_M(ofSize: 16)
        dataSource.titleSelectedColor = .mainTextColor
        
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemWidth = (KScreenWidth-16.0*2.0)/Double(segmentTitles.count)
        dataSource.itemSpacing = 0.0
        return dataSource
    }()
    
    lazy var fixedSegmentView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.alpha = 0.0
        v.addSubview(segmented2View)
        
        segmented2View.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(30)
            make.bottom.equalTo(-6)
            make.top.equalTo(8)
        }
        
        return v
    }()
    
    lazy var bottomView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        
        let listView = YHPlanItemsView(frame: .zero)
        v.addSubview(listView)
        
        let button = YHLookPlanButton(frame: .zero)
        button.addTarget(self, action: #selector(didBottomBtnClicked), for: .touchUpInside)
        v.addSubview(button)
        
        listView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(17)
            make.top.equalTo(12)
        }
        
        button.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(60)
            make.top.equalTo(listView.snp.bottom).offset(8)
        }
        
        return v
    }()
    
    lazy var policyVieiw: YHPlanPolicyCarouselView = {
        let v = YHPlanPolicyCarouselView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 268))
        v.clickBlock = { [weak self] arr, index in
            guard let self = self else { return }
            let vc = YHPlanPolicyDetailViewController()
            vc.arr = arr
            vc.currentIndex = index
            self.navigationController?.pushViewController(vc, animated: true)
        }
        return v
    }()
    
    @objc func didRevalueBtnClicked() {
        let vc = YHCustomerInformationQuestionnaireVC()
        self.navigationController?.pushViewController(vc)
    }
    
    @objc func didBottomBtnClicked() {
        self.enterMakePlanPage()
    }
    
    func enterMakePlanPage() {
        let vc = YHMakePlanViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    func updateRightBarButtonItemWhite(_ isWhite: Bool) {
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: isWhite ? "plan_nav_share" : "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(didShareBtnClicked))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        gk_navBarAlpha = 0.0
        gk_navBackgroundColor = .clear
        gk_backImage = UIImage(named: "back_icon_white")
        gk_navTitleColor = .mainTextColor
        gk_navTitle = "续签至永居方案分析"
        
        self.view.backgroundColor = .init(hex: 0xF8F9FB)
        self.view.addSubview(bgImgView)
        self.view.addSubview(tableView)
        self.view.addSubview(fixedSegmentView)
        self.view.addSubview(bottomView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        fixedSegmentView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.height.equalTo(44)
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(102 + k_Height_safeAreaInsetsBottom())
        }
        
        requestData()
    }
    
    func requestData() {
        viewModel.requetResignPlanInfo { [weak self] _, _ in
            guard let self = self else { return }
            
            var workModel = YHPlanAnalyzeModel()
            workModel.name = "work"
            var liveModel = YHPlanAnalyzeModel()
            liveModel.name = "live"
            var investModel = YHPlanAnalyzeModel()
            investModel.name = "invest"
            var stayModel = YHPlanAnalyzeModel()
            stayModel.name = "stay"

            for item in self.viewModel.planListModel.list {
                if item.name == "work" {
                    workModel = item
                    
                } else if item.name == "live" {
                    liveModel = item
                    
                } else if item.name == "invest" {
                    investModel = item
                    
                } else if item.name == "stay" {
                    stayModel = item
                }
            }
            workModel.score = self.viewModel.planListModel.basic.work_score
            liveModel.score = self.viewModel.planListModel.basic.live_score
            investModel.score = self.viewModel.planListModel.basic.invest_score
            stayModel.score = self.viewModel.planListModel.basic.stay_time_score
            
            analyzeArr.removeAll()
            analyzeArr.append(contentsOf: [workModel, liveModel, investModel, stayModel])
            policyArr.removeAll()
            policyArr.append(contentsOf: self.viewModel.planListModel.plan_article_policy)
            caseArr.removeAll()
            caseArr.append(contentsOf: self.viewModel.planListModel.plan_article_case)
            
            policyVieiw.bannerArr = policyArr
            
            let url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/plan-analysis?code="
            pdfCreateUrl = url + self.viewModel.planListModel.code
            pdfDownloadUrl = self.viewModel.planListModel.pdf_url
            shareUrl = self.viewModel.planListModel.share_url
            
            self.tableView.reloadData()
            
            UIView.performWithoutAnimation {
                self.tableView.scrollToRow(at: IndexPath(row: NSNotFound, section: self.infoArr.count-2), at: .top, animated: false)
               self.tableView.setContentOffset(.zero, animated: false)
            }
        }
    }
}

extension YHPlanTestViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.infoArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                
        if 0 <= indexPath.section && indexPath.section < self.infoArr.count {
            if indexPath.section == 0 {
                guard let cell1 = tableView.dequeueReusableCell(withIdentifier: YHPlanScoreCell.cellReuseIdentifier, for: indexPath) as? YHPlanScoreCell else {
                    return UITableViewCell()
                }
                cell1.model = self.viewModel.planListModel.basic
                return cell1
            } else if indexPath.section < 5 {
                guard let cell2 = tableView.dequeueReusableCell(withIdentifier: YHPlanAnalyzeInfoCell.cellReuseIdentifier, for: indexPath) as?  YHPlanAnalyzeInfoCell else {
                    return UITableViewCell()
                }
                cell2.model = analyzeArr[indexPath.section-1]
                cell2.clickBlock = { [weak self] _ in
                    guard let self = self else { return }
                    self.enterMakePlanPage()
                }
                return cell2
                
            } else if indexPath.section == 5 {
                
                if caseArr.count > 0 {
                    guard let cell3 = tableView.dequeueReusableCell(withIdentifier: YHPlanCustomerCaseListCell.cellReuseIdentifier, for: indexPath) as?  YHPlanCustomerCaseListCell else {
                        return UITableViewCell()
                    }
                    cell3.cases = self.caseArr
                    cell3.clickBlock = { [weak self] arr, index in
                        guard let self = self else { return }
                        let vc = YHPlanPolicyDetailViewController()
                        vc.arr = arr
                        vc.currentIndex = index
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                    return cell3
                }
            }
        }
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        defaultCell.backgroundColor = .clear
        defaultCell.contentView.backgroundColor = .clear
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 5 {
            if caseArr.count > 0 {
                return getCaseListHeight()
            }
            return 1.0
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        if section == 4 {
            if policyArr.count > 0 {
                return 268.0
            }
            return 1.0
        }
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 4 {
            if policyArr.count > 0 {
                return self.policyVieiw
            }
        }
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    // 计算文字宽度大小
    func getHeigt(font: UIFont, width: CGFloat, string: String) -> CGFloat {
        let size = CGSize.init(width: width, height: CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        let strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return ceil(strSize.height)
    }
    
    func getCaseListHeight() -> CGFloat {
        
        let cellWidth = floor((KScreenWidth-16.0*2.0-10.0)/2.0)
        var yOffset1 = 0.0
        var yOffset2 = 0.0
        
        for (index, item) in caseArr.enumerated() {
            let textHeight = self.getHeigt(font: UIFont.PFSC_R(ofSize: 14), width: cellWidth-8.0*2.0, string: item.title)
            let caseCellHeight = textHeight + (cellWidth*(200.0/166.0) + 8.0+12.0+10.0)
            
            if index % 2 == 0 {
                yOffset1 += caseCellHeight
            } else {
                yOffset2 += caseCellHeight
            }
        }
        let contentHeight = max(yOffset1, yOffset2) + 20.0 + 12.0
        return contentHeight
    }
}

extension YHPlanTestViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView.contentOffset.y > 0 {
            var alpha = scrollView.contentOffset.y/20.0
            if alpha > 1.0 {
                alpha = 1.0
            } else if alpha < 0.0 {
                alpha = 0.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = "续签至永居方案分析"
            gk_backImage = UIImage(named: "nav_black_24")
            updateRightBarButtonItemWhite(false)
            
        } else {
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
            gk_backImage = UIImage(named: "back_icon_white")
            updateRightBarButtonItemWhite(true)
        }

        fixedSegmentView.alpha = scrollView.contentOffset.y >= topScrollHeight ? 1.0 : 0.0
        bgImgView.y =  -tableView.contentOffset.y
        printLog("tableView: \(tableView.contentOffset.y)")
        
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
        var find = false
        for index in 0...infoArr.count-1 {
            let rect = self.tableView.rectForRow(at: IndexPath(row: 0, section: index))
            
            let conditon =  tableView.contentOffset.y <= rect.origin.y-44.0
            
            if  conditon, index < infoArr.count-1 {
                find = true
                
                let targetIndex = index-1 >= 0 ? index-1 : 0
                self.segmented2View.defaultSelectedIndex = targetIndex
                self.segmented2View.reloadDataWithoutListContainer()
                self.segmented1View.defaultSelectedIndex = targetIndex
                self.segmented1View.reloadDataWithoutListContainer()
                printLog("TargetIndex: \(targetIndex)")
                break
            }
        }
        
        if !find {
            printLog("TargetIndex: \(segmentTitles.count-1)")
            self.segmented2View.defaultSelectedIndex = segmentTitles.count-1
            self.segmented2View.reloadDataWithoutListContainer()
            self.segmented1View.defaultSelectedIndex = segmentTitles.count-1
            self.segmented1View.reloadDataWithoutListContainer()
        }
    }
}

extension YHPlanTestViewController: JXSegmentedViewDelegate {
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {

        self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y+2), animated: true)
        
        DispatchQueue.main.asyncAfter(deadline: .now()+0.15, execute: {
            let index = segmentedView.selectedIndex
            let rect = self.tableView.rectForHeader(inSection: index)
            let gap = index > 0 ? 8.0 : 0.0
            self.tableView.setContentOffset(CGPoint(x: 0, y: rect.origin.y-44.0-gap), animated: true)
        })
        
        if segmentedView == segmented1View {
            self.segmented2View.defaultSelectedIndex = index
            self.segmented2View.reloadDataWithoutListContainer()
        }
        if segmentedView == segmented2View {
            self.segmented1View.defaultSelectedIndex = index
            self.segmented1View.reloadDataWithoutListContainer()
        }
    }
}
