//
//  YHReAppointViewController.swift
//  galaxy
//
//  Created by edy on 2024/8/22.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

// 重新预约
class YHReAppointViewController: YHBaseViewController {

    var orderId: Int = 0
    var items:[YHAppointItem] = []

    var waitAppointMembers:[YHHKMemberModel] = []
    var viewModel = YHCerAppointViewModel()
    
    var updateBlock:(()->())?

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame:.zero, style:.grouped)
        tableView.estimatedSectionHeaderHeight = 16.0
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor(hex: 0xF8F9FB)
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateAppointOptionCell.self, forCellReuseIdentifier: YHCertificateAppointOptionCell.cellReuseIdentifier)
        tableView.register(YHSelectApplicantGroupCell.self, forCellReuseIdentifier: YHSelectApplicantGroupCell.cellReuseIdentifier)
        tableView.register(YHAppointWarmTipsCell.self, forCellReuseIdentifier: YHAppointWarmTipsCell.cellReuseIdentifier)
        tableView.register(YHGrabingNumberListCell.self, forCellReuseIdentifier: YHGrabingNumberListCell.cellReuseIdentifier)
        tableView.register(YHActivateHKVisaCell.self, forCellReuseIdentifier: YHActivateHKVisaCell.cellReuseIdentifier)
        tableView.register(YHWaitAppointMembersCell.self, forCellReuseIdentifier: YHWaitAppointMembersCell.cellReuseIdentifier)
        tableView.register(YHNoNeedAppointMembersCell.self, forCellReuseIdentifier: YHNoNeedAppointMembersCell.cellReuseIdentifier)
        tableView.register(YHHaveGrabbedNumberListCell.self, forCellReuseIdentifier: YHHaveGrabbedNumberListCell.cellReuseIdentifier)
        
        return tableView
    }()
    
    lazy var bottomBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("确认提交", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didBottomBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
    }
    
    func createUI() {
        
        super.viewDidLoad()
        self.gk_navTitle = "赴港办证预约"
        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.view.addSubview(bottomView)
        
        self.tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98.0)
        }
        
        updateData()
    }
    
    func updateData() {
        items.removeAll()
        // *温馨提示
        let item1 = YHAppointItem(type: .warmTips)
        items.append(item1)
        
        let item2 = YHAppointItem(type: .confirmGoHKInfo)
        item2.itemIndex = 0
        let group1 = YHSelectGroupMemberModel()
        group1.isAllMembersGoHK = true
        group1.isShowReAppointView = true
        group1.arr = waitAppointMembers
        item2.model = group1
        item2.placeList = self.viewModel.placeList
        item2.arrHkHolidays = self.viewModel.dataModelForHkHolidays?.legaldays ?? []
        items.append(item2)
        
        self.tableView.reloadData()
    }
    
    func getReAppointMemberNameText() -> String {
        var text = ""
        for (index, user) in self.waitAppointMembers.enumerated() {
            text += user.name
            if index != self.waitAppointMembers.count-1 {
                text += "、"
            }
        }
        text = "成员：\(text)"
        return text
    }
}

extension YHReAppointViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        
        if 0 <= indexPath.row, indexPath.row < items.count {
            let item = items[indexPath.row]
            if item.type == .warmTips {
                // 温馨提示
                let cell = tableView.dequeueReusableCell(withIdentifier: YHAppointWarmTipsCell.cellReuseIdentifier, for: indexPath) as! YHAppointWarmTipsCell
                return cell
            }
            if item.type == .confirmGoHKInfo {
                // 请您确认第X批赴港信息
                let cell = tableView.dequeueReusableCell(withIdentifier: YHSelectApplicantGroupCell.cellReuseIdentifier, for: indexPath) as! YHSelectApplicantGroupCell
                cell.repointMembersNameLabel.text = self.getReAppointMemberNameText()
                cell.dataModel = item
                cell.refreshBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    self.tableView.reloadData()
                }
                return cell
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        return view
    }
}

extension YHReAppointViewController {
    
    @objc func  didBottomBtnClicked() {
        
        // 检测各批次是否有日期或办证地点未选择
        var isOK = true
        for item in self.items {
            if item.type != .confirmGoHKInfo {
                continue
            }
            if let groupModel = item.model {
                if groupModel.dateTye == 0 { // 选择具体日期
                    if groupModel.detailDateStr.isEmpty {
                        groupModel.isNeedCheck = true
                        isOK = false
                    }

                } else { // 选择具体时段
                    if groupModel.startDateStr.isEmpty || groupModel.endDateStr.isEmpty {
                        groupModel.isNeedCheck = true
                        isOK = false
                    }
                }
                
                // 办证地点未选
                if groupModel.hkPlace.name.isEmpty {
                    groupModel.isNeedCheck = true
                    isOK = false
                }
            }
        }
        if !isOK { // 检测各批次是否有日期或办证地点未选择
            self.tableView.reloadData()
            return
        }
        
        var batchs:[[String: Any]] = []
        for group in items {
            if let model = group.model {
                var start_time = ""
                var end_time = ""
                if model.dateTye == 0 { // 具体时间
                    start_time = model.detailDateStr
                    end_time = model.detailDateStr
                    
                } else { // 具体时段
                    start_time = model.startDateStr
                    end_time = model.endDateStr
                }
                
                let selectUsers = model.arr.filter {
                    return $0.isSelected == true
                }
                let users = self.waitAppointMembers.map {
                    let dict = ["id" : $0.id,
                                "type" : $0.type,
                                "name" : $0.name] as! [String : Any]
                    return dict
                }
                
                if users.count > 0 {
                    let batch:[String : Any] = ["start_time" : start_time,
                                                "end_time" : end_time,
                                                "migration_office" : model.hkPlace.name,
                                                "users" : users]
                    batchs.append(batch)
                }
            }
        }
        
        // 请求参数
        let params:[String : Any] = ["order_id": orderId,
                                     "batch": batchs]
        
        printLog("\(params)")
        
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.submitAppoint(params: params) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            if success {
                YHHUD.flash(message: "提交成功")
                updateBlock?()
                self.navigationController?.popViewController()
                return
            }
            let msg = error?.errorMsg ?? ""
            YHHUD.flash(message: msg)
        }
    }
}

