//
//  YHGCMySignatureListViewController.swift
//  galaxy
//
//  Created by EDY on 2024/12/24.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

class YHGCMySignatureListViewController: YHBaseViewController {

    var tableView: UITableView!
    
    lazy var viewModel: YHGCMySignatureListViewModel = {
       let mv = YHGCMySignatureListViewModel()
        return mv
    }()
    
    
    lazy var viewModel2 : YHMyDocumentsListViewModel = {
        let mv = YHMyDocumentsListViewModel()
         return mv
        
    }()
    
    var orderId: Int = 0
    var mobile: String = ""
    var arrIDs : [Int] = []//保存所有下载的id
    
    
    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()
        gk_navTitle = "我的签字"
        setView()
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    
    deinit {
        removeNotify()
    }
}

extension YHGCMySignatureListViewController {
    func getData() {
        viewModel.requestSignatureList("\(orderId)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "数据获取失败")
            }
            
            self.headSessionView.userInfoData = self.viewModel.mainModel?.user_info
            self.headSessionView.canShowDownLoadBtnFlag = true
            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.renewal_manage_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.renewal_manage_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: YHGCDocListCell.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.viewModel2.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.renewal_manage_docs.count
        var selectedCount : Int = 0
        for item in dataSource.renewal_manage_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.renewal_manage_docs {
            if item.isSelectedFlag {
                arrIDs.append(item.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 YHGCMySignatureListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.mainModel?.renewal_manage_docs.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHGCDocListCell.self)
        cell.dataSourceForSign = viewModel.mainModel?.renewal_manage_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.renewal_manage_docs[indexPath.row]
        if self.isEditFlag {
            //编辑状态下的点击
            model.isSelectedFlag = !model.isSelectedFlag
            tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
            updateBottomViewNumbers()
        } else {
            let vc = YHGCMySignatureDetailViewController()
            vc.id = model.id
//            vc.isAuth = viewModel.mainModel?.user_info.is_auth ?? true
            vc.orderID = orderId
            vc.mobile = mobile
            self.navigationController?.pushViewController(vc)
        }
    }
}



extension YHGCMySignatureListViewController {
    
    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()
        }
    }
}
