//
//  YHLookResignResultViewController.swift
//  galaxy
//
//  Created by EDY on 2024/10/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHLookResignResultViewController: YHBaseViewController {
    var orderId: Int = 0
    // 批次id
    var batchId: Int = 0
    var state = 2
    lazy var viewModel: YHLookResignResultViewModel = {
        let vm = YHLookResignResultViewModel()
        return vm
    }()

    var headView: YHLookResignResultHeadView!
    var privacyView: YHLookResignResultPrivateView!
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(YHLookResignResultStateOneTableViewCell.self, forCellReuseIdentifier: YHLookResignResultStateOneTableViewCell.cellReuseIdentifier)
        tableView.register(YHLookResignResultStateTwoTableViewCell.self, forCellReuseIdentifier: YHLookResignResultStateTwoTableViewCell.cellReuseIdentifier)
        tableView.register(YHLookResignResultStateThreeTableViewCell.self, forCellReuseIdentifier: YHLookResignResultStateThreeTableViewCell.cellReuseIdentifier)
        tableView.register(YHLookResignResultStateThreePeopleTableViewCell.self, forCellReuseIdentifier: YHLookResignResultStateThreePeopleTableViewCell.cellReuseIdentifier)
        
        return tableView
    }()

    // 我已知悉，确认
    lazy var rewardBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("去缴费", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.white, for: .disabled)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickNextBtn), for: .touchUpInside)
        button.backgroundColor = UIColor.brandMainColor
        return button
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(self.rewardBtn)
        self.rewardBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(44)
        }
        view.layer.zPosition = 10
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadData()
    }
    
    @objc func clickNextBtn() {
        if state == 1 {
            let vc = YHResignUploadDocListViewController()
            vc.orderId = orderId
            vc.batchId = batchId
            self.navigationController?.pushViewController(vc)
        } else {
            if privacyView.isAgree {
                let vc = YHHKVisaRenewalPaymentVC(orderId: orderId, renewalId: batchId)
                self.navigationController?.pushViewController(vc)
            } else {
                privacyView.alert()
            }
        }
    }
}

private extension YHLookResignResultViewController {
    func loadData() {
        viewModel.getRenewalResult(batchId) {[weak self] success, error in
            guard let self = self else { return }
            if success {
                if self.viewModel.dataModel.status == 1 || self.viewModel.dataModel.status == 2 {
                    state = 0
                } else if self.viewModel.dataModel.status == 3 {
                    state = 1
                } else {
                    state = 2
                }
                self.updateView()
                self.tableView.reloadData()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "数据错误")
                self.tableView.isHidden = true
                self.bottomView.isHidden = true
            }
        }
        
    }
    
    func setupUI() {
        view.backgroundColor = UIColor.contentBkgColor
    
        headView = {
            let view = YHLookResignResultHeadView()
            view.state = state
            return view
        }()
        headView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 239.fix)
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(98)
            make.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalTo(-98)
        }
        
        tableView.tableHeaderView = headView
    }
    
    func updateView() {
        if state == 0 {
            bottomView.isHidden = true
            tableView.snp.remakeConstraints { make in
                make.left.equalToSuperview()
                make.right.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            tableView.tableFooterView = YHLookResignResultFootView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 150))
        } else if state == 1 {
            bottomView.isHidden = false
            rewardBtn.setTitle("去补件", for: .normal)
        } else {
            bottomView.isHidden = false
            rewardBtn.setTitle("去缴费", for: .normal)
            tableView.snp.remakeConstraints { make in
                make.left.equalToSuperview()
                make.right.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalTo(-138)
            }
            privacyView = {
                let view = YHLookResignResultPrivateView()
                return view
            }()
            view.addSubview(privacyView)
            privacyView.snp.makeConstraints { make in
                make.bottom.equalTo(-98)
                make.left.equalTo(0)
                make.height.equalTo(40)
                make.right.equalTo(0)
            }
        }
        headView.state = state
        headView.dataSource = self.viewModel.dataModel
    }
    
    func convertNumberToChineseText(_ number: Int) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: "zh_CN")
        numberFormatter.numberStyle = .spellOut
        return numberFormatter.string(from: NSNumber(value: number)) ?? ""
    }
}

