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

import UIKit
import IQKeyboardManagerSwift
import AttributedString

class YHResignMaterialUploadVC: YHBaseViewController {

    // 进入该页面以下三个参数必传
    // 订单id
    var orderId: Int = 0
    // 批次id
    var batchId: Int = 0
    var materialId: Int = 0
    
    var materialModel: YHMaterialModel = YHMaterialModel() {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    var templateModel: YHResignTemplateDetail = YHResignTemplateDetail()
    var templateArr: [YHResignTemplateItemModel] = []
    
    var categoryId: Int = 0
    var supplementId: Int = 0
    
    var viewModel: YHResignMaterialViewModel = YHResignMaterialViewModel()
    
    var items: [YHMaterialModelItemModel] = []
    
    var selectEditItem: YHMaterialModelItemModel?
    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(YHResignMaterialNameCell.self, forCellReuseIdentifier: YHResignMaterialNameCell.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)
        btn.isHidden = true
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "资料上传"
        
        addKeyBoardNotify()
        createUI()
        requestMaterialDetail()
        
        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: "重命名中..."))
                selectEditItem.name = text
                
                self.viewModel.updateMaterials(material: self.materialModel, addInfoArr: []) {
                    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.requestMaterialDetail()
                }
            }
        }
    }
    
    deinit {
        removeNotify()
    }
    
    @objc func didClickUploadBtn() {
        
        if items.count >= 99 {
            YHHUD.flash(message: "已达上限\n最多上传99张图片或文件")
            return
        }
        
        let sheetView = YHCertificateUploadSheetView.sheetView()
        sheetView.maxSelectImageCount = 99-items.count
        sheetView.tips = "支持的文件格式为jpg/jpeg、png、bmp、doc/docx、xls/xlsx、pdf，最多可上传99张图片或文件"
        sheetView.uploadTypeArr = [ YHCertificateUploadItem(type: .camera, title: "拍照上传"),
                                    YHCertificateUploadItem(type: .photo, title: "相册上传"),
                                    YHCertificateUploadItem(type: .phoneFile, title: "手机文件上传", subtitle: "从手机文件管理中上传"),
                                    YHCertificateUploadItem(type: .wechatUpload, title: "微信上传"),
                                    YHCertificateUploadItem(type: .cancel, title: "取消")]
        sheetView.fileTypes = [ "public.image",
                                "com.adobe.pdf",
                                "com.microsoft.word.doc",
                                "org.openxmlformats.wordprocessingml.document",
                                "org.openxmlformats.spreadsheetml.sheet",
                                "com.microsoft.excel.xls" ]
        sheetView.uploadFilesBlock = {
            [weak self] fileUrl in
            guard let self = self else { return }
            print(fileUrl)
            
            self.viewModel.uploadFilesWithMaterial(material: self.materialModel, fileUrl: fileUrl) {
                [weak self] in
                guard let self = self else { return }
                self.requestMaterialDetail()
            }
        }
        sheetView.uploadImageBlock = {
            [weak self] targetImgArr in
            guard let self = self else { return }
            self.viewModel.uploadImageArr(targetImgArr, material: self.materialModel) {
                [weak self] in
                guard let self = self else { return }
                self.requestMaterialDetail()
            }
        }
        sheetView.wechatUploadBlock = {
            [weak self] in
            guard let self = self else { return }
            let token = YHLoginManager.shared.h5Token
            let path = "/superApp/pages/wxUpload/wxUpload?param=\(token)&material_id=\(self.materialModel.id)&template_id=\(self.materialModel.template_id)&type=wx_upload_renewal_data"
            YHShareManager.shared.openMiniProgram(path: path, title: "微信上传")
        }

        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.bottom.equalToSuperview()
        }
        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 YHResignMaterialUploadVC: 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 {
            
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateTemplateCell.cellReuseIdentifier, for: indexPath) as? YHCertificateTemplateCell else { return UITableViewCell() }
            cell.update(bottomMargin: 15)
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                cell.templateModel = templateArr[indexPath.row]
            }
            return cell
        }
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHResignMaterialNameCell.cellReuseIdentifier, for: indexPath) as? YHResignMaterialNameCell else {
            return UITableViewCell()
        }
        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 self.materialModel.status == YHMaterialStatus.completed.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.isEnabled = 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: "删除中..."))
                            var deleteIndex = -1
                            for (index, item) in self.materialModel.info.enumerated() {
                                if contentItem.url == item.url {
                                    deleteIndex = index
                                    break
                                }
                            }
                            
                            if deleteIndex == -1 { // 没有找到对应资料文件
                                YHHUD.flash(message: "删除成功")
                                return
                            }
                            self.materialModel.info.remove(at: deleteIndex)
                            self.viewModel.updateMaterials(material: self.materialModel, addInfoArr: []) {
                                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.requestMaterialDetail()
                            }
                        }
                        
                    } else if editType == .preview { // 预览
                        print(contentItem.url)
                        self.viewModel.getPublicImageUrl(contentItem.url) { success, _ 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 {
            return UITableView.automaticDimension
        }
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 { // 证件示例模板
        
            let titlelabel = UILabel()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.textAlignment = .left
            titlelabel.font = UIFont.PFSC_M(ofSize: 17)
            titlelabel.text = "\(self.materialModel.getName())示例模板"
            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 !self.templateModel.remark.isEmpty {
                tipsLabel.text = "注意事项：\(self.templateModel.remark)"
            }
            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 = self.materialModel.getName()
        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 self.materialModel.status == YHMaterialStatus.review.rawValue {
            text = "审核中".local
            textColor = UIColor(hexString: "#FF9900")!
            bgColor = UIColor(hexString: "#FF9900", transparency: 0.08)!
            
        } else if self.materialModel.status == YHMaterialStatus.preUpload.rawValue {

            text = "待上传".local
            textColor = UIColor(hexString: "#2F7EF6")!
            bgColor = UIColor(hexString: "#2F7EF6", transparency: 0.08)!

        } else if self.materialModel.status == YHMaterialStatus.completed.rawValue {
            text =  "已完成".local
            textColor = UIColor(hexString: "#49D2B1")!
            bgColor = UIColor(hexString: "#49D2B1", transparency: 0.08)!

        } else if self.materialModel.status == YHMaterialStatus.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: 14)
        tipsLabel.textAlignment = .left
        tipsLabel.numberOfLines = 0
        
        tipsLabel.text = "支持的文件格式为jpg/jpeg、png、bmp、doc/docx、xls/xlsx、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 self.materialModel.status != YHMaterialStatus.rejected.rawValue {
            return view
        }
        
        if self.materialModel.audit_remark.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 = self.materialModel.audit_remark
        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.fileUrl)
                if !path.fileUrl.isEmpty {
                    self.previewFileTool.openXLSXRemoteFile(urlString: path.fileUrl, 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, _ in
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: cer.name)
                        }
                    }
                }
            }
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHResignMaterialUploadVC {
    
    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)
        NotificationCenter.default.addObserver(self, selector: #selector(requestMaterialDetail), name: YhConstant.YhNotification.didMyResignMaterialWeChatFileUploadCallBackNotification, 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.renameInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

extension YHResignMaterialUploadVC {
    
    @objc func requestMaterialDetail() {
    
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getMaterialDeal(orderId: orderId, id: batchId, materialId: materialId) {
            [weak self] _, error  in
            YHHUD.hide()
            guard let self = self else { return }
            
            self.materialModel = self.viewModel.materialDeal
            self.items = self.materialModel.info
            
            if self.materialModel.status == YHMaterialStatus.completed.rawValue {
                self.uploadBtn.isHidden = true
            } else {
                self.uploadBtn.isHidden = false
                self.uploadBtn.alpha = (items.count >= 99 ? 0.5 : 1.0)
            }
            
            self.tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalToSuperview()
                if self.materialModel.status == YHMaterialStatus.completed.rawValue {
                    make.bottom.equalToSuperview()
                } else {
                    make.bottom.equalTo(self.uploadBtn.snp.top).offset(-34)
                }
            }
            self.tableView.reloadData()
            self.requestTemplate()
            
            if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                YHHUD.flash(message: errorMsg, duration: 3)
            }
        }
    }
    
    func requestTemplate() {
        viewModel.getTemplateInfo(templateId: self.materialModel.template_id) { 
            [weak self] _, _ in
            guard let self = self else { return }
            
            self.templateModel = self.viewModel.templateDeail
            self.templateArr = self.templateModel.file_url
            self.tableView.reloadData()
        }
    }
}
