//
//  YHMyDocumentsListViewController.swift
//  galaxy
//
//  Created by EDY on 2024/3/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
/*
 *我的文书 列表 
 */

class YHMyDocumentsListViewController: YHBaseViewController {
    var tableView: UITableView!
    var viewModel: YHMyDocumentsListViewModel?
    var orderId: Int = 0
    var arrIDs: [Int] = []// 保存所有下载的id
    // 是否展示下载全部按钮
    var canSendEmailFlag: Bool = false {
        didSet {
            updateHeadView()
        }
    }
    
    private var isEditFlag: Bool = false
    
    lazy var headSessionView: YHMyDocListHeaderView = {
        let view = YHMyDocListHeaderView()
        return view
    }()
    
    lazy var bottomView: YHDocListBottomView = {
        let view = YHDocListBottomView()
        return view
    }()
    
    // 头部背景图片
    lazy var headBkgImagV: UIImageView = {
        let imagV = UIImageView()
        imagV.image = UIImage(named: "my_doc_head_bkg")
        imagV.contentMode = .scaleAspectFill
        imagV.clipsToBounds = true
        return imagV
    }()
    
    lazy var emailInputView: YHEmailInputAlertView = {
        let view = YHEmailInputAlertView.emailInputView(defalutText: "请输入邮箱")
        return view
    }()
    
    lazy var blackMaskView: UIView = {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissed))
        view.addGestureRecognizer(tap)
        view.isHidden = true
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHMyDocumentsListViewModel()
        gk_navTitle = "我的文书"
        setView()
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    deinit {
        removeNotify()
    }
}

extension YHMyDocumentsListViewController {
    func updateHeadView() {
        headSessionView.canShowDownLoadBtnFlag = canSendEmailFlag
    }
    
