//
//  YHResignAppointSubmitScheduleViewController.swift
//  galaxy
//
//  Created by edy on 2024/10/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResignAppointScheduleListViewController: YHBaseViewController {

    // 订单ID
    var orderId: Int = 0
    // 批次ID
    var renewalId: Int = 0

    let viewModel = YHResignAppointViewModel()
    var isTogether: Int = 0  // 0单人 1一起 2分批
    var result_open: Bool = false // 是否可以下一步，去查看递交凭证
    
    var scheduleArr: [YHResignAppointGroup] = [] {
        didSet {
            self.tableView.reloadData()
            self.updateBottomBtnAndMotifyBtnStatus()
        }
    }
    
    // 所有未预约人员
    var allAppointUsers: [YHResignAppointMember] = []
    
    // 是否隐藏修改按钮
    var isHiddenModifyBtn: Bool = false

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style:.grouped)
        if #available(iOS 15.0, *) {
           tableView.sectionHeaderTopPadding = 0.0
        }
        tableView.estimatedSectionHeaderHeight = 0.1
        tableView.estimatedSectionFooterHeight = 0.1
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.bounces = false

        tableView.register(YHResignScheduleMultipleInfoCell.self, forCellReuseIdentifier: YHResignScheduleMultipleInfoCell.cellReuseIdentifier)
        tableView.register(YHResignScheduleSingleInfoCell.self, forCellReuseIdentifier: YHResignScheduleSingleInfoCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var guideBtn: UIButton = {
        let button = UIButton()
        button.setTitle("在港递交指引", for: .normal)
        button.titleLabel?.font = .PFSC_R(ofSize: 11)
        button.setTitleColor(UIColor.mainTextColor, for: .normal)
        button.setImage(UIImage(named: "resign_appint_guide"), for: .normal)
        button.centerTextAndImage(imageAboveText: true, spacing: 0.0)
        button.addTarget(self, action: #selector(didGuideBtnClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var nextBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("下一步，去查看递交凭证", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        btn.addTarget(self, action: #selector(didNextBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(guideBtn)
        view.addSubview(nextBtn)
        guideBtn.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.width.equalTo(66)
            make.height.equalTo(43)
            make.centerY.equalTo(nextBtn)
        }
        nextBtn.snp.makeConstraints { make in
            make.left.equalTo(guideBtn.snp.right).offset(20)
            make.right.equalTo(-20)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = "续签在港递交行程安排"
        self.gk_navigationBar.backgroundColor = .white
        self.view.backgroundColor = .init(hex: 0xF8F9FB)
        self.view.addSubview(tableView)
        self.view.addSubview(bottomView)
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+16)
            make.bottom.equalTo(bottomView.snp.top)
        }
        self.bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(98)
        }
        self.tableView.reloadData()
        self.updateBottomBtnAndMotifyBtnStatus()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestList()
        
    }
    
    @objc func didNextBtnClicked() {
        //查看续签结果
        let vc = YHLookResignResultViewController()
        vc.orderId = orderId
        vc.batchId = renewalId
        self.navigationController?.pushViewController(vc)
    }
    
    func firstShowGuideSheetView() {
        
        let key = "resignGuideLine_is_first_watch_\(renewalId)"
        if let isHaveFirstShow = UserDefaults.standard.value(forKey: key) as? Bool, isHaveFirstShow == true {
            
        } else {
            showGuideSheetView()
            UserDefaults.standard.set(true, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }
    
    func showGuideSheetView() {
        
        let key = "resignGuideLine_watch_\(renewalId)"
        let view = YHResignAppointGuideLineView.sheetView()
        if let isWatched = UserDefaults.standard.value(forKey: key) as? Bool, isWatched == true {
            view.ischeckBeforeFlag = true
        } else {
            view.ischeckBeforeFlag = false
            UserDefaults.standard.set(true, forKey: key)
            UserDefaults.standard.synchronize()
        }
        view.block = {
            
        }
        view.show()
    }
    
    @objc func didGuideBtnClicked() {
        self.showGuideSheetView()
    }
    
    // 更新底部下一步按钮点击状态
    func updateBottomBtnAndMotifyBtnStatus() {
        let isCanNextStep = self.result_open
        self.nextBtn.isUserInteractionEnabled = isCanNextStep
        self.nextBtn.alpha = isCanNextStep ? 1.0 : 0.3
        
        // 所有分批都已确认在港 则无需修改了
        self.isHiddenModifyBtn = self.isAllHaveHaveConfirmInHK()
        self.tableView.reloadData()
    }
    
    func clickConfirmHKButton(status: YHResignConfirmHKStatus, _ model: YHResignAppointGroup) {
        if status == .waitConfirmHK { // 待确认在港
           // 展示提前到港弹窗
           let alert = YHForwardArriveHKAlertView.alertView()
           alert.confirmBlock = {
               [weak self] isConfirm in
               guard let self = self else { return }
               if isConfirm {
                   // 去修改预约递交时间
                   self.modifySchedule()
               }
           }
           alert.show()
            
        } else if status == .canConfirmHK { // 可点击确认在港
            let alertView = YHResignAppointedScheduleRiskTipsView.alertView()
            alertView.bottomBtnBlock = {
                [weak self] isSure in
                guard let self = self else { return }
                if isSure {
                    self.requestConfirmInHK(model)
                }
            }
            alertView.show()
        }
    }
    
    // 修改行程
    @objc func modifySchedule() {
        // 是否只有一个人
        var isOnlyOneUser = true
        // 是否只有一批
        var isOnlyOneGroup = true
        
        if scheduleArr.count > 1 {
            isOnlyOneUser = false
            isOnlyOneGroup = false
            
        } else {
            // 只有一批
            isOnlyOneGroup = true
            if scheduleArr.count > 0 {
                let group = scheduleArr[0]
                isOnlyOneUser = group.user_list.count <= 1
            }
        }
        
        if isOnlyOneUser { // 只有一个人
            if scheduleArr.count > 0 {
                // 先得到所有分批用户的集合
                YHHUD.show(.progress(message: "加载中..."))
                self.viewModel.getResignAppointUserlist(renewalId: self.renewalId) {
                    [weak self] success, error in
                    YHHUD.hide()
                    guard let self = self else { return }
                    let group = scheduleArr[0]
                    let vc = YHResignAppointTimeViewController()
                    vc.isUpdate = true
                    vc.renewalId = self.renewalId
                    vc.togetherSetting.isCanEdit = false
                    vc.togetherSetting.is_together = self.isTogether
                    vc.defaultSubmitTime = group.ready_to_submit_at
                    vc.defaultLeaveHKTime = group.leave_hk_at
                    vc.allAppointUsers = self.viewModel.appointUsers
                    self.navigationController?.pushViewController(vc)
                }
            }
            return
        }
        
        // 以下是多人的情况
        // 先得到所有分批用户的集合
        YHHUD.show(.progress(message: "加载中..."))
        self.viewModel.getResignAppointUserlist(renewalId: self.renewalId) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            
            if !success {
                let msg = error?.errorMsg ?? ""
                YHHUD.flash(message: msg)
                return
            }
            
            let appAppointUsers = self.viewModel.appointUsers
            
            // 组装数据
            // 上一个批次中未选中的用户集合
            var lastLeftUnselectUsers: [YHResignAppointMember] = appAppointUsers.deepCopy()
            
            var groupArr = [YHResignAppointTimeSettingModel]()
            var targetIndex: Int = 0
            
            for (index, group) in scheduleArr.enumerated() {
                
                targetIndex = index
                let model = YHResignAppointTimeSettingModel()
                let status = group.getConfirmInHKStatus()
                model.isHaveAppointed = (status == .haveConfirmHK)
                model.ready_to_submit_at = group.ready_to_submit_at
                model.leave_hk_at = group.leave_hk_at
                model.notleaveHK = group.leave_hk_at.isEmpty
                model.itemIndex = index
                
                if status != .haveConfirmHK { // 非已确认在港
                    // 先讲所有需分批用户设置为未选择状态
                    let users = lastLeftUnselectUsers.map {
                        let m = $0.copy() as! YHResignAppointMember
                        m.isSelected = false
                        return m
                    }
                    
                    // group.user_list 表示当前批已选用户组 更新已选择状态
                    for selectUser in group.user_list {
                        for user in users {
                            if user.id == selectUser.memberId {
                                user.isSelected = true
                                break
                            }
                        }
                    }
                    model.users = users
                    if users.count > 0 {
                        groupArr.append(model)
                    }
                    
                    lastLeftUnselectUsers = users.filter {
                        return $0.isSelected == false
                    }.deepCopy()
                    
                } else { // 已确认在港
                    
                    let users = group.user_list.map {
                        return $0.transformToMember()
                    }
                    
                    model.users = users
                    groupArr.append(model)
                    
                    lastLeftUnselectUsers = lastLeftUnselectUsers.filter {
                        for model in group.user_list {
                            if model.memberId == $0.id { // 该用户已经选择过
                                return false
                            }
                        }
                        return true
                    }.deepCopy()
                }
            }
            
            if lastLeftUnselectUsers.count > 0 { // 如果还有剩余的人 这批人不在行程列表里 可能是在后台随意操作删除用户的
                let model = YHResignAppointTimeSettingModel()
                let status = YHResignConfirmHKStatus.waitConfirmHK
                model.isHaveAppointed = false
                model.ready_to_submit_at = ""
                model.leave_hk_at = ""
                model.notleaveHK = false
                model.itemIndex = targetIndex+1
                
                let users = lastLeftUnselectUsers.map {
                    let m = $0.copy() as! YHResignAppointMember
                    m.isSelected = true
                    return m
                }
                model.users = users
                groupArr.append(model)
            }
            
            let modifyVC = YHResignAppointTimeModifyViewController()
            modifyVC.renewalId = self.renewalId
            modifyVC.selectGroupArr = groupArr
            modifyVC.allAppointUsers = appAppointUsers.deepCopy()
            
            if scheduleArr.count == 1 { // 只有一批
                let group = scheduleArr[0]
                modifyVC.oneGroupTimeSetting.ready_to_submit_at = group.ready_to_submit_at
                modifyVC.oneGroupTimeSetting.leave_hk_at = group.leave_hk_at
                modifyVC.oneGroupTimeSetting.notleaveHK = group.leave_hk_at.isEmpty
            }
            
            // 只要有一个已确认在港则不能再编辑是否一起递交
            modifyVC.isCanEditTogether = !self.isAtLeastOneHeaveConfirmInHK()
            modifyVC.isTogether = (self.isTogether == 1)
            self.navigationController?.pushViewController(modifyVC)
        }
    }
    
    func isAllHaveHaveConfirmInHK() -> Bool { // 是否所有行程安排都已确认在港
        var isAllHaveConfirmed = true
        for group in scheduleArr {
            let status = group.getConfirmInHKStatus()
            if status != .haveConfirmHK {
                isAllHaveConfirmed = false
            }
        }
        return isAllHaveConfirmed
    }
    
    func isAtLeastOneHeaveConfirmInHK() -> Bool { // 至少有一个已确认在港
        var isAtLeastOneHaveConfirmed = false
        for group in scheduleArr {
            let status = group.getConfirmInHKStatus()
            if status == .haveConfirmHK {
                isAtLeastOneHaveConfirmed = true
            }
        }
        return isAtLeastOneHaveConfirmed
    }
    
    
    
    func requestConfirmInHK(_ model: YHResignAppointGroup) {
        YHHUD.show(.progress(message: "提交中..."))
        self.viewModel.submitConfirmInHK(id: model.id, is_edit: model.is_edit) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self else { return }

            if success {
                // 重新请求列表
                self.requestList()
                return
            }
            let msg = error?.errorMsg ?? "提交失败"
            YHHUD.flash(message: msg)
        }
    }
    
    func requestList() {
        self.viewModel.getScheduleInfoList(renewalId: self.renewalId) {
            [weak self] success,error in
            guard let self else { return }
            self.scheduleArr.removeAll()
            self.scheduleArr.append(contentsOf: self.viewModel.scheduleInfoList.renewal_List)
            self.tableView.reloadData()
            self.updateBottomBtnAndMotifyBtnStatus()
        }
    }
}

