//
//  YHPrincipleUploadListVC.swift
//  galaxy
//
//  Created by edy on 2024/4/29.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SmartCodable
import AttributedString
import IQKeyboardManagerSwift

class YHPrincipleUploadListVC: YHBaseViewController {

    var orderId: Int = 0
    var items: [SmartCodable] = []
    var isNeedShowSubmitCheckError: Bool = false
    
    let viewModel = YHPrincleViewModel()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.estimatedSectionHeaderHeight = 24.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHPrincipleUploadStatusCell.self, forCellReuseIdentifier: YHPrincipleUploadStatusCell.cellReuseIdentifier)
        tableView.register(YHPrincipleProfileListCell.self, forCellReuseIdentifier: YHPrincipleProfileListCell.cellReuseIdentifier)
        tableView.register(YHPrincipleEnvelopeCell.self, forCellReuseIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.init(hex: 0xF8F8F8)
        let imgView = UIImageView(image: UIImage(named: "principle_detail_head_bg"))
        view.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(imgView.snp.width)
        }
        return view
    }()
    
    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(didUploadBtnClicked), for: .touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "原则批"
        gk_navigationBar.backgroundColor = .clear
        createUI()
        items.removeAll()
        requestData()
    }
    
    lazy var previewFileTool: YHFilePreviewTool = {
        let tool = YHFilePreviewTool(targetVC: UIViewController.current)
       return tool
    }()
    
    func createUI() {
        view.addSubview(bgView)
        view.addSubview(tableView)
        view.addSubview(uploadBtn)

        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(uploadBtn.snp.top).offset(-8)
        }
        
        uploadBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-42)
            make.height.equalTo(48.0)
        }
    }
    
    func requestData() {
        
        let group = DispatchGroup()
        group.enter()
        // 请求上传信息（《赴港居留同意书》、申请人意见访问、其他证明材料）
        viewModel.getPrincipleUploadDetail(orderId: orderId) { _, _ in
            group.leave()
        }
        
        group.enter()
        let params: [String: Any] = ["order_id": orderId,
                                      "search_type": 1]
        // 请求 入境处已认收受理 和 申请资料已递交港府留档
        viewModel.getPrincipleWaitReviewResult(params: params) { _, _ in
            group.leave()
        }
        group.enter()
        viewModel.getEnvelopeInfo(orderId: orderId) { _, _ in
            group.leave()
        }
        
        group.notify(queue: .main) {
            self.updateData()
        }
    }
    
    func updateData() {
        self.items.removeAll()
        
        // 赴港居留同意书
        let agreementModel = self.viewModel.uploadDetailModel.file_data.agreement
        
        if agreementModel.id > 0 {
            agreementModel.customType = YHPrincipleAgreementType.agreement.rawValue
            agreementModel.isNeedTemplate = true
            
            self.items.append(agreementModel)
        }
        
        // 申请人意见访问
        let opinionModel = self.viewModel.uploadDetailModel.file_data.opinion
        if opinionModel.id > 0 {
            opinionModel.customType = YHPrincipleAgreementType.opinion.rawValue
            opinionModel.isNeedTemplate = true
            self.items.append(opinionModel)
        }
        
        // 其他证明条件
        let otherModel = self.viewModel.uploadDetailModel.file_data.other
        if otherModel.id > 0 {
            otherModel.customType = YHPrincipleAgreementType.other.rawValue
            otherModel.isNeedTemplate = false
            self.items.append(otherModel)
        }
        
        let isBottomUploadBtnHidden = !agreementModel.isCanUpload && !opinionModel.isCanUpload && !otherModel.isCanUpload
        self.uploadBtn.isHidden = isBottomUploadBtnHidden
        uploadBtn.snp.updateConstraints { make in
            let bottomMargin = isBottomUploadBtnHidden ? 48 : -42
            make.bottom.equalTo(bottomMargin)
        }
        
        // 已获得港府甄选名额
        if !self.viewModel.envelopModel.name.isEmpty, !self.viewModel.envelopModel.url.isEmpty {
            self.items.append(self.viewModel.envelopModel)
        }
        
        let waitResultModel = self.viewModel.waitResultModel
        // 入境处已认收受理
        let model2 = waitResultModel.copy()
        model2.type = .entry
        model2.title = "入境处已认收受理"
        model2.subTitle = "申请确认通知书：(来自香港入境处)"
        model2.isUnfold = false
        self.items.append(model2)
        
        // 申请资料已递交港府留档
        let model3 = waitResultModel.copy()
        model3.type = .profile
        model3.title = "申请资料已递交港府留档"
        model3.subTitle = "档案号："
        model3.isUnfold = false
        self.items.append(model3)
        
        self.tableView.reloadData()
        self.view.setNeedsLayout()
        self.view.layoutIfNeeded()
        
    }
}

