//
//  YHFileListViewController.swift
//  galaxy
//
//  Created by davidhuangA on 2024/3/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Photos
/*
 文件清单
 */


class YHFileListViewController: YHBaseViewController {
    
    var orderId : Int?
    private let certificateReqVM : YHCertificateViewModel = YHCertificateViewModel()
    let viewModel: YHCertificateViewModel = YHCertificateViewModel()

    private lazy var headView : YHFileListHeaerView = {
        let view = YHFileListHeaerView()
        view.backgroundColor = .clear
        return view
    }()
    
    private lazy var emptyView: YHFileListEmptyView = {
       let view = YHFileListEmptyView()
       view.isHidden = true
       view.bottomBtnClick = {
           [weak self] in
           guard let self = self else { return }
           NotificationCenter.default.post(name: YhConstant.YhNotification.didClickFileListBackToServiceTabNotifiction, object: nil)
       }
       return view
    }()
    
    private lazy var myScrollView : UIScrollView = {
        let view = UIScrollView()
        view.backgroundColor = .white
        return view
    }()
    
    
    private lazy var myContentView : YHFileListContentView = {
        let view = YHFileListContentView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius12
        view.clipsToBounds = true
        return view
    }()
    
    
    private lazy var bottomView : YHFileListBottomView = {
        var bottomView : YHFileListBottomView = YHFileListBottomView()
        bottomView.nextButton.isEnabled = false
        bottomView.layer.opacity = 0.8
        return bottomView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // 【WARNING】加载数据不要在viewWillAppear里请求数据 因为点击itemView上传文件拉起系统VC，dismiss后 所有itemView会被移除，导致itemView中使用的block找不到self(即itemView本身)引起上传功能bug
        //  pushVC返回需要刷新数据时通过通知或block重新刷新数据
        loadData()
        loadData2()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshListData), name: YhConstant.YhNotification.refreshCertificateFileListNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(didClickFileListItem(_:)), name: YhConstant.YhNotification.clickCertificateFileListItemNotifiction, object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    private lazy var footLable : UILabel = {
        
        let footLable = UILabel()
        footLable.text = "*感谢您对银河集团的信赖，以上信息均用于香港优才签证申请，银河集团承诺对您所提供的信息将绝对保密"
        footLable.textColor = .white
        footLable.textAlignment = .center
        footLable.font = UIFont.PFSC_R(ofSize: 12)
        footLable.numberOfLines = 0
        footLable.lineBreakMode = .byWordWrapping
        
        return footLable
    }()
}

extension YHFileListViewController {
    
    @objc func refreshListData() {
        loadData()
        loadData2()
    }
    
    func loadData() {
        if let orderID = orderId {
            let param = ["order_id":orderID,"node":"1","state":"1"] as [String : Any]
            certificateReqVM.getCertificateFileListData(params: param) { success, error in
                if success == true {
                    self.myContentView.dataModel = self.certificateReqVM.arrFileListData
                    self.myContentView.layoutIfNeeded()
                    
                    //
                    var isHaveData = false
                    for (_, item) in self.certificateReqVM.arrFileListData.enumerated() {
                        let arr = item?.supplement_list.filter { (item) -> Bool in
                            return item.checkStatus == 2 || item.checkStatus == 3
                         }
                        if let array = arr, array.count > 0 {
                            isHaveData = true
                        }
                    }
                    self.emptyView.isHidden = isHaveData
                    let r = self.myContentView.bounds
                    self.myContentView.frame = CGRect(x: kMargin, y: 217, width: KScreenWidth - 2*kMargin, height: r.height)
                    
                    self.footLable.frame = CGRect(x: 28, y: 217 + r.height + 29, width: KScreenWidth - 2*28, height: 36)
                    
                    self.myScrollView.contentSize =  CGSize(width: KScreenWidth, height: r.height + 217 + 29 + 36 + 41)
                    
                    
                    self.bottomView.nextButton.isEnabled = true
                    self.bottomView.layer.opacity = 1.0
                } else {
                    YHHUD.flash(message: error?.errorMsg ?? "请求出错")
                }
            }
        } else {
            printLog("error : orderID 为空")
        }
    }
    
