//
//  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和orderId
    // 订单ID
    var orderId: Int = 0
    // 专业ID
    var detailId: Int = 0
    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: .grouped)
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 14.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor(hexString: "#F8F8F8")
        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()
        view.isHiddenSave = true
        view.changeRightBtnTitle("提交".local)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "专业资格及会员资格".local
        self.gk_navigationBar.backgroundColor = .white
        view.backgroundColor = UIColor(hexString: "#F8F8F8")
        createUI()
    }
    
    func createUI() {
        
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.saveBlock = {
            [weak self] in
            guard let self = self else { return }
            saveDetailInfo(isSubmit: false, isNeedPop: true, isShowToast: 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()
            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 != 0 { // 有专业ID则该专业已存在
            reqeustDetailInfo()
        }
    }
    
    func loadInfo() {
                
        items.removeAll()
        
        let title0 = YHFormTitleItem(type: .mainApplicantProfessionalQualification)
        let item00 = YHFormDetailItem(type: .qualificationCertificateName)
        item00.tips = "请选择资格证书名称".local
        item00.value = detailInfo.certName
        
        let item01 = YHFormDetailItem(type: .conferAgencyFullName)
        item01.tips = "请输入颁授机构".local
        item01.value = detailInfo.issuingAgent
        
        let item02 = YHFormDetailItem(type: .conferTime)
        item02.tips = "请选择颁授年份".local
        if detailInfo.issuingYear > 0 {
            item02.value = String(detailInfo.issuingYear)
        }
        
        let item03 = YHFormDetailItem(type: .conferCountry)
        item03.tips = "请选择颁授国家/地区".local
        item03.value = detailInfo.issuingAddr.country
        
        let item04 = YHFormDetailItem(type: .conferCity)
        if detailInfo.isCollegeInAboard() {
            item04.tips = "请输入颁授城市".local
            item04.value = detailInfo.issuingAddr.foreign
        } else {
            item04.tips = "请选择颁授城市".local
            item04.value = detailInfo.issuingAddr.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 { // 是标题
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemTitleCell.cellReuseIdentifier, for: indexPath) as? YHFormItemTitleCell else {
                return UITableViewCell()
            }
            if let formItem = item as? YHFormTitleItem {
                cell.setTitleAndSubTitle(title: formItem.getTitle())
            }
            return cell
        }
        
        if item is YHFormDetailItem {
            
            guard let detailItem = item as? YHFormDetailItem else { return UITableViewCell()}
            let cellType = getCellType(detailItem)
            if cellType == .inputText {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemInputTextCell.cellReuseIdentifier, for: indexPath) as? YHFormItemInputTextCell else {
                    return UITableViewCell()
                }
                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.textInputCondtion = {
                    textField in
                    
                    var max = -1
                    if detailItem.type == .conferAgencyFullName ||
                        detailItem.type == .conferCity {
                        max = 100
                    }

                    if max > 0 {
                        if let textStr = textField.text {
                            textField.text = (textStr.count > max ? textStr[safe: ..<max] : textStr)
                        }
                    }
                    return true
                }
                
                cell.textChange = {
                    [weak self] (text, isEditEnd) in
                    guard let self = self else { return }
                    // 只有国外城市才需输入，国内城市使用的是选择器
                    if detailItem.type == .conferCity {
                        
                        if let text = text, !text.isEmpty {
                            detailInfo.issuingAddr.foreign = text
                        } else {
                            detailInfo.issuingAddr.foreign = ""
                        }
                    } else if detailItem.type == .conferAgencyFullName {
                        if let text = text, !text.isEmpty {
                            detailInfo.issuingAgent = text
                        } else {
                            detailInfo.issuingAgent = ""
                        }
                    }
                    if isEditEnd {
                        loadInfo()
                        saveInfoSilent()
                    }
                }
                return cell
                
            } else if cellType == .selectSheet {
                
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHFormItemSelectSheetCell.cellReuseIdentifier, for: indexPath) as? YHFormItemSelectSheetCell else {
                    return UITableViewCell()
                }
                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 {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection 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 {
            guard let detailItem = item as? YHFormDetailItem else { return }
            
            if  detailItem.type == .qualificationCertificateName { // 资格证书名称
                
                YHSheetPickerView.show(type: .professionCertificate, selectTitle: detailInfo.certName) {
                    [weak self] selectItem in
                    guard let self = self else { return }
                    detailInfo.certName = selectItem.title
                    loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .conferTime { // 授权年份
                
                YHDatePickView.show(type: .yyyy, title: "选择授权年份".local, lastIsTaday: true, currentDay: "\(detailInfo.issuingYear)") {
                    [weak self] dateStr in
                    guard let self = self else { return }
                    
                    let format = DateFormatter()
                    format.dateFormat = "yyyy"
                    if let selectDate = format.date(from: dateStr) {
                        let selectTimeInterval = selectDate.timeIntervalSince1970
                        let currentTimeInterval = Date().timeIntervalSince1970
                        // 出生日期须早于当前日期
                        if selectTimeInterval > currentTimeInterval {
                            YHHUD.flash(message: "授权年份不能晚于当前年份".local)
                            return
                        }
                    }
                    
                    detailInfo.issuingYear = Int(dateStr) ?? 2024
                    loadInfo()
                    saveInfoSilent()
                }
                
            } else if detailItem.type == .conferCountry { // 授权国家/地区
                
                let vc = YHSelectCountryViewController()
                vc.backLocationStringController = {
                    [weak self] country in
                    guard let self = self else { return }
                    detailInfo.issuingAddr.country = country
                    detailInfo.isAboardAddr = detailInfo.isCollegeInAboard()
                    loadInfo()
                    saveInfoSilent()
                }
                self.navigationController?.pushViewController(vc)
                
            } else if detailItem.type == .conferCity { // 授权城市
                
                if detailInfo.isCollegeInAboard() { return }
                
                let vc = YHAddressViewController()
                vc.backLocationStringController = {
                    [weak self] (_, string2, string3, _) in
                    guard let self = self else { return }
                    var citys: [String] = []
                    if !isEmptyString(string2) {
                        citys.append(string2)
                    }
                    if !isEmptyString(string3) {
                        citys.append(string3)
                    }
                    detailInfo.issuingAddr.area = citys
                    loadInfo()
                    saveInfoSilent()
                }
                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: [Any], indexPath: IndexPath) {
        // 设置每块section圆角
        if indexPath.row == 0 {
            let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else if indexPath.row == arr.count-1 {
            let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
            cell.createCorner(CGSize(width: 12.0, height: 12.0), corner)
            
        } else {
            cell.layer.mask = nil
        }
    }
    
    func getCellType(_ item: Any) -> HKFormItemCellType {
        if item is YHFormTitleItem {
            return .title
        }
        
        if item is YHFormDetailItem {
            guard let detailItem = item as? YHFormDetailItem else {
                return .defaultType
            }
            
            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, _ in
            guard let self = self else { return }
            if success {
                if let qualificationDetailInfo = self.educationRequest.qualificationDetailInfo {
                    detailInfo = qualificationDetailInfo
                }
                loadInfo()
            }
        }
    }
    
    func saveInfoSilent() {
        if detailId != 0 {
            saveDetailInfo(isSubmit: false, isNeedPop: false, isShowToast: false)
        }
    }
    
    // 保存数据 
    // @param isNeedPop：保存成功后是否需要退出该页面
    // @param isShowToast: 请求完成后是否弹Toast
    func saveDetailInfo(isSubmit: Bool, isNeedPop: Bool, isShowToast: Bool) {
        
        var dict: [String: Any] = ["orderId": self.orderId]
        detailInfo.isAboardAddr = detailInfo.isCollegeInAboard()
        let quaDict: [String: Any] = detailInfo.toDictionary() ?? [:]
        dict["qua_data"] = quaDict
        
        print(dict)
        
        self.educationRequest.saveQualificationInfo(params: dict, isSilent: !isShowToast) {
            [weak self] success, error in
            guard let self = self else { return }
            if success {
                if isShowToast {
                    YHHUD.flash(message: isSubmit ? "提交成功":"保存成功" )
                }
                if isNeedPop {
                    self.navigationController?.popViewController(animated: true)
                }
                
            } else {
                if isShowToast {
                    var errorMsg = isSubmit ? "提交失败" : "保存失败"
                    if let errMsg = error?.errorMsg, errMsg.count > 0 {
                        errorMsg = errMsg
                    }
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
    
    func submitInfo() {
        let isChecked = checkIntegrity()
        isNeedShowError = !isChecked
        
        self.tableView .reloadData()
        
        if !isChecked {
            YHHUD.flash(message: "资料还未填完")
            return
        }
        
        saveDetailInfo(isSubmit: true, isNeedPop: true, isShowToast: true)

    }
    
    // 检查填写信息完整性
    func checkIntegrity() -> Bool {
        
        if detailInfo.certName.isEmpty
            || detailInfo.issuingAgent.isEmpty
            || detailInfo.issuingYear <= 0
            || detailInfo.issuingAddr.country.isEmpty {
            return false
        }
        
        if detailInfo.isCollegeInAboard(), detailInfo.issuingAddr.foreign.isEmpty {
            return false
        }
        
        if !detailInfo.isCollegeInAboard(), detailInfo.issuingAddr.area.count <= 0 {
            return false
        }
        return true
    }
}