extension YHPrincipleUploadListVC {
    
    func checkMustItems() -> Bool {
        // 赴港居留同意书
        let agreementModel = self.viewModel.uploadDetailModel.file_data.agreement
        if agreementModel.isMust, agreementModel.id > 0, agreementModel.content_url.count <= 0 {
            YHHUD.flash(message: "请上传必要文件赴港居留同意书")
            return false
        }
        // 申请人意见访问
        let opinionModel = self.viewModel.uploadDetailModel.file_data.opinion
        if  opinionModel.isMust, opinionModel.id > 0, opinionModel.content_url.count <= 0 {
            YHHUD.flash(message: "请上传必要文件申请人意见访问")
            return false
        }
        
        //  其他证明条件
        let otherModel = self.viewModel.uploadDetailModel.file_data.opinion
        if  otherModel.isMust, otherModel.id > 0, otherModel.content_url.count <= 0 {
            YHHUD.flash(message: "请上传必要文件其他证明条件")
            return false
        }
        return true
    }
    
    @objc func didUploadBtnClicked() {
        
        let isMustHave = self.checkMustItems()
        if !isMustHave {
            isNeedShowSubmitCheckError = true
            self.tableView.reloadData()
            return
        }
        
        isNeedShowSubmitCheckError = false

        var files: [YHPrincipleRequestModel] = []
        
        // 赴港居留同意书
        let agreementModel = self.viewModel.uploadDetailModel.file_data.agreement
        let agree = YHPrincipleRequestModel()
        agree.id = agreementModel.id
        agree.check_status = agreementModel.check_status
        if agree.check_status == YHPrincipleUploadStatus.rejected.rawValue { // 已驳回
            agree.check_status = YHPrincipleUploadStatus.review.rawValue
        }
        agree.file_url = agreementModel.content_url
        files.append(agree)
        
        // 申请人意见访问
        let opinionModel = self.viewModel.uploadDetailModel.file_data.opinion
        let opinion = YHPrincipleRequestModel()
        opinion.id = opinionModel.id
        opinion.check_status = opinionModel.check_status
        if opinion.check_status == YHPrincipleUploadStatus.rejected.rawValue { // 已驳回
            opinion.check_status = YHPrincipleUploadStatus.review.rawValue
        }
        opinion.file_url = opinionModel.content_url
        files.append(opinion)

        // 其他证明条件
        let otherModel = self.viewModel.uploadDetailModel.file_data.other
        let other = YHPrincipleRequestModel()
        other.id = otherModel.id
        other.check_status = otherModel.check_status
        if other.check_status == YHPrincipleUploadStatus.rejected.rawValue { // 已驳回
            other.check_status = YHPrincipleUploadStatus.review.rawValue
        }
        other.file_url = otherModel.content_url
        files.append(other)
        
        YHHUD.show(.progress(message: "上传中"))
        viewModel.uploadPrincipleFiles(files) { success, error in
            YHHUD.hide()
            if success {
                YHHUD.flash(message: "上传成功")
                self.requestData()
                return
            }
            let errMsg = error?.errorMsg ?? "上传失败"
            YHHUD.flash(message: errMsg)
        }
    }
    
    func showFileOperationAlertView(_ index: Int, itemModel: YHPrincipleAgreementModel) {
        
        if index < 0 || index > itemModel.content_url.count {
            return
        }
        
        let model = itemModel.content_url[index]
        let arr = [YHCertificateEditItem(type: .rename, title: "重命名"),
                   YHCertificateEditItem(type: .preview, title: "预览"),
                   YHCertificateEditItem(type: .delete, title: "删除"),
                   YHCertificateEditItem(type: .cancel, title: "取消")]
        
        YHCertificateEditSheetView.sheetView(items: arr) {
            [weak self] editType in
            guard let self = self else { return }
            print("editType:\(editType.rawValue)")
            
            if editType == .rename { // 重命名
                IQKeyboardManager.shared.isEnabled = false
                
                var name = model.getFileNameWithoutSuffix()
                if name.count > 30 {
                    name = name[safe: ..<30]!
                }
                let view = YHPrincipleFileRenameView.renameView(name: name)
                view.confirmBlock = {
                    [weak self] text in
                    guard let self = self else { return }
                    model.name = text + "." + model.getFileSuffixName()
                    self.tableView.reloadData()
                }
                view.show()
                
            } else if editType == .delete { // 删除
                
                let msg = "您确定要删除文档\(model.name)吗?"
                YHTwoOptionAlertView.showAlertView(message: msg, aligentment: .left) { sure in
                    if !sure { return }
                    // 删除
                    var targetIndex: Int = -1
                    for (index, m) in itemModel.content_url.enumerated() {
                        if m.url == model.url {
                            targetIndex = index
                            break
                        }
                    }
                    itemModel.content_url.remove(at: targetIndex)
                    self.tableView.reloadData()
                }
            } else if editType == .preview { // 预览
                print(model.url)
                let fileUrl = !model.url.isEmpty ? model.url : model.fileUrl
                YHHUD.show(.progress(message: "加载中..."))
                self.viewModel.getRealUsefulUrl(fileUrl) {
                    [weak self] resultUrl in
                    YHHUD.hide()
                    guard let self = self else { return }
                    self.previewFileTool.openXLSXRemoteFile(urlString: resultUrl, fileName: model.name)
                }
            }
        }.show()
    }
}

