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

import UIKit
import IQKeyboardManagerSwift
import AttributedString

class YHCertificateUploadContentListVC: YHBaseViewController {

    // 进入该页面以下三个参数必传
    var orderId : Int = 0
    var categoryId: Int = 0
    var supplementId: Int = 0
    
    private var categoryInfo = YHCategoryData()
    private var supplementInfo = YHSupplementInfo() {
        didSet {
            templateArr.removeAll()
                if supplementInfo.templateInfo.materialPath.count > 0 {
                    let template = supplementInfo.templateInfo.materialPath[0]
                    template.type = 0
                    templateArr.append(template)
                }
                if supplementInfo.templateInfo.guideFilePath.count > 0 {
                    let guide = supplementInfo.templateInfo.guideFilePath[0]
                    guide.type = 1
                    templateArr.append(guide)
                }
            self.tableView.reloadData()
        }
    }
    var viewModel: YHCertificateViewModel = YHCertificateViewModel()
    var templateArr:[YHMaterialPath] = []
    var items:[YHContentUrl] = []
    var selectEditItem: YHContentUrl?
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()

    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(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
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateNameCell.self, forCellReuseIdentifier: YHCertificateNameCell.cellReuseIdentifier)
        tableView.register(YHCertificateTemplateCell.self, forCellReuseIdentifier: YHCertificateTemplateCell.cellReuseIdentifier)


        return tableView
    }()
    
    lazy var uploadBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("继续上传".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickUploadBtn), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "上传内容"
        
        addKeyBoardNotify()
        createUI()
        
        items.removeAll()
        if supplementInfo.contentUrl.count > 0 {
            items.append(contentsOf: supplementInfo.contentUrl)
        }
        tableView.reloadData()
        
        requestList()
        
        renameInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            if let selectEditItem = selectEditItem, var text = text {
                // 重命名
                text = text + "." + selectEditItem.getFileSuffixName()
                YHHUD.show(.progress(message: "重命名中..."))
                self.viewModel.updateCertificateItem(supplementsId:supplementInfo.id, urlModels:[selectEditItem], operation: "rename", rename: text) {
                    success, error in
                    YHHUD.hide()
                    if success {
                        YHHUD.flash(message: "重命名成功")
                    } else {
                        var msg = "重命名失败"
                        if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                            msg = errorMsg
                        }
                        YHHUD.flash(message:msg)
                    }
                    self.requestList()
                }
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.post(name: YhConstant.YhNotification.refreshCertificateFileListNotifiction, object: nil)
    }
    
    deinit {
        removeNotify()
    }
    
    @objc func didClickUploadBtn() {
        
        if items.count >= 99 {
            YHHUD.flash(message: "已达上限\n最多上传99张图片或文件")
            return
        }
        
        let sheetView = YHCertificateUploadSheetView.sheetView()
        sheetView.maxSelectCount = 99-items.count
        sheetView.uploadFilesBlock = {
            [weak self] fileUrl in
            guard let self = self else { return }
            print(fileUrl)
            self.viewModel.uploadFile(fileUrl, supplementId: supplementId) {
                [weak self] in
                guard let self = self else { return }
                self.requestList()
            }
        }
        sheetView.uploadImageBlock = {
            [weak self] targetImgArr in
            guard let self = self else { return }
            self.viewModel.uploadImageArr(targetImgArr, supplementId: supplementId) {
                [weak self] in
                guard let self = self else { return }
                self.requestList()
            }
        }
        sheetView.show()
    }
    
    func createUI() {

        view.addSubview(uploadBtn)
        view.addSubview(tableView)
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            if supplementInfo.checkStatus == YHCertificateUploadStatus.finish.rawValue {
                make.bottom.equalToSuperview()
            } else {
                make.bottom.equalTo(uploadBtn.snp.top).offset(-34)
            }
        }
        uploadBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48.0)
            make.bottom.equalToSuperview().offset(-8-k_Height_safeAreaInsetsBottom())
        }

        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileRenameInputView.height)
            make.bottom.equalToSuperview().offset(YHFileRenameInputView.height)
        }
    }
}

extension YHCertificateUploadContentListVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return templateArr.count
        }
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateTemplateCell.cellReuseIdentifier, for: indexPath) as! YHCertificateTemplateCell
            cell.update(bottomMargin: 15)
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                cell.templatePath = templateArr[indexPath.row]
            }
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateNameCell.cellReuseIdentifier, for: indexPath) as! YHCertificateNameCell
        if 0 <= indexPath.row && indexPath.row < items.count {
            let item = items[indexPath.row]
            cell.updateModel(item)
            cell.editBlock = {
                
                [weak self] contentItem in
                guard let self = self else { return }
                selectEditItem = contentItem
                var items = [YHCertificateEditItem(type:.rename, title:"重命名"),
                             YHCertificateEditItem(type:.preview, title:"预览"),
                             YHCertificateEditItem(type:.delete, title:"删除"),
                             YHCertificateEditItem(type:.cancel, title:"取消")]
                
                if supplementInfo.checkStatus == YHCertificateUploadStatus.finish.rawValue {
                    items = [YHCertificateEditItem(type:.preview, title:"预览"),
                             YHCertificateEditItem(type:.cancel, title:"取消")]
                }
                
                YHCertificateEditSheetView.sheetView(items:items) {
                    [weak self] editType in
                    guard let self = self else { return }
                    print("editType:\(editType.rawValue)")
                    
                    if editType == .rename { // 重命名
                        IQKeyboardManager.shared.enable = false
                        
                        var name = contentItem.getFileNameWithoutSuffix()
                        if name.count > 30 {
                            name = name[safe: ..<30]!
                        }
                        renameInputView.textField.text = name
                        renameInputView.textField.becomeFirstResponder()
                        
                    } else if editType == .delete { // 删除
                        
                        let msg = "您确定要删除文档\(contentItem.name)吗?"
                        YHTwoOptionAlertView.showAlertView(message:msg) { sure in
                            if !sure { return }
                            // 删除
                            YHHUD.show(.progress(message: "删除中..."))
                            self.viewModel.updateCertificateItem(supplementsId:self.supplementInfo.id, urlModels:[contentItem], operation: "del", rename:"") {
                                success, error in
                                YHHUD.hide()
                                if success {
                                    YHHUD.flash(message: "删除成功")
                                } else {
                                    var msg = "删除失败"
                                    if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                                        msg = errorMsg
                                    }
                                    YHHUD.flash(message:msg)
                                }
                                self.requestList()
                            }
                        }
                        
                    } else if editType == .preview { // 预览
                        print(contentItem.url)
                        self.viewModel.getPublicImageUrl(contentItem.url) { success, error in
                            if let success = success {
                                self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:contentItem.name)
                            }
                        }
                    }
                }.show()
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return 77.0
        }
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            if supplementInfo.templateInfo.isNeedShowTemplate() {
                return UITableView.automaticDimension
            }
            return 0.0
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 { // 证件示例模版
            
            if !supplementInfo.templateInfo.isNeedShowTemplate() {
                return view
            }

            let titlelabel = UILabel()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.textAlignment = .left
            titlelabel.font = UIFont.PFSC_M(ofSize:17)
            titlelabel.text = "\(supplementInfo.name)示例模版"
            titlelabel.numberOfLines = 0
            view.addSubview(titlelabel)
            
            titlelabel.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(16)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
            }

            let tipsLabel = UILabel()
            tipsLabel.textColor = UIColor.labelTextColor2
            tipsLabel.textAlignment = .left
            tipsLabel.font = UIFont.PFSC_R(ofSize:14)
            tipsLabel.numberOfLines = 0
            if !supplementInfo.templateInfo.description.isEmpty {
                tipsLabel.text = "注意事项:\n\(supplementInfo.templateInfo.description)"
            }
            view.addSubview(tipsLabel)
            
            tipsLabel.snp.makeConstraints { make in
                make.top.equalTo(titlelabel.snp.bottom).offset(5)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.bottom.equalToSuperview().offset(-15)
           }
           return view
        }

        // 证件标题和状态
        let titlelabel = UILabel()
        titlelabel.textColor = UIColor.mainTextColor
        titlelabel.textAlignment = .left
        titlelabel.font = UIFont.PFSC_M(ofSize:17)
        titlelabel.text = supplementInfo.name
        titlelabel.numberOfLines = 0
        view.addSubview(titlelabel)
        
        let statusLabel = UILabel()
        statusLabel.textAlignment = .center
        statusLabel.font = UIFont.PFSC_M(ofSize:10)
        statusLabel.layer.cornerRadius = kCornerRadius3
        statusLabel.clipsToBounds = true
        view.addSubview(statusLabel)
        
        var text = ""
        var textColor:UIColor = .clear
        var bgColor:UIColor = .clear
        if supplementInfo.checkStatus == YHCertificateUploadStatus.review.rawValue {
            text = "审核中".local
            textColor = UIColor(hexString: "#FF9900")!
            bgColor = UIColor(hexString: "#FF9900", transparency: 0.08)!
        } else if supplementInfo.checkStatus == YHCertificateUploadStatus.preUpload.rawValue {
            text = "待上传".local
            textColor = UIColor(hexString: "#2F7EF6")!
            bgColor = UIColor(hexString: "#2F7EF6", transparency: 0.08)!

        } else if supplementInfo.checkStatus == YHCertificateUploadStatus.finish.rawValue {
            text =  "已完成".local
            textColor = UIColor(hexString: "#49D2B1")!
            bgColor = UIColor(hexString: "#49D2B1", transparency: 0.08)!

        } else if supplementInfo.checkStatus == YHCertificateUploadStatus.rejected.rawValue {
            text =  "已驳回".local
            textColor = UIColor.failColor
            bgColor = UIColor(hexString: "#F81D22", transparency: 0.08)!
        }
        statusLabel.text = text
        statusLabel.textColor = textColor
        statusLabel.backgroundColor = bgColor
        
        let tipsLabel = UILabel()
        tipsLabel.textColor = .labelTextColor2
        tipsLabel.font = UIFont.PFSC_R(ofSize:12)
        tipsLabel.textAlignment = .left
        tipsLabel.numberOfLines = 0
        tipsLabel.text = "支持的文件格式为jpg/jpeg、png、doc/docx、pptx、pdf，最多可上传99张图片或文件"
        view.addSubview(tipsLabel)
        
        titlelabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview()
        }
        
        statusLabel.snp.makeConstraints { make in
            make.centerY.equalTo(titlelabel)
            make.left.equalTo(titlelabel.snp.right).offset(4)
            make.right.lessThanOrEqualTo(view).offset(-20)
            make.height.equalTo(16)
            make.width.equalTo(38)
        }
        
        tipsLabel.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titlelabel.snp.bottom).offset(7)
            make.bottom.equalToSuperview().offset(-15)
        }
        
        if supplementInfo.checkStatus != YHCertificateUploadStatus.rejected.rawValue {
            return view
        }
        
        if supplementInfo.auditContent.isEmpty { // 无驳回理由
            return view
        }
        
        // 有驳回理由
        let rejectView = UIView()
        view.addSubview(rejectView)
        
        let warningImgV = UIImageView(image: UIImage(named: "my_cer_upload_warning"))
        rejectView.addSubview(warningImgV)
        
        let rejectTitleLabel = UILabel()
        rejectTitleLabel.textColor = .failColor
        rejectTitleLabel.font = UIFont.PFSC_R(ofSize:12)
        rejectTitleLabel.textAlignment = .left
        rejectTitleLabel.text = "驳回原因："
        rejectView.addSubview(rejectTitleLabel)
        
        let rejectContentLabel = UILabel()
        rejectContentLabel.textColor = .failColor
        rejectContentLabel.font = UIFont.PFSC_R(ofSize:12)
        rejectContentLabel.numberOfLines = 0
        rejectContentLabel.textAlignment = .left
        rejectContentLabel.text = supplementInfo.auditContent
        rejectView.addSubview(rejectContentLabel)
        
        tipsLabel.snp.remakeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titlelabel.snp.bottom).offset(7)
            make.bottom.equalTo(rejectView.snp.top).offset(-20)
        }

        rejectView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview().offset(-12)
        }
        
        warningImgV.snp.makeConstraints { make in
            make.width.height.equalTo(14)
            make.left.top.equalTo(0)
        }
        
        rejectTitleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(warningImgV)
            make.left.equalTo(warningImgV.snp.right).offset(4)
        }
        
        rejectContentLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(warningImgV.snp.bottom).offset(7)
            make.bottom.equalToSuperview()
        }
        return view
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return 20.0
        }
        return 60.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 {
            return view
        }
        
        let label = UILabel(frame: CGRect(x: 0, y: 20, width:KScreenWidth, height:20))
        label.textColor = UIColor.labelTextColor2
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize:12)
        
        let tipsFont = UIFont.PFSC_R(ofSize: 12)
        let a: ASAttributedString = .init("已上传", .font(tipsFont),.foreground(UIColor.labelTextColor2))
        let b: ASAttributedString = .init(" \(items.count)/99 ", .font(UIFont.PFSC_M(ofSize: 12)), .foreground(UIColor.init(hexString:"#2F2F2F")!))
        let c: ASAttributedString = .init("张图片或文件", .font(tipsFont), .foreground(UIColor.labelTextColor2))
        
        label.attributed.text = a+b+c
        
        view.addSubview(label)
        
        label.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 { // 模版列表
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                let path = templateArr[indexPath.row]
                print(path.url)
                if !path.url.isEmpty {
                    self.previewFileTool.openXLSXRemoteFile(urlString:path.url, fileName:"预览")
                }
            }
             
        } else if indexPath.section == 1 { // 证件列表
            if 0 <= indexPath.row && indexPath.row < items.count {
                let cer = items[indexPath.row]
                if !cer.url.isEmpty {
                    print(cer.url)
                    self.viewModel.getPublicImageUrl(cer.url) { success, error in
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:cer.name)
                        }
                    }
                }
            }
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHCertificateUploadContentListVC {
    
    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.enable = true
            }
            
            self.renameInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

extension YHCertificateUploadContentListVC {
    
    func requestList() {
        
        let params:[String:Any] = [
                                    "order_id" : orderId,
                                    "node": "1",
                                    "state": "1",
                                    "category_id": categoryId,
                                    "supplement_ids": supplementId]

        print(params)
        viewModel.getCertificateList(params: params) {
            
            [weak self] listInfo, error in
            guard let self = self else { return }
            
            items.removeAll()
            if let listInfo = listInfo {
                categoryInfo = listInfo.categoryData
                let arr = listInfo.supplementList
                if arr.count > 0 {
                    supplementInfo = arr[0]
                }
                for item in arr {
                    items.append(contentsOf: item.contentUrl)
                }
            }
            
            if categoryInfo.checkStatus == YHCertificateUploadStatus.finish.rawValue {
                self.uploadBtn.isHidden = true
            } else {
                self.uploadBtn.isHidden = false
                self.uploadBtn.alpha = (items.count >= 99 ? 0.5 : 1.0)
            }
            
            self.tableView.reloadData()
            
            if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                YHHUD.flash(message: errorMsg, duration:3)
            }
        }
    }
}

