//
//  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: [YHAdopterDependentDataDocModel] = []
    var isShowPrompt: Bool = false
    var id: Int = 0
    var titleText: String = "新增子女"
    var isShowRed: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHAdopterNewPeopleViewModel()
        gk_navTitle = titleText
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        setView()
//        getData()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    func getData() {
        self.updateDataSource()
        viewModel.getDependentsData(id: id) {[weak self] _, _ in
            guard let self = self else { return }
            if self.viewModel.isCanNext(self.stepView.currentIndex) {
                self.stepView.currentIndex = 1
            } else {
                self.stepView.currentIndex = 0
            }
            self.updateDataSource()
        }
    }
    
    func updateDataSource() {
        if self.stepView.currentIndex == 0 {
            if titleText == "新增子女" {
                self.dataSource = self.viewModel.getBaseDataSource(isShowPrompt, "子女信息")
            } else {
                self.dataSource = self.viewModel.getBaseDataSource(isShowPrompt)
            }
            self.bottomView.nextButton.setTitle("下一步", for: .normal)
        } else if self.stepView.currentIndex == 1 {
            self.cardDataSource = self.viewModel.mainModel.docList
            self.bottomView.nextButton.isEnabled = true
            self.bottomView.saveButton.isHidden = false
            self.bottomView.nextButton.setTitle("确认，保存", for: .normal)
            self.bottomView.nextButton.snp.remakeConstraints { make in
                make.right.equalTo(-16)
                make.top.equalTo(10)
                make.height.equalTo(44)
                make.left.equalTo(self.bottomView.saveButton.snp.right).offset(10)
            }
        }
        self.tableView.reloadData()
    }
    
    func setView() {
        view.backgroundColor = .contentBkgColor
        
        stepView = {
            let step = YHStepView()
            if titleText == "新增子女" {
                step.dataSource = ["完善子女信息", "上传子女资料"]
            } else {
                step.dataSource = ["完善配偶信息", "上传配偶资料"]
            }
            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.stepView.currentIndex == 0 {
                    if self.viewModel.isCanNext(self.stepView.currentIndex) {
                        self.viewModel.postDependentsAdd(id: id) {[weak self]  _, _ 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 += 1
                            self.updateDataSource()
                            if self.viewModel.mainModel.info.is_read_agreement == 0 &&  titleText == "新增子女" {
                                let view = YHAdopterCardOtherGuideView.sheetView()
                                view.ischeckBeforeFlag = false
                                view.block = {
                                    self.viewModel.postIsReadAgreement(id: self.id) { _, _ in
                                    }
                                }
                                view.show()
                            }
                        }
                    } else {
                        bottom.nextButton.isEnabled = true
                        self.isShowPrompt = true
                        self.updateDataSource()
                        YHHUD.flash(message: "您还有信息未填写")
                    }
                } else {
                    for item in cardDataSource {
                        if (item.status == 0 || item.status == 2) && item.require == 1 {
                            YHHUD.flash(message: "请上传相关证件")
                            isShowRed = true
                            tableView.reloadData()
                            return
                        }
                    }
                    self.viewModel.getDependentsCheck {[weak self] _, _ in
                        guard let self = self else { return }
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                self.stepView.currentIndex = 0
                self.updateDataSource()
                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.isShowRed = isShowRed
            cell.dataSource = cardDataSource[indexPath.row]
            cell.clickBlock = {[weak self] _ in
                guard let self = self else { return }
                let model = cardDataSource[indexPath.row]
                switch model.dep_type {
                case 0:// 旅行证件（港澳通行证/护照)
                    let vc = YHAdopterTravelViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 1:// 身份证（正反面)
                    let vc = YHAdopterChinaViewController()
                    vc.model = model
                    vc.name = viewModel.mainModel.info.dep_name
                    self.navigationController?.pushViewController(vc)
                case 2:// 户口信息页
                    let vc = YHAdopterResidentViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 3:// 结婚证信息页
                    let vc = YHAdopterMarryViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 4:// 证件照片
                    let vc = YHAdopterIdCardViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 5:// 出生医学证明
                    let vc = YHAdopterBirthViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 6:// 中国居留许可签证（有效期内)
                    let vc = YHAdopterChinaLifeViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 7:// 中国旅行证
                    let vc = YHAdoptedChinaTravelViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                case 8:// 其他证件（请致电客服咨询后上传相关证件）
                    let vc = YHAdopterOtherViewController()
                    vc.model = model
                    self.navigationController?.pushViewController(vc)
                default:
                    break
                }
            }
            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 isShowRed && (model.status == 0 || model.status == 2) && model.require == 1 {
                return 99
            }
            if model.dep_type == 1 || model.dep_type == 2 {
                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 += 72
                    }
                } else {
                    if isShow && message.count == 0 && isNeed {
                        h += (52 + 20)
                    } else {
                        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.dep_type {
            case 0:// 旅行证件（港澳通行证/护照)
                let vc = YHAdopterTravelViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 1:// 身份证（正反面)
                let vc = YHAdopterChinaViewController()
                vc.model = model
                vc.name = viewModel.mainModel.info.dep_name
                self.navigationController?.pushViewController(vc)
            case 2:// 户口信息页
                let vc = YHAdopterResidentViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 3:// 结婚证信息页
                let vc = YHAdopterMarryViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 4:// 证件照片
                let vc = YHAdopterIdCardViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 5:// 出生医学证明
                let vc = YHAdopterBirthViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 6:// 中国居留许可签证（有效期内)
                let vc = YHAdopterChinaLifeViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 7:// 中国旅行证
                let vc = YHAdoptedChinaTravelViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            case 8:// 其他证件（请致电客服咨询后上传相关证件）
                let vc = YHAdopterOtherViewController()
                vc.model = model
                self.navigationController?.pushViewController(vc)
            default:
                break
            }
        }
    }
}
