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

import UIKit
import AttributedString

enum YHDateCompareResult: Int {
    case same = 1
    case large = 2
    case small = 3
}

class YHResignAppointTimeSingleCell: UITableViewCell {

    static let cellReuseIdentifier = "YHResignAppointTimeSingleCell"
    var model = YHResignAppointTimeSettingModel()
    
    var switchBlock: ((Bool) -> Void)?
    var refreshBlock: (() -> Void)?
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let titleLabel = UILabel(frame: CGRect(x: 18, y: 16, width: KScreenWidth, height: 24.0))
        let mustTag: ASAttributedString = .init("* ", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.failColor))
        var title: ASAttributedString = .init("请您确认以下信息", .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
        title = mustTag + title
        titleLabel.attributed.text = title
        return titleLabel
    }()
    
    lazy var submitTimeItemView: YHResignAppointSelectTimeItemView = {
        let view = YHResignAppointSelectTimeItemView(frame: .zero)
        view.title = "预约在港递交时间"
        view.placeHolder = "请选择"
        view.isNeedShowErrorTips = false
        view.errorTips = "请选择在港递交时间"
        view.detail = ""
        view.updateLineMargin(-18.0)
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
            
            self.getDateInfo { [weak self] startDate, endDate in
                guard let self = self else { return }
                let view = YHRangeDatePickerSheetView2.sheetView()
                view.viewTitle = "选择预约在港递交时间"
                view.minDateStr = startDate
                view.maxDateStr = endDate
                view.block = {
                    [weak self] (selectDateStr, hourTime) in
                    guard let self = self else { return }
                    let selectTimeStr = "\(selectDateStr) \(hourTime)"
                    printLog("\(selectTimeStr)")
                    // 选择在港递交时间
                    if self.model.leave_hk_at.isEmpty {
                        self.model.ready_to_submit_at = selectTimeStr
                    } else {
                        if !self.model.notleaveHK { // 离港才比较日期
                            if self.compareDates(selectTimeStr, self.model.leave_hk_at) != .small {
                                // selectTimeStr >= leave_hk_at
                                YHHUD.flash(message: "预约在港递交时间必须早于预计离港时间")
                                return
                            }
                        }
                        self.model.ready_to_submit_at = selectTimeStr
                    }
                    self.refreshBlock?()
                }
                view.show()
            }
        }
        return view
    }()
    
    lazy var leaveTimeItemView: YHResignAppointSelectTimeItemView = {
        let view = YHResignAppointSelectTimeItemView(frame: .zero)
        view.title = "预计离港时间"
        view.placeHolder = "请选择"
        view.errorTips = "请选择离港时间"
        view.isNeedShowErrorTips = false
        view.detail = ""
        view.clickBlock = {
            [weak self] in
            guard let self = self else { return }
//            self.getDateInfo { [weak self] startDate, endDate in
//                guard let self = self else { return }
            
                //  离港时间选择区间从预约在港递交时间到2029-12-31 若在港递交时间为空则离港时间选择最早为今天
                var startDate: String = self.model.getSubmitHKTime()
                let format = "yyyy-MM-dd"
                if startDate.count >= format.count {
                    startDate = String(startDate.prefix(format.count))
                }
                if startDate.isEmpty {
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = format
                    startDate = dateFormatter.string(from: Date())
                }
                var endDate = "2029-12-31"
            
                let view = YHRangeDatePickerSheetView2.sheetView()
                view.viewTitle = "选择预计离港时间"
                view.minDateStr = startDate
                view.maxDateStr = endDate
                view.showBestFlag = false
                view.block = {
                    [weak self] (selectDateStr, hourTime) in
                    guard let self = self else { return }
                    let selectTimeStr = "\(selectDateStr) \(hourTime)"
                    printLog("\(selectTimeStr)")
                    // 选择离港时间
                    if self.model.ready_to_submit_at.isEmpty {
                        self.model.leave_hk_at = selectTimeStr
                    } else {
                        
                        if self.compareDates(selectTimeStr, self.model.ready_to_submit_at) != .large {
                            // selectTimeStr <= ready_to_submit_at
                            YHHUD.flash(message: "预计离港时间预约必须晚于在港递交时间")
                            return
                        }
                        self.model.leave_hk_at = selectTimeStr
                    }
                    self.refreshBlock?()

                }
                view.show()
//            }
        }
        return view
    }()
    
    lazy var leaveHKSwithView: YHResignLeaveHKSwitchItemView = {
        let view = YHResignLeaveHKSwitchItemView()
        view.title = "暂不离港"
        view.selectBlock = {
            [weak self] on in
            guard let self = self else { return }
            self.switchBlock?(on)
        }
        return view
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func updateModel(_ model: YHResignAppointTimeSettingModel) {
        self.model = model
        self.leaveHKSwithView.switchBtn.setOn(self.model.notleaveHK, animated: false)
        let isHiddenLeaveHKTime = self.model.notleaveHK
        
        // 时间控件显示
        submitTimeItemView.detail = model.getSubmitHKTime()
        leaveTimeItemView.detail = model.getLeaveHKTime()
        
        // 时间控件红色提示显示
        submitTimeItemView.isNeedShowErrorTips = (model.isClickSubmit && model.ready_to_submit_at.isEmpty)
        leaveTimeItemView.isNeedShowErrorTips = (model.isClickSubmit && model.leave_hk_at.isEmpty)
        
        leaveTimeItemView.removeFromSuperview()
        leaveTimeItemView.snp.removeConstraints()
        
        if isHiddenLeaveHKTime {
            leaveHKSwithView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(submitTimeItemView.snp.bottom)
                make.bottom.equalToSuperview()
            }
            
        } else {
            
            whiteContentView.addSubview(leaveTimeItemView)
            leaveTimeItemView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(submitTimeItemView.snp.bottom)
            }
            
            leaveHKSwithView.snp.remakeConstraints { make in
                make.left.equalTo(18)
                make.right.equalTo(-18)
                make.top.equalTo(leaveTimeItemView.snp.bottom)
                make.bottom.equalToSuperview()
            }
        }
        
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(submitTimeItemView)
        whiteContentView.addSubview(leaveTimeItemView)
        whiteContentView.addSubview(leaveHKSwithView)
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(-16)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(16)
            make.height.equalTo(24)
        }
        
        submitTimeItemView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
        }
        
        leaveTimeItemView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(submitTimeItemView.snp.bottom)
        }
        
        leaveHKSwithView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(leaveTimeItemView.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
    
    func getDateInfo(_ result: ((_ startTime: String, _ endTime: String) -> Void)?) {
        
        // 开始时间和结束时间 都有则都取服务器model时间
        // 若开始时间为空则取当前时间
        // 若结束时间为空则取当前时间+28天的时间
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        var startTimeStr = formatter.string(from: Date())
        var endTimeStr = ""
        if let date = formatter.date(from: startTimeStr) {
            let endTimeStamp = date.timeIntervalSince1970 + (28.0 * 24.0 * 60.0 * 60.0)
            endTimeStr = formatter.string(from: Date(timeIntervalSince1970: endTimeStamp))
        }
        
        if let firstUser = self.model.users.first {
            if !firstUser.stay_deadline_start.isEmpty { // 服务器起始时间不为空
                startTimeStr = firstUser.stay_deadline_start
            }
            
            if !firstUser.stay_deadline.isEmpty { // 服务器结束时间不为空
                endTimeStr = firstUser.stay_deadline
                
            } else {
                // 结束时间为空 则设置为开始时间后的28天
                // 将字符串转换为 Date 对象
                if let date = formatter.date(from: startTimeStr) {
                    let endTimeStamp = date.timeIntervalSince1970 + (28.0 * 24.0 * 60.0 * 60.0)
                    endTimeStr = formatter.string(from: Date(timeIntervalSince1970: endTimeStamp))
                }
            }
        }
        let duration = "START_DATE: \(startTimeStr) END_DATE: \(endTimeStr)"
        printLog("\(duration)")
        result?(startTimeStr, endTimeStr)
    }
    
    func compareDates(_ dateStr1: String, _ dateStr2: String) -> YHDateCompareResult {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        let dateFormatCount = dateFormatter.dateFormat.count
        
        var dateString1 = dateStr1
        if dateString1.count > dateFormatCount {
            dateString1 = String(dateString1.prefix(dateFormatCount))
        }
        var dateString2 = dateStr2
        if dateString2.count > dateFormatCount {
            dateString2 = String(dateString2.prefix(dateFormatCount))
        }
        
        // 将字符串转换为 Date 对象
        guard let date1 = dateFormatter.date(from: dateString1),
              let date2 = dateFormatter.date(from: dateString2) else {
            print("日期格式错误")
            YHHUD.flash(message: "日期格式错误")
            return .same
        }
        
        // 比较日期
        if date1 < date2 {
            return .small
        } else if date1 > date2 {
            return .large
        }
        return .same
    }
}