    func getData() {
        viewModel?.requestDocumentsList("\(orderId)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                guard let arr = self.viewModel?.mainModel?.docs else { return }
                var tag = true
                for item in arr {
                    if item.sign_doc.doc_send.contains(".pdf", caseSensitive: false) == false {
                        tag = false
                        break
                    }
                }
                self.headSessionView.userInfoData = self.viewModel?.mainModel?.user_info
                self.canSendEmailFlag = tag
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "数据获取失败")
            }
            self.tableView.reloadData()
        })
    }
    
    func updateDataSource() {
        
        self.tableView.reloadData()
    }
    
    func setView() {
        
        addKeyBoardNotify()
        
        // 1
        view.addSubview(headBkgImagV)
        headBkgImagV.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(312)
        }
        
        view.addSubview(headSessionView)
        headSessionView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.height.equalTo(YHMyDocListHeaderView.viewH)
        }
        
        headSessionView.block = { type in
            self.updateUIForClickButton(type: type)
            self.isEditFlag = type == .downAll ? true : false
            
            guard let model = self.viewModel?.mainModel else { return }
            for item in model.docs {
                item.isEditFlag = self.isEditFlag
                if self.isEditFlag {
                    item.isSelectedFlag = true
                }
            }
            
            self.updateBottomViewNumbers()
            self.tableView.reloadData()
        }
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(YHDocListBottomView.viewH)
        }
        bottomView.isHidden = true
        
        bottomView.block = { (type, flag) in
            if type == .downAllCheck {
                // todo
                self.readyToDownLoad()
            } else if type == .allChoice {
                guard let model = self.viewModel?.mainModel else { return }
                var tag = false
                if flag {
                    // 全选
                    tag = true
                } else {
                    // 全选 的 反选
                    tag = false
                }
                for item in model.docs {
                    item.isSelectedFlag = tag
                }
                self.updateBottomViewNumbers()
            }
            self.tableView.reloadData()
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .plain)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHDocListCell.self)
            return tableView
        }()
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(headSessionView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        bottomView.layoutIfNeeded()
        bottomView.bottomButton.addYinHeGradualLayer()
        
        view.addSubview(blackMaskView)
        view.addSubview(emailInputView)
        emailInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHEmailInputAlertView.height)
            make.bottom.equalToSuperview().offset(YHEmailInputAlertView.height)
        }
        
        emailInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            
            if let text = text {
                YHCheckEamilAlertView.show(nil, text, "取消", "确认") {
                    // 发送接口
                    if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                        YHHUD.show(.progress(message: "发送中..."))
                        let params = ["order_id": orderID, "ids": self.arrIDs, "email": text]
                        self.viewModel?.sendEmailForDocs(params, callBackBlock: { success, error in
                            YHHUD.hide()
                            if success {
                                YHHUD.flash(message: "已发送至邮箱")
                                self.headSessionView.clickCancelBtn()
                            } else {
                                let msg = error?.errorMsg ?? "发送失败"
                                YHHUD.flash(message: msg)
                            }
                        })
                    } else {
                        YHHUD.flash(message: "订单ID 为空")
                    }
                }
            }
        }
    }
    
    @objc func dismissed() {
        emailInputView.textField.resignFirstResponder()
    }
    
    private func updateUIForClickButton(type: ClickButtonType) {
        bottomView.snp.removeConstraints()
        tableView.snp.removeConstraints()
        if type == .downAll {
            bottomView.isHidden = false
            bottomView.snp.remakeConstraints { make in
                make.bottom.left.right.equalToSuperview()
                make.height.equalTo(YHDocListBottomView.viewH)
            }
            
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(headSessionView.snp.bottom)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(bottomView.snp.top)
            }
            
            gk_navTitle = "批量下载"
        } else if type == .cancel {
            bottomView.isHidden = true
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(headSessionView.snp.bottom)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            
            gk_navTitle = "我的文书"
        } else {
            gk_navTitle = "我的文书"
        }
    }
    
    private func updateBottomViewNumbers() {
        guard let dataSource = viewModel?.mainModel else { return }
        let count = dataSource.docs.count
        var selectedCount: Int = 0
        for item in dataSource.docs {
            if item.isSelectedFlag {
                selectedCount += 1
            }
        }
        bottomView.updateNumber(allNumber: count, selectedNumber: selectedCount)
    }
    
    private func readyToDownLoad() {
        
        guard let dataSource = viewModel?.mainModel else {
            YHHUD.flash(message: "暂无数据")
            return
        }
        
        arrIDs.removeAll()
        for item in dataSource.docs {
            if item.isSelectedFlag {
                arrIDs.append(item.sign_doc.id)
            }
        }
        
        if arrIDs.isEmpty {
            YHHUD.flash(message: "至少选择一个下载项")
            return
        }
        
        // 弹窗 选择发送邮箱
        let items = [YHCertificateEditItem(type: .sendEmail, title: "发送至邮箱"),
                     YHCertificateEditItem(type: .cancel, title: "取消")]
        YHCertificateEditSheetView.sheetView(items: items, sheetTitle: "请选择下载方式") {
            [weak self] editType in
            guard let self = self else { return }
            
            IQKeyboardManager.shared.isEnabled = false
            if editType == .sendEmail {
                emailInputView.textField.text = ""
                emailInputView.textField.becomeFirstResponder()
            }
        }.show()
    }
}

extension YHMyDocumentsListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.mainModel?.docs.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHDocListCell.self)
        cell.dataSourceForDocs = viewModel?.mainModel?.docs[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let  dataSource = viewModel?.mainModel else { return }
        let model = dataSource.docs[indexPath.row]
        if self.isEditFlag {
            // 编辑状态下的点击
            model.isSelectedFlag = !model.isSelectedFlag
            tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
            updateBottomViewNumbers()
        } else {
            // 文书状态
            if model.template_id == 195 {
                // 跳转赴港计划书
                let vc = YHHKPlanDoctumentVC()
                vc.supplement_id = model.id
                vc.status = model.status
                self.navigationController?.pushViewController(vc)
            } else {
                let vc = YHMyDocumentsDetailViewController()
                vc.id = model.id
                vc.isAuth = viewModel?.mainModel?.user_info.is_auth ?? true
                vc.fileType = model.file_type
                vc.orderID = orderId
                self.navigationController?.pushViewController(vc)
            }
        }
    }
}

extension YHMyDocumentsListViewController {
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }
            
            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            self.blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.isEnabled = true
            }
            
            self.emailInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}