    func loadData2() {
        if let orderID = orderId {
            let param = ["order_id":orderID,"node":"1","state":"1"] as [String : Any]
            certificateReqVM.getCertificateStatisticData(params: param) { success, error in
                if success == true {
                    self.headView.dataModel = self.certificateReqVM.certificateEntryModel
                } else {
                    YHHUD.flash(message: error?.errorMsg ?? "请求出错")
                }
            }
        } else {
            printLog("error : orderID 为空")
        }
    }
    
    
    func setupUI() {
        gk_navTitle = "待完善清单"
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        
        view.backgroundColor = UIColor(hex:0x0D37C7, alpha: 1.0)
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHFileListBottomView.viewH)
        }
        
        bottomView.block = {
            [weak self] flag in
            guard let self = self else { return }
            if flag == 1 {
                YHHUD.show(.progress(message: "正在生成图片"))
                if let image = self.captureScrollView(scrollView: self.myScrollView) {
                    YHHUD.hide()
                    saveImageToPhotosAlbum(image: image)
                } else {
                    YHHUD.hide()
                    YHHUD.flash(message: "生成图片失败")
                }
            }
        }
        
        myScrollView.backgroundColor = UIColor(hex:0x0D37C7, alpha: 1.0)
        
        view.addSubview(myScrollView)
        myScrollView.frame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: KScreenWidth, height: KScreenHeight - k_Height_NavigationtBarAndStatuBar - YHFileListBottomView.viewH)
        
        
        myScrollView.contentSize = CGSize(width: KScreenWidth, height: 2000)
        
        myScrollView.addSubview(headView)
        headView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: YHFileListHeaerView.viewH)
        
        myScrollView.addSubview(myContentView)
        myContentView.snp.makeConstraints { make in
            make.top.equalTo(217)
            make.left.equalTo(kMargin)
            make.width.equalTo(KScreenWidth - 2*kMargin)
        }
        
        myScrollView.addSubview(footLable)
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    func captureScrollView(scrollView : UIScrollView) -> UIImage? {
        
        scrollView.showsVerticalScrollIndicator = false
        UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, false, UIScreen.main.scale)
        let savedContentOffset = scrollView.contentOffset
        let savedFrame = scrollView.frame
        
        scrollView.contentOffset = CGPoint.zero
        scrollView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height)
        
        scrollView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        scrollView.contentOffset = savedContentOffset
        scrollView.frame = savedFrame
        UIGraphicsEndImageContext()
        
        scrollView.showsVerticalScrollIndicator = true
        return image
    }
    
    
    func saveImageToPhotosAlbum(image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.sync {
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            } else {
                YHHUD.flash(message: "没有访问图库权限")
            }
        }
    }
    
    
    @objc func image(image: UIImage,didFinishSavingWithError: NSError?,contextInfo: AnyObject) {
        if didFinishSavingWithError != nil {
            YHHUD.flash(message: "保存失败")
            return
        }
        YHHUD.flash(message: "保存成功")
    }
}

extension YHFileListViewController {
    
    // 点击文件清单
    @objc func didClickFileListItem(_ notification: Notification) {
        
        guard let userInfo = notification.userInfo else {
            return
        }
        
        guard let supplementId = userInfo["supplementId"] as? Int,
              let categoryId = userInfo["categoryId"] as? Int,
              let checkStatus = userInfo["checkStatus"] as? Int  else {
            
            printLog("参数不全")
            return
        }
        
        printLog("点击文件清单：\(userInfo)")
        
        if checkStatus == YHCertificateUploadStatus.preUpload.rawValue { // 待上传
            self.viewModel.showUploadSheetView(supplementId: supplementId) {
                [weak self] in
                guard let self = self else { return }
                DispatchQueue.main.async {
                    let vc = YHCertificateUploadContentListVC()
                    vc.orderId = self.orderId ?? 0
                    vc.categoryId = categoryId
                    vc.supplementId = supplementId
                    self.navigationController?.pushViewController(vc)
                }
                self.loadData()
                self.loadData2()
            }
            return
        }
        // 非待上传的进入详情
        let vc = YHCertificateUploadContentListVC()
        vc.orderId = self.orderId ?? 0
        vc.categoryId = categoryId
        vc.supplementId = supplementId
        self.navigationController?.pushViewController(vc)
    }
}
