//
//  YHProfessionalQualificationVC.swift
//  galaxy
//
//  Created by edy on 2024/2/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Toast_Swift

class YHQualificationDetailVC: YHBaseViewController {
    
    //【WARNING!】新添加 传orderId 已有信息传detailId
    // 订单ID
    var orderId: String = ""
    // 专业ID
    var detailId: String = ""
    let educationRequest:YHEducationRequestViewModel = YHEducationRequestViewModel()
    // 专业详情信息
    var detailInfo =  YHQualificationDetailInfo()
    var isChildsEditMode: YHFormTitleItemEditType = .none
    var isBrothersEditMode: YHFormTitleItemEditType = .none
    // 是否显示未填写错误提示
    var isNeedShowError = false
    var items:[[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(YHFormItemTitleCell.self, forCellReuseIdentifier: YHFormItemTitleCell.cellReuseIdentifier)
        tableView.register(YHFormItemAddCell.self, forCellReuseIdentifier: YHFormItemAddCell.cellReuseIdentifier)
        tableView.register(YHFormItemInputTextCell.self, forCellReuseIdentifier: YHFormItemInputTextCell.cellReuseIdentifier)
        tableView.register(YHFormItemSelectSheetCell.self, forCellReuseIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier)
        return tableView
    }()
    
    var bottomView: YHSaveAndSubmitView = {
        let view = YHSaveAndSubmitView.createView()
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "专业资格及会员资格".local
        view.backgroundColor = UIColor(hexString:"#F8F8F8")
        createUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func createUI() {
        
        view.addSubview(tableView);
        view.addSubview(bottomView)
        bottomView.saveBlock = {
            [weak self] in
            guard let self = self else { return }
            saveDetailInfo(isNeedPop: true)
        }
        bottomView.submitBlock = {
            [weak self] in
            guard let self = self else { return }
            submitInfo()
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-k_Height_safeAreaInsetsBottom())
            make.height.equalTo(YHSaveAndSubmitView.height)
        }
        
        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)
        }
        
        loadInfo()
        if !self.detailId.isEmpty { // 有专业ID则该专业已存在
            reqeustDetailInfo()
        } else { // 该专业是新添加的
            detailInfo.orderId = orderId
        }
    }
    
    func loadInfo() {
                
        items.removeAll()
        
        let title0 = YHFormTitleItem(type: .mainApplicantProfessionalQualification)
        let item00 = YHFormDetailItem(type: .qualificationCertificateName)
        item00.placeHolder = "请选择资格证书名称".local
        item00.tips = "请选择资格证书名称".local
        item00.value = detailInfo.qualification
        
        let item01 = YHFormDetailItem(type: .conferAgencyFullName)
        item01.placeHolder = "请输入颁授机构".local
        item01.tips = "请输入颁授机构".local
        item01.value = detailInfo.college
        
        let item02 = YHFormDetailItem(type: .conferTime)
        item02.placeHolder = "请选择颁授年份".local
        item02.tips = "请选择颁授年份".local
        item02.value = detailInfo.promulgation
        
        let item03 = YHFormDetailItem(type: .conferCountry)
        item03.placeHolder = "请选择颁授国家/地区".local
        item02.tips = "请选择颁授国家/地区".local
        item03.value = detailInfo.collegeAddress.country
        
        let item04 = YHFormDetailItem(type: .conferCity)
        if detailInfo.isCollegeInAboard() {
            item04.placeHolder = "请输入颁授城市".local
            item04.tips = "请输入颁授城市".local
            item04.value = detailInfo.collegeAddress.foreign
        } else {
            item04.placeHolder = "请选择颁授城市".local
            item04.tips = "请选择颁授城市".local
            item04.value = detailInfo.collegeAddress.area.joined(separator: ",")
        }
        
        let arr0:[YHFormItemProtocol] = [title0, item00, item01, item02, item03, item04]
        items.append(arr0)
        self.tableView.reloadData()
    }
    
}

