//
//  YHHKRecordsEditContentVC.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import JXSegmentedView
import IQKeyboardManagerSwift

class YHHKRecordsEditContentVC: YHBaseViewController {
    
    enum YHHKRecordsEditPageType {
        case add, edit
        
        var title: String {
            switch self {
            case .add:
                return "新增在港记录"
            case .edit:
                return "编辑在港记录"
            }
        }
    }
    
    enum SelectTimeType {
        case fromTime, endTime
    }
    
    enum RowType {
        case tips(_ title: String, _ detail: NSAttributedString)
        case header(_ title: String)
        case personnelStaying(_ title: String, _ detail: [YHHKRecordsUserItem])
        case selectTime(_ title: String, _ detail: String?, _ placeholder: String, _ timeType: SelectTimeType)
        case remark(_ title: String, _ detail: String)
    }
    
    private var datas: [[RowType]] = []
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.estimatedSectionHeaderHeight = 16.0
        view.estimatedSectionFooterHeight = 0.01
        view.sectionHeaderHeight = 16.0
        view.sectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        view.showsVerticalScrollIndicator = false
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.tableFooterView = UITableViewHeaderFooterView()
        view.register(YHResignDocumentTipsCell.self, forCellReuseIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier)
        view.register(YHHKRecordsTitleCell.self, forCellReuseIdentifier: YHHKRecordsTitleCell.cellReuseIdentifier)
        view.register(YHHKRecordsRemarkCell.self, forCellReuseIdentifier: YHHKRecordsRemarkCell.cellReuseIdentifier)
        view.register(YHHKRecordsTimeSelectCell.self, forCellReuseIdentifier: YHHKRecordsTimeSelectCell.cellReuseIdentifier)
        view.register(YHHKRecordsStayingPersonnelCell.self, forCellReuseIdentifier: YHHKRecordsStayingPersonnelCell.cellReuseIdentifier)
        view.keyboardDismissMode = .onDrag
        return view
    }()
    
    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var saveButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        let buttonName = "保存在港记录"
        button.setTitle(buttonName, for: .normal)
        button.setTitle(buttonName, for: .highlighted)
        button.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
        button.setTitleColor( UIColor(hex: 0xffffff), for: .highlighted)
        button.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()
    
    private var personnelStayingHeight: CGFloat?
    
    private lazy var viewModel = YHHKImmigrationRecordsViewModel()
    private lazy var editModel = YHHKImmigrationEditRecordModel()
    private var familyMembers: YHHKRecordsFamilyMembers?
    
    private let pageType: YHHKRecordsEditPageType
    private let orderId: Int
    
    init(orderId: Int, pageType: YHHKRecordsEditPageType, editModel: YHHKImmigrationEditRecordModel? = nil) {
        self.pageType = pageType
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
        if let editModel = editModel {
            self.editModel = editModel
        }
        self.editModel.order_id = orderId
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        requestData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.isEnabled = true
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.isEnabled = false
    }
}

extension YHHKRecordsEditContentVC {
    
    private func setupUI() {
        gk_navBarAlpha = 1
        gk_navTitle = pageType.title
        
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(saveButton)
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(64)
        }
        
        saveButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.centerY.equalToSuperview()
            make.height.equalTo(48)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(bottomView.snp.top)
        }
        tableView.tableFooterView = UIView(frame: CGRect.init(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        editModel.valueChanged = { [weak self] isSubmittable in
            self?.updateSaveButton(isSubmittable)
        }
        updateSaveButton(editModel.isSubmittable)
    }
    
    private func updateSaveButton(_ isSubmittable: Bool) {
        saveButton.isEnabled = editModel.isSubmittable
        saveButton.backgroundColor = editModel.isSubmittable ? .brandMainColor : .brandMainColor30
    }
    
    private func requestData() {
        viewModel.getHKImmigrationRecordsFamilyMembers(orderId: orderId) { [weak self] familyMembers, error in
            guard let self = self else {
                return
            }
            self.familyMembers = familyMembers
            if let familyMembers = familyMembers {
                self.updateVC(familyMembers: familyMembers)
            } else {
                printLog("YHHKRecordsEditContentVC:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                self.datas = []
                self.tableView.reloadData()
            }
        }
    }
    
    private func updateVC(familyMembers: YHHKRecordsFamilyMembers) {
        if pageType == .add {
            var sections: [[RowType]] = [[.tips("温馨提示：", getTips())]]
            var section: [RowType] = [.header("在港逗留记录")]
            section.append(.personnelStaying("逗留人员", familyMembers.list))
            section.append(.selectTime("入境时间", nil, "请选择", .fromTime))
            section.append(.selectTime("离境时间", nil, "请选择", .endTime))
            section.append(.remark("备注", ""))
            sections.append(section)
            datas = sections
        } else {
            var sections: [[RowType]] = [[.tips("温馨提示：", getTips())]]
            var section: [RowType] = [.header("在港逗留记录")]
            familyMembers.list.forEach { item in
                if editModel.users.contains(where: { oldItem in
                    oldItem.user_id == item.user_id
                }) {
                    item.isSelected = true
                }
            }
            section.append(.personnelStaying("逗留人员", familyMembers.list))
            section.append(.selectTime("入境时间", editModel.start_date, "请选择", .fromTime))
            section.append(.selectTime("离境时间", editModel.end_date, "请选择", .endTime))
            section.append(.remark("备注", editModel.remark))
            sections.append(section)
            datas = sections
        }
        tableView.reloadData()
    }
    
    @objc private func clickSaveButton() {
        guard editModel.isSubmittable else {
            YHHUD.flash(message: "请填写完整所需材料")
            return
        }
        if pageType == .add {
            submitAdd()
        } else {
            submitEdit()
        }
    }
    
    private func submitEdit() {
        viewModel.editHKImmigrationRecord(editModel.getParameters()) { [weak self] success, error in
            if success {
                YHHUD.flash(message: "保存成功")
                self?.navigationController?.popViewController(animated: true)
            } else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
    
    private func submitAdd() {
        viewModel.addHKImmigrationRecord(editModel.getParameters()) { [weak self] success, error in
            if success {
                YHHUD.flash(message: "新增成功")
                self?.navigationController?.popViewController(animated: true)
            } else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
}

extension YHHKRecordsEditContentVC: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension YHHKRecordsEditContentVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        let sectionArr = datas[section]
        return sectionArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let row = sectionArr[indexPath.row]
        switch row {
        case let .remark(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsRemarkCell.cellReuseIdentifier) as? YHHKRecordsRemarkCell {
                cell.setupCellInfo(title: title, titleColor: .mainTextColor, detail: detail, isEditable: true, cellType: .bottom)
                cell.textDidExceedsMaxLimit = { maxCount in
                    YHHUD.flash(message: "不可超过\(maxCount)字")
                }
                
                cell.textViewDidChanged = { [weak self] textView in
                    guard let self = self else {
                        return
                    }
                    var sections = self.datas[indexPath.section]
                    sections[indexPath.row] = .remark(title, textView.text)
                    self.datas[indexPath.section] = sections
                    self.editModel.remark = textView.text
                }
                return cell
            }
        case let .tips(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier) as? YHResignDocumentTipsCell {
                cell.setupCellInfo(title: title, detail: detail, detailColor: .mainTextColor70)
                return cell
            }
        case let .header(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsTitleCell.cellReuseIdentifier) as? YHHKRecordsTitleCell {
                cell.setupCellInfo(title)
                return cell
            }
        case let .personnelStaying(title, personnels):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsStayingPersonnelCell.cellReuseIdentifier) as? YHHKRecordsStayingPersonnelCell {
                cell.setupCellInfo(title: title)
                cell.collectionData = personnels
                cell.didHeightChanged = { [weak self] height in
                    self?.personnelStayingHeight = height
                    self?.tableView.performBatchUpdates { [weak tableView] in
                        guard let tableView = tableView else {
                            return
                        }
                        // 解决在旧机器上没法准确更新cell造成界面重叠的问题， 新机器reloadRows(at: [indexPath], with: .none)没问题
                        tableView.reloadData()
                    }
                }
                cell.didFinishLoading = { [weak cell] in
                    cell?.defaultSelectItems(rows: personnels.enumerated().filter { _, person in
                        person.isSelected
                    }.map { $0.0 })
                }
                cell.selectItemAction = { [weak self] item in
                    guard let self = self else {
                        return
                    }
                    var users = self.editModel.users
                    users.append(item)
                    self.editModel.users = users
                    self.familyMembers?.list.forEach({ oldItem in
                        if oldItem.user_id == item.user_id {
                            item.isSelected = true
                            return
                        }
                    })
                    var sections = self.datas[indexPath.section]
                    if let list = self.familyMembers?.list {
                        sections[indexPath.row] = .personnelStaying(title, list)
                        self.datas[indexPath.section] = sections
                    }
                }
                cell.deselectItemAction = { [weak self] item in
                    guard let self = self else {
                        return
                    }
                    if let index = self.editModel.users.firstIndex(where: { oldItem in
                        oldItem.user_id == item.user_id
                    }) {
                        var users = self.editModel.users
                        users.remove(at: index)
                        self.editModel.users = users
                    }
                    self.familyMembers?.list.forEach({ oldItem in
                        if oldItem.user_id == item.user_id {
                            item.isSelected = false
                            return
                        }
                    })
                    var sections = self.datas[indexPath.section]
                    if let list = self.familyMembers?.list {
                        sections[indexPath.row] = .personnelStaying(title, list)
                        self.datas[indexPath.section] = sections
                    }
                }
                return cell
            }
        case let .selectTime(title, detail, placeholder, _):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHHKRecordsTimeSelectCell.cellReuseIdentifier) as? YHHKRecordsTimeSelectCell {
                cell.setupCellInfo(title: title, detail: detail, placeholder: placeholder)
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard datas.count > indexPath.section else {
            return
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return
        }
        let row = sectionArr[indexPath.row]
        if case let .selectTime(title, detail, placeholder, timeType)  = row {
            YHDatePickView.show(type: .yyyymmdd, title: title, lastIsTaday: false, currentDay: detail ?? "") { [weak self] dateStr in
                guard let self = self, dateStr.count > 0 else { return }
                if timeType == .fromTime {
                    if self.editModel.end_date.count > 0, self.compareDateStrings(dateStr, self.editModel.end_date) == .orderedDescending {
                        YHHUD.flash(message: "入境时间不能晚于离境时间")
                    } else {
                        var sections = self.datas[indexPath.section]
                        sections[indexPath.row] = .selectTime(title, dateStr, placeholder, timeType)
                        self.datas[indexPath.section] = sections
                        self.editModel.start_date = dateStr
                        tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                } else {
                    if self.editModel.start_date.count > 0, self.compareDateStrings(self.editModel.start_date, dateStr) == .orderedDescending {
                        YHHUD.flash(message: "离境时间不能早于入境时间")
                    } else {
                        var sections = self.datas[indexPath.section]
                        sections[indexPath.row] = .selectTime(title, dateStr, placeholder, timeType)
                        self.datas[indexPath.section] = sections
                        self.editModel.end_date = dateStr
                        tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }
                
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard datas.count > indexPath.section else {
            return 0
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return 0
        }
        let row = sectionArr[indexPath.row]
        switch row {
        
        case .remark:
            return 146
        case .tips:
            return UITableView.automaticDimension
        case .header:
            return 52
        case .personnelStaying:
            if let personnelStayingHeight = personnelStayingHeight {
                return personnelStayingHeight
            }
            return UITableView.automaticDimension
        case .selectTime:
            return 52
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}

extension YHHKRecordsEditContentVC {
    
    private func getTips() -> NSAttributedString {
        let normalTextFirst = "您好，所有家庭成员赴港时间"
        let attText = "间隔不能超出180天"
        let normalTextLast = "（红线）如超出，递交续签时需向港府解释说明连续180未赴港原因。主申请人赴港频率越高，逗留时间越长，续签成功率越高哦~"
        let attStr = NSMutableAttributedString(string: normalTextFirst + attText + normalTextLast)
        attStr.setAttributes([.foregroundColor: UIColor.brandMainColor, .font: UIFont.PFSC_B(ofSize: 12)], range: NSRange(location: normalTextFirst.count, length: attText.count))
        return attStr
    }
    
    private func compareDateStrings(_ date1: String, _ date2: String) -> ComparisonResult? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd" // 根据你的日期字符串格式调整
        guard let firstDate = dateFormatter.date(from: date1),
              let secondDate = dateFormatter.date(from: date2) else {
            YHHUD.flash(message: "日期字符串格式无效")
            return nil
        }
        return firstDate.compare(secondDate)
    }
}