extension YHLookResignResultViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if state == 0 {
            return self.viewModel.dataModel.data.data.count
        } else if state == 1 {
            return 1
        } else {
            return 2
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if state == 2 {
            if section == 1 {
                return 1
            }
            return self.viewModel.dataModel.data.data.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if state == 0 {
            guard let approveCell = tableView.dequeueReusableCell(withIdentifier: YHLookResignResultStateOneTableViewCell.cellReuseIdentifier, for: indexPath) as? YHLookResignResultStateOneTableViewCell else {
                return UITableViewCell()
            }
            approveCell.title = "第" + convertNumberToChineseText(self.viewModel.dataModel.data.data[indexPath.section].number) + "批"
            approveCell.dataSource = self.viewModel.dataModel.data.data[indexPath.section]
            return approveCell
        } else if state == 1 {
            guard let approveCell = tableView.dequeueReusableCell(withIdentifier: YHLookResignResultStateTwoTableViewCell.cellReuseIdentifier, for: indexPath) as? YHLookResignResultStateTwoTableViewCell else {
                return UITableViewCell()
            }
            approveCell.state = state
            let model = YHLookResignResultDataLettersModel()
            model.result_file = self.viewModel.dataModel.data.result_file
            model.user = self.viewModel.dataModel.data.user
            approveCell.dataSource = [model]
            return approveCell
            
        } else {
            if indexPath.section == 0 {
                guard let approveCell = tableView.dequeueReusableCell(withIdentifier: YHLookResignResultStateThreePeopleTableViewCell.cellReuseIdentifier, for: indexPath) as? YHLookResignResultStateThreePeopleTableViewCell else {
                    return UITableViewCell()
                }
                approveCell.title = "第" + convertNumberToChineseText(self.viewModel.dataModel.data.data[indexPath.row].number) + "批"
                approveCell.dataSource = self.viewModel.dataModel.data.data[indexPath.row]
                if indexPath.row == self.viewModel.dataModel.data.data.count - 1 {
                    approveCell.lineView.isHidden = true
                } else {
                    approveCell.lineView.isHidden = false
                }
                return approveCell
            } else {
                guard let approveCell = tableView.dequeueReusableCell(withIdentifier: YHLookResignResultStateThreeTableViewCell.cellReuseIdentifier, for: indexPath) as? YHLookResignResultStateThreeTableViewCell else {
                    return UITableViewCell()
                }
                approveCell.state = state
                approveCell.dataSource = self.viewModel.dataModel.data.letters
                return approveCell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if state == 0 {
            return 140
        }
        if state == 1 {
            return 258
//            let number = (6 - 1) / 2
//            return CGFloat(208 + 116 * number)
        }
        
        if indexPath.section == 0 {
            return 126
        }
        if self.viewModel.dataModel.data.letters.count == 1 {
            return 242
        }
        let number = (self.viewModel.dataModel.data.letters.count - 1) / 2
        return CGFloat(192 + 116 * number)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if self.viewModel.dataModel.data.data.count == 0 {
            return 0.01
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if self.viewModel.dataModel.data.data.count == 0 {
            let view = UIView()
            return view
        }
        let view = UIView()
        let titlelabel = UITextView()
        titlelabel.backgroundColor = .clear
        titlelabel.textColor = UIColor.mainTextColor
        titlelabel.font = UIFont.PFSC_M(ofSize: 16)
        titlelabel.isScrollEnabled = false
        titlelabel.isEditable = false
        titlelabel.isSelectable = false
        titlelabel.text = "    "
        view.addSubview(titlelabel)
        
        titlelabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview()
            make.height.equalTo(16)
            make.bottom.equalToSuperview()
        }
        return view
    }
}

extension YHLookResignResultViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            var alpha =  scrollView.contentOffset.y / (k_Height_NavigationtBarAndStatuBar)
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            if state == 0 {
                gk_navTitle = "续签审核中"
            } else if state == 1 {
                gk_navTitle = "续签待补件"
            } else {
                gk_navTitle = "续签已获批"
            }
            gk_backImage = UIImage(named: "back_icon")
        } else {
            gk_navBarAlpha = 0.0
            gk_navTitle = ""
            gk_backImage = UIImage(named: "back_icon")
        }
    }
}