extension YHQualificationDetailVC : 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 formItem = item as! YHFormTitleItem
            let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as! YHFormItemTitleCell
            cell.setTitleAndSubTitle(title:formItem.getTitle())
            return cell
        }
        
        if item is YHFormDetailItem {
            
            let detailItem = item as! YHFormDetailItem
            let cellType = getCellType(detailItem)
            if cellType == .inputText {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as! YHFormItemInputTextCell
                var isValueValid = false
                if let value = detailItem.value, !value.isEmpty {
                    isValueValid = true
                }
                cell.setTips(detailItem.tips, isShow: (isNeedShowError && !isValueValid))
                cell.placeHolder = detailItem.placeHolder
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.text = detailItem.value
                cell.textChange = {
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    // 只有国外城市才需输入，国内城市使用的是选择器
                    if detailItem.type == .conferCity {
                        
                        if let text = text, !text.isEmpty {
                            detailInfo.collegeAddress.foreign = text
                        } else {
                            detailInfo.collegeAddress.foreign = ""
                        }
                    } else if detailItem.type == .conferAgencyFullName {
                        if let text = text, !text.isEmpty {
                            detailInfo.college = text
                        } else {
                            detailInfo.college = ""
                        }
                    }
                    if isEditEnd {
                        loadInfo()
                        if !detailId.isEmpty {
                            saveDetailInfo(isNeedPop: false)
                        }
                    }
                }
                return cell
                
            } else if cellType == .selectSheet {
                
                let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as! YHFormItemSelectSheetCell
                cell.placeHolder = detailItem.placeHolder
                var isValueValid = false
                if let value = detailItem.value, !value.isEmpty {
                    isValueValid = true
                }
                cell.setTips(detailItem.tips, isShow: (isNeedShowError && !isValueValid))
                cell.isMust = detailItem.isNeed
                cell.title = detailItem.getTitle()
                cell.detail = detailItem.value
                return cell
            }
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
    
    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 tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let arr = items[indexPath.section]
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        if item is YHFormTitleItem { // 是标题
            return 52.0
        }
        return UITableView.automaticDimension
    }
    
    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 arr = items[indexPath.section]
        let item:YHFormItemProtocol = arr[indexPath.row]
        
        // 标题
        if item is YHFormTitleItem {
            return
        }
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if  detailItem.type == .qualificationCertificateName { // 资格证书名称
                YHFormPickerView.show(type: .professionCertificate, selectType: .professionCertificate(.ACA)) {
                    
                    [weak self] selectType in
                    guard let self = self else { return }
                    detailInfo.qualification = selectType.title
                    loadInfo()
                    if !detailId.isEmpty {
                        saveDetailInfo(isNeedPop: false)
                    }
                }
                
            } else if detailItem.type == .conferTime { // 授权年份
                
                YHDatePickView.show(type: .yyyy) {
                    [weak self] date in
                    guard let self = self else { return }
                    detailInfo.promulgation = date
                    loadInfo()
                    if !detailId.isEmpty {
                        saveDetailInfo(isNeedPop: false)
                    }
                }
                
            } else if detailItem.type == .conferCountry { // 授权国家/地区
                
                let vc = YHSelectCountryViewController()
                 vc.backLocationStringController = {
                     [weak self] country in
                     guard let self = self else { return }
                     detailInfo.collegeAddress.country = country
                     loadInfo()
                     if !detailId.isEmpty {
                         saveDetailInfo(isNeedPop: false)
                     }
                 }
                 self.navigationController?.pushViewController(vc)
                
            } else if detailItem.type == .conferCity { // 授权城市
                
                if detailInfo.isCollegeInAboard() { return }
                    
                let vc = YHAddressViewController()
                vc.backLocationStringController = {
                     [weak self] (string1, string2, string3, string4) in
                     guard let self = self else { return }
                     detailInfo.collegeAddress.area = [string1, string2, string3, string4]
                     loadInfo()
                    if !detailId.isEmpty {
                        saveDetailInfo(isNeedPop: false)
                    }
                 }
                self.present(vc, animated: true)
            }
        }
    }
    
    func createDefaultCell(_ indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return cell
    }
        
    func createCorner(cell:UITableViewCell, arr:Array<Any>, indexPath:IndexPath) {
        // 设置每块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
        }
    }
    
    func getCellType(_ item: Any) ->HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            let detailItem = item as! YHFormDetailItem
            
            if detailItem.type == .conferCity {
                if detailInfo.isCollegeInAboard() {
                    return .inputText
                }
                return .selectSheet
            }
            
            if detailItem.type == .conferAgencyFullName {
                return .inputText
            }
            
            if detailItem.type == .conferTime
                || detailItem.type == .conferCountry
                || detailItem.type == .conferCity 
                || detailItem.type == .qualificationCertificateName{
                
                return .selectSheet
            }
        }
        return .defaultType
    }
}

extension YHQualificationDetailVC {
    
    func reqeustDetailInfo() {
        self.educationRequest.getQualificationDetailInfo(id:self.detailId) {
            [weak self] success, error in
            guard let self = self else { return }
            if success {
                if let qualificationDetailInfo = self.educationRequest.qualificationDetailInfo {
                    detailInfo = qualificationDetailInfo
                }
                loadInfo()
            }
        }
    }
    
    // 保存数据 isNeedPop：保存成功后是否需要退出该页面
    func saveDetailInfo(isNeedPop:Bool) {
        
        var dict:[String : Any] = [:]
        if detailId.isEmpty { // 新增数据
            dict = ["verify" : 0,
                    "college":detailInfo.college,
                    "college_address_aboard":"",
                    "id":"",
                    "order_id" : detailInfo.orderId,
                    "promulgation" : detailInfo.promulgation,
                    "qualification" : detailInfo.qualification,
                    "college_address":["area":[],
                                       "country":"",
                                       "details":"",
                                       "foreign":""]]
            
        } else { // 已有数据
            dict = detailInfo.toDictionary() ?? [:]
            dict["verify"] = 0
        }
        
        print(dict)
        
        self.educationRequest.saveQualificationInfo(params: dict) {
            [weak self] success, error in
            guard let self = self else { return }
            if success {
                YHHUD.flash(message: "保存成功")
                if isNeedPop {
                    self.navigationController?.popViewController(animated: true)
                }
                
            } else {
                YHHUD.flash(message: "保存失败")
            }
        }
    }
    
    func submitInfo() {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        self.tableView .reloadData()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return
        }
        saveDetailInfo(isNeedPop: true)
    }
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        if detailInfo.qualification.isEmpty 
            || detailInfo.college.isEmpty
            || detailInfo.promulgation.isEmpty
            || detailInfo.collegeAddress.country.isEmpty
        {
            return false
        }
        
        if detailInfo.isCollegeInAboard(), detailInfo.collegeAddress.foreign.isEmpty {
            return false
        }
        
        if !detailInfo.isCollegeInAboard(), detailInfo.collegeAddress.area.count <= 0 {
            return false
        }
        return true
    }
}

