//
//  YHResignInfoConfirmViewController.swift
//  galaxy
//
//  Created by edy on 2024/10/9.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHResignConfirmInfoListViewController: YHBaseViewController {

    var orderId: Int = 0
    var stepId: Int = 0 // 批次ID
    var familyArr = [YHResignInfoConfirmFamilyInfoModel]()
    
    let viewModel = YHResignInfoConfirmViewModel()

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        if #available(iOS 15.0, *) {
           tableView.sectionHeaderTopPadding = 0.0
        }
        tableView.estimatedSectionHeaderHeight = 52.0
        tableView.estimatedSectionFooterHeight = 0.1
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false
        tableView.register(YHResignFamilyMemberInfoCell.self, forCellReuseIdentifier: YHResignFamilyMemberInfoCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = headerView
        return tableView
    }()
    
    lazy var headerView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth-32, height: (KScreenWidth-32.0) * (109.0/343.0) + 16.0))
        let tipsImgView = UIImageView(image: UIImage(named: "resign_risk_warning"))
        view.addSubview(tipsImgView)
        tipsImgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-16.0)
        }
        return view
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认修改，下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didBottomBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(46)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "续签信息确认"
        self.gk_navigationBar.backgroundColor = .white
        self.view.backgroundColor = .init(hex: 0xF8F9FB)
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+16)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestList()
    }
    
    func isAllMemberConfirmed() -> Bool {
        for model in familyArr {
            if !model.isConfirmed() {
                return false
            }
        }
        return true
    }

    @objc func didBottomBtnClicked() {
        
        if !isAllMemberConfirmed() {
            YHHUD.flash(message: "存在未确认信息，此信息涉及后续【续签申请】，辛苦核对")
            return
        }
        
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.submitAllConfirmInfo(orderId: self.orderId, stepId: self.stepId) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if !success {
                let msg = error?.errorMsg ?? ""
                YHHUD.flash(message: msg)
                return
            }
            self.navigationController?.popToRootViewController(animated: false)
            YHButlerServiceManager.shared.sessionGoBack()
            goTabBarBy(tabType: .service)
        }
    }
    
    func showRiskAlertView() {
        let isShowKey = "isShowResignConfirmRisk_\(stepId)"
        if let isShow = UserDefaults.standard.value(forKey: isShowKey) as? Bool, isShow == true {
            
        } else {
            // 风险弹窗
            YHResignRiskWarningAlertView.alertView().show()
            UserDefaults.standard.set(true, forKey: isShowKey)
            UserDefaults.standard.synchronize()
        }
    }
}

extension YHResignConfirmInfoListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return familyArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHResignFamilyMemberInfoCell.cellReuseIdentifier, for: indexPath) as? YHResignFamilyMemberInfoCell else {
            return UITableViewCell()
        }
        
        if 0 <= indexPath.row && indexPath.row < familyArr.count {
            let model = familyArr[indexPath.row]
            cell.updateModel(model)
            cell.updateLineMargin(indexPath.row == 0 ? 0.0 : 18.0)
            if indexPath.row == familyArr.count-1 {
                let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
                cell.createCorner(CGSize(width: kCornerRadius6, height: kCornerRadius6), corner)
                
            } else {
                cell.layer.mask = nil
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 69.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.row && indexPath.row < familyArr.count {
            
            let model = familyArr[indexPath.row]
            let vc = YHResignInfoConfirmModifyViewController()
            vc.detailMember = model.info
            self.navigationController?.pushViewController(vc)
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 52.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        view.clipsToBounds = true
        let cornerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.width, height: 58.0))
        cornerView.backgroundColor = .white
        cornerView.layer.cornerRadius = kCornerRadius6
        cornerView.clipsToBounds = true
        view.addSubview(cornerView)
        let titleLabel = UILabel(frame: CGRect(x: 18, y: 16, width: KScreenWidth, height: 24.0))
        let mustTag: ASAttributedString = .init("* ", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.failColor))
        var title: ASAttributedString = .init("续签信息核实", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
        title = mustTag + title
        titleLabel.attributed.text = title
        cornerView.addSubview(titleLabel)
        return view
    }
}

extension YHResignConfirmInfoListViewController {
    
    func requestList() {
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getList(id: stepId) { success, _ in
            if success {
                self.showRiskAlertView()
            }
            YHHUD.hide()
            self.familyArr.removeAll()
            self.familyArr.append(contentsOf: self.viewModel.getList())
            self.tableView.reloadData()
        }
    }
}
