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

import UIKit

class YHChildInitialInfoVC: YHBaseViewController {

    var child:YHFamilyMember?
    
    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(YHFormItemDoubleChoiceCell.self, forCellReuseIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier)
        tableView.register(YHFormItemInputTextCell.self, forCellReuseIdentifier: YHFormItemInputTextCell.cellReuseIdentifier)
        tableView.register(YHFormItemEnterDetailCell.self, forCellReuseIdentifier: YHFormItemEnterDetailCell.cellReuseIdentifier)
        tableView.register(YHFormItemTitleCell.self, forCellReuseIdentifier: YHFormItemTitleCell.cellReuseIdentifier)
        tableView.register(YHFormItemAddCell.self, forCellReuseIdentifier: YHFormItemAddCell.cellReuseIdentifier)
        tableView.register(YHFormItemQuestionCell.self, forCellReuseIdentifier: YHFormItemQuestionCell.cellReuseIdentifier)
        tableView.register(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    lazy var submitBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("提交".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(.white, for: .normal)
        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()
        btn.setTitle("保存", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_R(ofSize: 14)
        btn.setTitleColor(UIColor(hexString:"#222222"), for: .normal)
        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 child = child else { return }
        
        items.removeAll()

        // 随行
        let title0 = YHFormTitleItem(type: .accompany)
        let item00 = YHFormDetailItem(type: .ownCustody)
        let item01 = YHFormDetailItem(type: .birthday)
        let item02 = YHFormDetailItem(type: .isAccompanyToHK)
        item02.value = String(child.follow == 1)
        let arr0:[YHFormItemProtocol] = [title0, item00, item01, item02]
        items.append(arr0)
        
        if child.isFollow() { // 随行才加后面的信息
            // 国籍
            let title1 = YHFormTitleItem(type: .country)
            let item10 = YHFormDetailItem(type: .nationOrArea)
            let arr1:[YHFormItemProtocol] = [title1, item10]
            
            // 居住信息
            let title2 = YHFormTitleItem(type: .liveInfo)
            let item20 = YHFormDetailItem(type: .isLiveTother)
            item20.value = String(child.isLiveTother())
            let item21 = YHFormDetailItem(type: .nationOrArea)
            let item22 = YHFormDetailItem(type: .liveCity)
            let item23 = YHFormDetailItem(type: .detailAddress)
            let arr2:[YHFormItemProtocol] = [title2, item20, item21, item22, item23]
            
            // 港澳通信证
            let title3 = YHFormTitleItem(type: .hkAndMacaoPassport)
            let item30 = YHFormDetailItem(type: .isHandleHKPassPort)
            item30.value = String(child.isNeedHandleHKPassPort())
            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 YHChildInitialInfoVC : 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: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.titleLabel.text = item.getTitle()
            return cell
            
        } else if item is YHFormDetailItem { // 具体信息
            
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .isAccompanyToHK || detailItem.type == .isHandleHKPassPort || detailItem.type == .isLiveTother {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemDoubleChoiceCell.cellReuseIdentifier, for: indexPath) as! YHFormItemDoubleChoiceCell
                cell.title = detailItem.getTitle()
                
                var select = false
                if let value = detailItem.value {
                   select = Bool(value)!
                }
                
                let answers = [YHFormChoiceItem(title: "是".local, isSelect: select),YHFormChoiceItem(title: "否".local, isSelect: !select)]
                cell.answerArr = answers
                            
                cell.answerBlock = {
                    
                    [weak self]  (arr, selectIndex) in
                    
                    let selectItem:YHFormChoiceItem = arr[selectIndex]
                    
                    if detailItem.type == .isAccompanyToHK { // 是否随行
                        let follow = (selectItem.title == "是".local ? 1 : 0)
                        self?.child?.follow = follow
                        self?.loadSponseInfo()
                        
                    } else if detailItem.type == .isHandleHKPassPort { // 是否办理港澳通行证
                        let handlePassport = (selectItem.title == "是".local ? 1 : 0)
                        self?.child?.isHandled = handlePassport
                        self?.loadSponseInfo()
                        
                    } else if detailItem.type == .isLiveTother { // 是否与主申请人同住
                        let isLiveTother = (selectItem.title == "是".local ? 1 : 0)
                        self?.child?.finishFollow = (selectItem.title == "是".local ? 1 : 0)
                        self?.loadSponseInfo()
                    }
                }
                return cell
                
            } else if detailItem.type == .nationOrArea || detailItem.type == .nationOrArea || detailItem.type == .liveCity || detailItem.type == .detailAddress || detailItem.type == .birthday {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                return cell
                
            } else if detailItem.type == .ownCustody {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemQuestionCell.cellReuseIdentifier, for: indexPath) as! YHFormItemQuestionCell
                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 == .isAccompanyToHK ||
                detailItem.type == .isHandleHKPassPort ||
                detailItem.type == .ownCustody
            {
                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) {

        let vc = YHChildBasicInfoVC()
        self.navigationController?.pushViewController(vc)
    }
        
    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
        }
    }
}

