//
//  YHAdopterNewPeopleViewController.swift
//  galaxy
//
//  Created by EDY on 2024/8/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHAdopterNewPeopleViewController: YHBaseViewController {
    var stepView: YHStepView!
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHAdopterNewPeopleViewModel!
    var dataSource: [YHSectionItemModel] = []
    var cardDataSource: [YHAdopterCardModel] = []
    var isShowPrompt: Bool = false
    var id: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHAdopterNewPeopleViewModel()
        gk_navTitle = "新增配偶"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        setView()
        getData()
        // Do any additional setup after loading the view.
    }
    
    func getData() {
        self.updateDataSource()
        viewModel.getDependentsData(id: id) {[weak self] success, error in
            guard let self = self else { return }
            self.updateDataSource()
        }
    }
    
    func updateDataSource() {
        if self.stepView.currentIndex == 0 {
            self.dataSource = self.viewModel.getBaseDataSource(isShowPrompt)
            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        } else if self.stepView.currentIndex == 1 {
            self.cardDataSource = self.viewModel.getIdCardInformation()
//            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        }
        self.tableView.reloadData()
    }
    
    func setView() {
        view.backgroundColor = .contentBkgColor
        
        stepView = {
            let step = YHStepView()
            step.dataSource = ["完善配偶信息", "上传配偶资料"]
            step.block = { [weak self] (index) in
                guard let self = self else { return }
                self.updateDataSource()
            }
            return step
        }()
        view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.height.equalTo(104)
        }
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHMainInformationTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterCardTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + YHStepView.height)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = YHBottomNextView()
            bottom.saveButton.setTitle("上一步", for: .normal)
            bottom.saveButton.isHidden = true
            bottom.nextButton.snp.remakeConstraints { make in
                make.right.equalTo(-16)
                make.top.equalTo(10)
                make.height.equalTo(44)
                make.left.equalTo(16)
            }
            bottom.nextblock = { [weak self] in
                bottom.nextButton.isEnabled = false
                guard let self = self else { return }
                if self.viewModel.isCanNext(self.stepView.currentIndex) {
                    self.viewModel.postDependentsAdd(id: id) {[weak self]  success, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        bottom.saveButton.isHidden = false
                        bottom.nextButton.setTitle("确认，保存", for: .normal)
                        bottom.nextButton.snp.remakeConstraints { make in
                            make.right.equalTo(-16)
                            make.top.equalTo(10)
                            make.height.equalTo(44)
                            make.left.equalTo(bottom.saveButton.snp.right).offset(10)
                        }
                        self.stepView.currentIndex = self.stepView.currentIndex + 1
                        let view = YHAdopterCardOtherGuideView.sheetView()
                        view.ischeckBeforeFlag = false
                        view.block = {
                        }
                        view.show()
                    }
                    
//                    self.viewModel.mainModel.step = self.stepView.currentIndex
//                    self.viewModel.updateMainInformation(.submit, self.orderId, self.stepView.currentIndex) {[weak self] success, error  in
//                        guard let self = self else { return }
//                        if let error = error {
//                            YHHUD.flash(message: error.errorMsg )
//                        } else {
//                            YHHUD.hideFlashMessage()
//                            self.stepView.currentIndex = self.stepView.currentIndex + 1
//                            self.isShowPrompt = false
//                            self.stepView.currentIndex = self.stepView.currentIndex
//                            if self.stepView.currentIndex == 3 {
//                                self.bottomView.nextButton.setTitle("提交", for: .normal)
//                            } else {
//                                self.bottomView.nextButton.setTitle("下一步", for: .normal)
//                            }
//                            if self.stepView.currentIndex == self.stepView.dataSource?.count {
//                                YHHUD.flash(message: "提交成功")
//                                self.navigationController?.popViewController()
//                            } else {
//                                self.updateDataSource()
//                            }
//                        }
//                    }
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    YHHUD.flash(message: "您还有信息未填写")
                }
                
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                self.stepView.currentIndex = 0
                self.getData()
                bottom.saveButton.setTitle("上一步", for: .normal)
                bottom.saveButton.isHidden = true
                bottom.nextButton.snp.remakeConstraints { make in
                    make.right.equalTo(-16)
                    make.top.equalTo(10)
                    make.height.equalTo(44)
                    make.left.equalTo(16)
                }
            }
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        bottomView.layoutIfNeeded()
        bottomView.nextButton.addYinHeGradualLayer()
    }
}

extension YHAdopterNewPeopleViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if stepView.currentIndex == 1 {
            return cardDataSource.count
        }
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if stepView.currentIndex == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterCardTableViewCell.self)
            cell.dataSource = cardDataSource[indexPath.row]
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHMainInformationTableViewCell.self)
            cell.dataSource = dataSource[indexPath.row]
            cell.informationBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if stepView.currentIndex == 1 {
            let model = cardDataSource[indexPath.row]
            if model.type == .china || model.type == .resident {
                return 90
            } else {
                return 78
            }
        } else {
            let array = dataSource[indexPath.row].models ?? []
            var h = 0
            for i in 0..<array.count {
                let data = array[i]
                let isShow = data.isShowPrompts ?? false
                let message = data.message ?? ""
                let isNeed = data.isNeed ?? false
                if data.id == .id3 || data.id == .id4 || data.id == .id32 || data.id == .id33 {
                    if isShow && message.count == 0 && isNeed {
                        h = h + 72 + 20
                    } else {
                        h = h + 72
                    }
                } else {
                    if isShow && message.count == 0 && isNeed {
                        h = h + 52 + 20
                    } else {
                        h = h + 52
                    }
                }
            }
            return CGFloat(h + 52 + 14)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if stepView.currentIndex == 1 {
            let model = cardDataSource[indexPath.row]
            switch model.type {
            case .travel:
                let vc = YHAdopterTravelViewController()
                self.navigationController?.pushViewController(vc)
            case .china:
                let vc = YHAdopterChinaViewController()
                self.navigationController?.pushViewController(vc)
            case .resident:
                let vc = YHAdopterResidentViewController()
                self.navigationController?.pushViewController(vc)
            case .birth:
                let vc = YHAdopterBirthViewController()
                self.navigationController?.pushViewController(vc)
            case .id:
                let vc = YHAdopterIdCardViewController()
                self.navigationController?.pushViewController(vc)
            case .other:
                let vc = YHAdopterOtherViewController()
                self.navigationController?.pushViewController(vc)
            case .marry:
                let vc = YHAdopterMarryViewController()
                self.navigationController?.pushViewController(vc)
            case .chinaTravel:
                let vc = YHAdoptedChinaTravelViewController()
                self.navigationController?.pushViewController(vc)
            case .chinaLife:
                let vc = YHAdopterChinaLifeViewController()
                self.navigationController?.pushViewController(vc)
            }
        }
    }
}