extension YHResignAppointScheduleListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return scheduleArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if 0 <= indexPath.row && indexPath.row < scheduleArr.count {
            let model = scheduleArr[indexPath.row]
            if scheduleArr.count <= 1 {
                let cell = tableView.dequeueReusableCell(withIdentifier: YHResignScheduleSingleInfoCell.cellReuseIdentifier, for: indexPath) as! YHResignScheduleSingleInfoCell
                cell.updateModel(model)
                // 点击确认在港或未确认在港按钮
                cell.clickConfirmBtnBlock = {
                    [weak self] status in
                    guard let self = self else { return }
                    self.clickConfirmHKButton(status: status, model)
                }
                cell.modifyBtn.isHidden = self.isHiddenModifyBtn
                // 点击修改按钮
                cell.modifyBtnBlock = {
                    [weak self] in
                    guard let self = self else { return }
                    self.modifySchedule()
                }
                return cell
            }
            
            // 分组
            let cell2 = tableView.dequeueReusableCell(withIdentifier: YHResignScheduleMultipleInfoCell.cellReuseIdentifier, for: indexPath) as! YHResignScheduleMultipleInfoCell
            model.batchIndex = indexPath.row+1
            cell2.updateModel(model)
            cell2.clickConfirmBtnBlock = {
                [weak self] status in
                guard let self = self else { return }
                self.clickConfirmHKButton(status: status, model)
            }
            let isShowCorner =  (indexPath.row == scheduleArr.count-1)
            cell2.showBottomCorner(isShowCorner)
            return cell2
        }
        
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.row && indexPath.row < scheduleArr.count {
//            let model = scheduleArr[indexPath.row]
        }
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        if scheduleArr.count <= 1 {
            return 0.1
        }
        return 52.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if scheduleArr.count <= 1 {
            let view = UIView()
            return view
        }
        
        let view = UIView()
        view.clipsToBounds = true
        
        let whiteView = UIView()
        whiteView.backgroundColor = .white
        whiteView.layer.cornerRadius = kCornerRadius6
        view.addSubview(whiteView)
        
        let titleLabel = UILabel()
        titleLabel.numberOfLines = 0
        titleLabel.font = UIFont.PFSC_M(ofSize: 17)
        titleLabel.textColor = .mainTextColor
        titleLabel.text = "赴港递交已预约"
        view.addSubview(titleLabel)
        
        let modifyBtn = UIButton()
        modifyBtn.isHidden = self.isHiddenModifyBtn
        modifyBtn.setTitle("修改", for: .normal)
        modifyBtn.setTitleColor(.brandMainColor, for: .normal)
        modifyBtn.titleLabel?.font = .PFSC_M(ofSize: 14)
        modifyBtn.addTarget(self, action: #selector(modifySchedule), for: .touchUpInside)

        view.addSubview(modifyBtn)
        
        whiteView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(kCornerRadius6)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.height.equalTo(24)
            make.bottom.equalTo(-12)
        }
        
        modifyBtn.snp.makeConstraints { make in
            make.width.equalTo(28)
            make.height.equalTo(24)
            make.right.equalTo(-18)
            make.centerY.equalTo(titleLabel)
        }
        return view
    }
}