extension YHPrincipleUploadListVC: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) as? UITableViewCell else {
            return UITableViewCell()
        }
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let m = items[indexPath.row]

            if m is YHPrincipleWaitResultModel {
                // 入境处已认收受理 和 申请资料已递交港府留档 cell
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleProfileListCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleProfileListCell else {
                    return UITableViewCell()
                }
                guard let model = m as? YHPrincipleWaitResultModel else {
                    return UITableViewCell()
                }
                cell.updateModel(model)
                // 点击展开
                cell.expandClick = {
                    [weak self] isUnfold in
                    guard let self = self else { return }
                    model.isUnfold = isUnfold
                    self.tableView.reloadData()
                }
                return cell
            }
            
            if m is YHPrincipleEnvelopeModel {
                //  已获得港府甄选名额 信封cell
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleEnvelopeCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleEnvelopeCell else {
                    return UITableViewCell()
                }
                if let model = m as? YHPrincipleEnvelopeModel {
                    cell.updateModel(model)
                    // 点击展开
                    cell.expandClick = {
                        [weak self] isUnfold in
                        guard let self = self else { return }
                        model.isUnfold = isUnfold
                        self.tableView.reloadData()
                    }
                }
                return cell
            }
            
            if m is YHPrincipleAgreementModel {
                //  上传文件 cell
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHPrincipleUploadStatusCell.cellReuseIdentifier, for: indexPath) as? YHPrincipleUploadStatusCell else {
                    return UITableViewCell()
                }
                if let model = m as? YHPrincipleAgreementModel {
                    if isNeedShowSubmitCheckError, model.isMust == true, model.content_url.count <= 0 {
                        model.isShowRedTips = true
                    } else {
                        model.isShowRedTips = false
                    }
                    cell.updateModel(model)
                    // 点击展开
                    cell.expandClick = {
                        [weak self] isUnfold in
                        guard let self = self else { return }
                        model.isUnfold = isUnfold
                        self.tableView.reloadData()
                    }
                    // 文件操作
                    cell.fileEditBlock = {
                        [weak self] _, index in
                        guard let self = self else { return }
                        self.showFileOperationAlertView(index, itemModel: model)
                    }
                    // 点击文件直接预览
                    cell.fileClickBlock = {
                        [weak self] fileModel, _ in
                        guard let self = self else { return }
                        // 直接点击文件所在行进行预览
                        let fileUrl = !fileModel.url.isEmpty ? fileModel.url : fileModel.fileUrl
                        YHHUD.show(.progress(message: "加载中..."))
                        self.viewModel.getRealUsefulUrl(fileUrl) {
                            [weak self] resultUrl in
                            YHHUD.hide()
                            guard let self = self else { return }
                            self.previewFileTool.openXLSXRemoteFile(urlString: resultUrl, fileName: model.name)
                        }
                    }
                    // 上传文件点击
                    cell.uploadBtnClick = {
                        [weak self] _ in
                        guard let self = self else { return }
                        if model.content_url.count >= 10 {
                            YHHUD.flash(message: "最多上传10张照片或文件")
                            return
                        }
                        self.showSelectImageAndFileView(model)
                    }
                    // 点击模板
                    cell.templateBtnClick = {
                        [weak self] _ in
                        guard let self = self else { return }
                        self.showPreviewAndMailList(model)
                        
                    }
                }
                return cell
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        if 0 <= indexPath.section && indexPath.section < items.count {

        }
    }

    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return self.getHeaderView()
    }
    
    func getHeaderView() -> UIView {
        
        let view = UIView()
        
        let titleLabel = UILabel()
        
        var name = self.viewModel.waitResultModel.applicant.userName
        if name.count > 5 {
            name = String(name.prefix(5)) + "..."
        }
        let callName = self.viewModel.waitResultModel.applicant.sex == 2 ? "女士" : "先生"
        
        let title: ASAttributedString = .init("祝贺您，\(name)\(callName)！", .font(UIFont.PFSC_M(ofSize: 24)), .foreground(UIColor.mainTextColor))
        titleLabel.attributed.text = title
        view.addSubview(titleLabel)
        
        let detailLabel = UILabel()
        detailLabel.numberOfLines = 0
        let str1: ASAttributedString = .init("您【与家人】申请的【优秀人才入境计划】，", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        let str2: ASAttributedString = .init("已获得港府的甄选名额", .font(UIFont.PFSC_B(ofSize: 14)), .foreground(UIColor.brandMainColor))
        let str3: ASAttributedString = .init("，请您于", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        let time: ASAttributedString = .init("\(self.viewModel.uploadDetailModel.convertDateFormat())", .font(UIFont.PFSC_B(ofSize: 14)), .foreground(UIColor.brandMainColor))
        let str4: ASAttributedString = .init("前补充更多文件，即可等待获得港府的正式批准！", .font(UIFont.PFSC_R(ofSize: 14)), .foreground(UIColor.mainTextColor(alpha: 0.7)))
        detailLabel.attributed.text = str1 + str2 + str3 + time + str4
        view.addSubview(detailLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(34)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-36)
        }
    
        return view
    }
    
    func showPreviewAndMailList(_ model: YHPrincipleAgreementModel) {
        
        // 弹窗 选择发送邮箱
        let items = [YHCertificateEditItem(type: .preview, title: "在线预览"),
                     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 == .preview {
                if let template = model.file_url.first {
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getRealUsefulUrl(template.url) {
                        [weak self] resultUrl in
                        YHHUD.hide()
                        guard let self = self else { return }
                        self.previewFileTool.openXLSXRemoteFile(urlString: resultUrl, fileName: template.name)
                    }
                }
                
            } else if editType == .sendEmail {
                
               let mailView = YHPrincipleSendMailView.mailView()
               mailView.confirmBlock = {
                   [weak self] mail in
                   guard let self = self else { return }
                   printLog("mail ： \(mail)")

                   if let template = model.file_url.first {
                       // 确认发送弹窗
                       YHCheckEamilAlertView.show(nil, mail, "取消", "确认", .center) {
                           YHHUD.show(.progress(message: "发送邮件中"))
                           self.viewModel.sendMail(mail, template: template) { success, error in
                               YHHUD.hide()
                               if success {
                                   YHHUD.flash(message: "发送成功")
                               } else {
                                   let errMsg = error?.errorMsg ?? "发送失败"
                                   YHHUD.flash(message: errMsg)
                               }
                           }
                       }
                       
                   } else {
                       YHHUD.flash(message: "模板链接为空")
                   }
               }
               mailView.show()

            }
        }.show()
    }
    
    func showSelectImageAndFileView(_ model: YHPrincipleAgreementModel) {
        
        let sheetView = YHCertificateUploadSheetView.sheetView()
        sheetView.tips = "支持的文件格式为jpg/jpeg、png、doc/docx、ppt/pptx、pdf, xls/xlsx，最多可上传10张图片或文件"
        sheetView.imageMaxCount = 10
        sheetView.maxSelectImageCount = 10-model.content_url.count
        sheetView.fileTypes = [ "public.image",
                                "com.adobe.pdf",
                                "com.microsoft.word.doc",
                                "org.openxmlformats.wordprocessingml.document",
                                "com.microsoft.powerpoint.ppt",
                                "org.openxmlformats.presentationml.presentation",
                                "org.openxmlformats.spreadsheetml.sheet",
                                "com.microsoft.excel.xls" ]
        // 上传文件
        sheetView.uploadFilesBlock = {
            [weak self] fileUrl in
            guard let self = self else { return }
            print(fileUrl)
            YHHUD.show(.progress(message: "上传中..."))
            self.viewModel.uploadFile(fileUrl.absoluteString) {
                [weak self] successUrl, _ in
                
                YHHUD.hide()

                guard let self = self else { return }
                
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    let fileName = successUrl.lastPathComponent
                    let suffixName = successUrl.pathExtension.lowercased()
                    
                    let urlModel = YHPrincipleContentUrlModel()
                    urlModel.name = fileName
                    urlModel.url = successUrl
                    urlModel.fileUrl = successUrl
                    let dateFormatter = self.viewModel.getUploadTimeFormat()
                    let dateString = dateFormatter.string(from: Date())
                    urlModel.updated_at = dateString
                    model.content_url.insert(urlModel, at: 0)
                    self.tableView.reloadData()
                }
            }
        }
        // 上传图片
        sheetView.uploadImageBlock = {
            [weak self] targetImgArr in
            guard let self = self else { return }
            self.viewModel.uploadImageArr(targetImgArr) {
                [weak self] resultArr  in
                guard let self = self else { return }
                model.content_url.insert(contentsOf: resultArr, at: 0)
                self.tableView.reloadData()
            }
        }
        sheetView.show()
    }
}
