//
//  YHConsortFormVC.swift
//  galaxy
//
//  Created by edy on 2024/1/23.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSpouseFormVC: YHBaseViewController {
    
    var spouse:YHSpouse?
    
    lazy var items:[[YHFormItemProtocol]] = [[YHFormItemProtocol]]()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.plain)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHDoubleChoiceFormCell.self, forCellReuseIdentifier: YHDoubleChoiceFormCell.cellReuseIdentifier)
        tableView.register(YHSingleLineInputCell.self, forCellReuseIdentifier: YHSingleLineInputCell.cellReuseIdentifier)
        tableView.register(YHSingleLineSelectCell.self, forCellReuseIdentifier: YHSingleLineSelectCell.cellReuseIdentifier)
        tableView.register(YHFormTitleCell.self, forCellReuseIdentifier: YHFormTitleCell.cellReuseIdentifier)
        tableView.register(YHFormAddInfoCell.self, forCellReuseIdentifier: YHFormAddInfoCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var submitBtn:UIButton = {
        let btn = UIButton.bs_button(title: "提交".local, font: UIFont.PFSCR(ofSize: 14), normalColor: .white)
        btn.backgroundColor = UIColor(hexString:"#4388FF")
        btn.layer.cornerRadius = 8.0
        btn.addTarget(self, action: #selector(didClickSubmitBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var saveBtn:UIButton = {
        let btn = UIButton.bs_button(title: "保存".local, font: UIFont.PFSCR(ofSize: 14), normalColor: UIColor(hexString:"#222222"))
        btn.backgroundColor = UIColor(hexString:"#F8F9FB")
        btn.layer.cornerRadius = 8.0
        btn.addTarget(self, action: #selector(didClickSaveBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var bottomView:UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(submitBtn)
        view.addSubview(saveBtn)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "配偶信息填写".local
        createUI()
        loadSponseInfo()
    }
    
    func loadSponseInfo() {
                        
        guard let spouse = spouse else { return }
        
        items.removeAll()

        // 随行
        let title0 = YHFormTitleItem(type: .accompany)
        let item0 = YHFormDetailItem(type: .accompany)
        item0.isAccompany = (spouse.follow == 1)
        let arr0:[YHFormItemProtocol] = [title0, item0]
        items.append(arr0)
        
        if item0.isAccompany { // 随行才加后面的信息
            // 国籍
            let title1 = YHFormTitleItem(type: .country)
            let item10 = YHFormDetailItem(type: .country)
            item10.country = "中国"
            let arr1:[YHFormItemProtocol] = [title1, item10]
            
            // 居住信息
            let title2 = YHFormTitleItem(type: .liveInfo)
            let item20 = YHFormDetailItem(type: .isLiveTother)
            let item21 = YHFormDetailItem(type: .liveContry)
            let item22 = YHFormDetailItem(type: .liveCity)
            let item23 = YHFormDetailItem(type: .detailAddress)
            let arr2:[YHFormItemProtocol] = [title2, item20, item21, item22, item23]
            
            // 港澳通信证
            let title3 = YHFormTitleItem(type: .hkPassport)
            let item30 = YHFormDetailItem(type: .hkPassport)
            let arr3:[YHFormItemProtocol] = [title3, item30]

            items.append(contentsOf:[arr1, arr2, arr3])

        }

        tableView.reloadData()
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        view.addSubview(bottomView)
        
        let submitBtnHeight = 48.0
        let gap = 8.0
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view)
            make.height.equalTo(submitBtnHeight+gap*2+k_Height_safeAreaInsetsBottom())
        }
        
        saveBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.size.equalTo(CGSize(width: 86.0, height: 48.0))
            make.top.equalTo(8)
        }
        
        submitBtn.snp.makeConstraints { make in
            make.left.equalTo(saveBtn.snp.right).offset(10)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48)
            make.centerY.equalTo(saveBtn)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
    }
    
    @objc func didClickSubmitBtn() {
        
    }
    
    @objc func didClickSaveBtn() {
        
    }
}


extension YHSpouseFormVC : UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section >= items.count { return 0 }
        let arr = items[section]
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section >= items.count { return createDefaultCell(indexPath) }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return createDefaultCell(indexPath) }
        
        
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 标题
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormTitleCell
            cell.titleLabel.text = item.getTitle()
            return cell
            
        } else if item is YHFormDetailItem { // 具体信息
            
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .accompany || detailItem.type == .hkPassport {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDoubleChoiceFormCell.cellReuseIdentifier, for: indexPath) as! YHDoubleChoiceFormCell
                cell.title = detailItem.getTitle()
                
                if detailItem.type == .accompany {
                    cell.response = detailItem.isAccompany
                } else if detailItem.type == .hkPassport {
                    
                }
                cell.responseBlock = {
                    
                    [weak self]  choice in
                    
                    if detailItem.type == .accompany {
                        self?.spouse?.follow = (choice ? 1 : 0)
                        self?.loadSponseInfo()
                        
                    } else if detailItem.type == .hkPassport {
                
                    }
                    
                }
                return cell
                
            } else if detailItem.type == .isLiveTother || detailItem.isHongKongMacouPassport {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHDoubleChoiceFormCell.cellReuseIdentifier, for: indexPath) as! YHDoubleChoiceFormCell
                cell.title = detailItem.getTitle()
                return cell
                
            } else if detailItem.type == .country || detailItem.type == .liveContry || detailItem.type == .liveCity || detailItem.type == .detailAddress {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHSingleLineSelectCell.cellReuseIdentifier, for: indexPath) as! YHSingleLineSelectCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                return cell
            }
        }
        
        return createDefaultCell(indexPath)
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.section >= items.count { return  }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return }
        
        createCorner(cell: cell, arr: arr, indexPath: indexPath)
    }
    
    func createDefaultCell(_ indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section >= items.count { return 0.0 }
        let arr:[YHFormItemProtocol] = items[indexPath.section]
        if indexPath.row >= arr.count {  return 0.0 }
        
        let item = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 标题
            return 52.0
        }
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            if detailItem.type == .isLiveTother ||
                detailItem.type == .accompany ||
                detailItem.type == .hkPassport
            {
                return UITableView.automaticDimension
            }
        }
        return 52.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 14.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
        
    func createCorner(cell:UITableViewCell, arr:Array<Any>, indexPath:IndexPath) {
        // 复用时需清理
        cell.layer.mask = nil
        // 设置每块section圆角
        if (indexPath.row == 0) {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else if (indexPath.row == arr.count-1) {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSizeMake(12.0, 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
}

