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

import UIKit

class YHAddAdoptersViewController: YHBaseViewController {
    var tableView: UITableView!
    var nextButton: UIButton!
    var bottonView: UIView!
    var clickIndex = 2
    let viewModel = YHAddpterViewModel()
    var orderId: Int = 0
    var isMore: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "新增受养人"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        setView()
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        isMore = false
        getData()
    }
    
    func getData() {
        viewModel.getAddpterMainData(orderId: orderId) {[weak self] _, _ in
            guard let self = self else { return }
            self.clickIndex = self.viewModel.model?.has_dependent ?? 2
            tableView.reloadData()
            if self.viewModel.model?.is_reserved_open == 1 && self.viewModel.model?.has_dependent == 0 {
                self.bottonView.isHidden = false
                self.nextButton.isHidden = false
            } else {
                self.bottonView.isHidden = true
                self.nextButton.isHidden = true
            }
        }
    }
    
    func setView() {
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.showsVerticalScrollIndicator = false
            tableView.showsHorizontalScrollIndicator = false
            tableView.register(cellWithClass: YHAdopterMainTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterStepTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterAddNewTableViewCell.self)
            tableView.register(cellWithClass: YHAdopterIncomeTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 8)
            make.left.right.equalTo(view)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom())
        }
        
        bottonView = UIView()
        bottonView.backgroundColor = .white
        bottonView.isHidden = true
        view.addSubview(bottonView)
        bottonView.snp.makeConstraints { make in
            make.height.equalTo(98)
            make.bottom.left.right.equalTo(view)
        }
        
        nextButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("下一步，预约赴港办证", for: .normal)
            button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(nextStep), for: .touchUpInside)
            button.isHidden = true
            return button
        }()
        view.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(48)
        }
        
    }
    
    @objc func nextStep() {
        let vc = YHCertificateAppointViewController()
        vc.orderId = orderId
        navigationController?.pushViewController(vc)
    }

    func showDeleteAlert(_ model: YHAdopterDependentModel) {
        var spouse = "子女"
        if model.is_spouse == 1 {
            spouse = "配偶"
        }
        var value = ""
        if model.dep_name.count != 0 {
            value = spouse + "(\(model.dep_name))"
        } else {
            value = spouse
        }
        YHCommonAlertView.show("", "您确定要删除\(value)吗？", "取消", "确认") {
            self.viewModel.postDependentsDel(id: model.id) { [weak self] _, _ in
                guard let self = self else { return }
                self.getData()
            }
        }
    }
}

extension YHAddAdoptersViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if clickIndex == 1 {
            return 4
        } else {
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterMainTableViewCell.self)
            cell.clickBlock = { [weak self] index in
                guard let self = self else { return }
                self.clickIndex = index
                self.viewModel.postDependentAdd(dependent: index, orderId: orderId) {[weak self] _, _ in
                    guard let self = self else { return }
                    if self.clickIndex == 0 {
                        let view = YHNoAdopterAlertView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
                        let window = UIApplication.shared.yhKeyWindow()
                        window?.addSubview(view)
                        if self.viewModel.flag?.is_reserved_open == 1 {
                            self.bottonView.isHidden = false
                            self.nextButton.isHidden = false
                        }
                    }
                    self.getData()
                }
            }
            cell.clickIndex = clickIndex
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterStepTableViewCell.self)
            return cell
        } else if indexPath.row == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterAddNewTableViewCell.self)
            cell.dataSource = self.viewModel.model?.dependent
            if isMore {
                cell.more()
            } else {
                cell.cannal()
            }
            cell.isMoreBlock = {[weak self] isMore in
                guard let self = self else { return }
                self.isMore = isMore
            }
            cell.newAdopterBlock = {[weak self] in
                guard let self = self else { return }
                var items: [YHCertificateEditItem] = []
                if !(self.viewModel.model?.has_spouse ?? false) {
                    items.append(YHCertificateEditItem(type: .rename, title: "新增配偶"))
                }
                items.append(YHCertificateEditItem(type: .preview, title: "新增子女"))
                items.append(YHCertificateEditItem(type: .cancel, title: "取消"))

                YHCertificateEditSheetView.sheetView(items: items) {
                    [weak self] editType in
                    guard let self = self else { return }
                    if editType == .rename {
                        self.viewModel.postManagementAdd(isSpouse: 1, orderId: orderId) {[weak self] _, _ in
                            guard let self = self else { return }
                            let vc = YHAdopterNewPeopleViewController()
                            vc.id = self.viewModel.addModel?.id ?? 0
                            vc.titleText = "新增配偶"
                            self.navigationController?.pushViewController(vc)
                        }
                    }
                    if editType == .preview {
                        self.viewModel.postManagementAdd(isSpouse: 0, orderId: orderId) {[weak self] _, _ in
                            guard let self = self else { return }
                            let vc = YHAdopterNewPeopleViewController()
                            vc.id = self.viewModel.addModel?.id ?? 0
                            vc.titleText = "新增子女"
                            self.navigationController?.pushViewController(vc)
                        }
                    }
                    if editType == .delete {
                        
                    }
                }.show()
            }
            cell.deleteBlock = { [weak self] model in
                guard let self = self else { return }
                self.showDeleteAlert(model)
            }
            cell.clickBlock = { [weak self] model in
                guard let self = self else { return }
                let vc = YHAdopterNewPeopleViewController()
                vc.id = model.id
                var spouse = "子女"
                if model.is_spouse == 1 {
                    spouse = "配偶"
                }
                vc.titleText = "新增" + spouse
                self.navigationController?.pushViewController(vc)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeTableViewCell.self)
            cell.dataSource = self.viewModel.model?.deposit
            cell.clickBlock = { [weak self] _ in
                guard let self = self else { return }
                let vc = YHAdopterIncomeDetailViewController()
                vc.data = self.viewModel.model?.deposit ?? YHAdopterDepositModel()
                vc.orderId = orderId
                self.navigationController?.pushViewController(vc)
            }
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 225
        }
        if indexPath.row == 1 {
            return 136
        }
        if indexPath.row == 2 {
            let count = self.viewModel.model?.dependent.count ?? 0
            return CGFloat(156 + count * 52)
        }
        if indexPath.row == 3 {
            return 209
        }
        return 40
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
    }
    
}
