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

import UIKit
import AttributedString
import JXSegmentedView
import Photos
import GKNavigationBarSwift
import TYSnapshotScroll

class YHMyFileListViewController: YHBaseViewController {

    let topSegmentHeight = 48.0
    var orderId: Int = 0
    var items: [YHFileListModel] = []
    lazy var titles: [String] = []
    let viewModel: YHCertificateViewModel = YHCertificateViewModel()

    lazy var navBar: YHCustomNavigationBar = {
        let bar = YHCustomNavigationBar.navBar()
        bar.backgroundColor = .clear
        bar.titleColor = .mainTextColor
        bar.title = "待完善清单"
        bar.backBlock = {
            [weak self] in
            guard let self = self else { return }
            self.navigationController?.popViewController(animated: true)
        }
        return bar
    }()
    
    lazy var navStatusBar: UIView = {
        let view = UIView()
        view.addSubview(self.navBar)
        self.navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_StatusBar)
            make.height.equalTo(k_Height_NavContentBar)
        }
        view.clipsToBounds = true
        return view
    }()
    
    let consentInsetTop = 140+k_Height_NavigationtBarAndStatuBar
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor.init(hex: 0xDCE4F1)
        tableView.separatorStyle = .none
        tableView.register(YHMyFileListCell.self, forCellReuseIdentifier: YHMyFileListCell.cellReuseIdentifier)
        tableView.register(YHMyFileListNoneCell.self, forCellReuseIdentifier: YHMyFileListNoneCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableHeaderView = self.headerView
        return tableView
    }()
    
    lazy var fakeTableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = UIColor.init(hex: 0xDCE4F1)
        tableView.separatorStyle = .none
        tableView.register(YHMyFileListCell.self, forCellReuseIdentifier: YHMyFileListCell.cellReuseIdentifier)
        tableView.register(YHMyFileListNoneCell.self, forCellReuseIdentifier: YHMyFileListNoneCell.cellReuseIdentifier)
        tableView.delegate = self
        tableView.dataSource = self
        let view = UIView(frame: self.headerView.frame)
        tableView.tableHeaderView = view
        return tableView
    }()
    
    lazy var bgImgView: UIImageView = {
        let bgView = UIImageView(image: UIImage(named: "my_filelist_bg"))
        return bgView
    }()
    
    lazy var totalLabel: UILabel = {
        let label = UILabel()
        return label
    }()
    
    let originHeaderHeight: CGFloat = 274.0-(88-k_Height_NavigationtBarAndStatuBar)
    
    lazy var headerView: UIView = {
        
        let top = 88-k_Height_NavigationtBarAndStatuBar
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: originHeaderHeight))
        myView.clipsToBounds = true
        bgImgView.frame = CGRect(x: 0, y: -top, width: KScreenWidth, height: 264)
        myView.addSubview(bgImgView)
        
        self.totalLabel.frame = CGRect(x: 26.0, y: 100+k_Height_NavigationtBarAndStatuBar+top, width: KScreenWidth-26*2, height: 20)
        bgImgView.addSubview(self.totalLabel)
        
        // 选择器背景
        let view = UIView(frame: CGRect(x: 16, y: self.consentInsetTop, width: KScreenWidth-16.0*2, height: 46))
        view.clipsToBounds = true
        myView.addSubview(view)
         
        let whiteView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth-16.0*2, height: 46.0+7.0))
        whiteView.backgroundColor = .white
        whiteView.layer.cornerRadius = 7.0
        whiteView.clipsToBounds = true
        view.addSubview(whiteView)
         
        let grayView = UIView(frame: CGRect(x: 1, y: 1, width: KScreenWidth-16.0*2-2, height: 46.0-2.0+6.0))
        grayView.backgroundColor = UIColor.init(hex: 0xE5E9F2)
        grayView.layer.cornerRadius = 6.0
        view.addSubview(grayView)
        
        view.addSubview(self.segmentView)
        return myView
    }()
    
    lazy var segmentView: YHSegmentView = {
        let view = YHSegmentView(frame: CGRect(x: 0, y: 0, width: KScreenWidth-16.0*2, height: 46))
        view.items = titles
        view.selectBlock = {
            [weak self] index in
            guard let self = self else { return }
            self.scrollToSection(index)
        }
        return view
    }()
    
    lazy var topSegmentView: YHSegmentView = {
        let view = YHSegmentView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: self.topSegmentHeight))
        view.items = titles
        view.isHidden = true
        view.selectBlock = {
            [weak self] index in
            guard let self = self else { return }
            self.scrollToSection(index)
        }
        return view
    }()
    
    lazy var bottomView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: k_Height_safeAreaInsetsBottom()+64))
        view.backgroundColor = .white
        view.addSubview(self.saveBtn)
        self.saveBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
        }
        return view
    }()
    
    lazy var saveBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("保存清单图", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        button.isUserInteractionEnabled = false
        button.layer.opacity = 0.3
        button.addTarget(self, action: #selector(clickSaveBtn), for: .touchUpInside)
        return button
    }()
    
    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
    }()
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if self.tableView.contentSize != self.fakeTableView.contentSize {
            self.tableView.contentSize = self.fakeTableView.contentSize
        }
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navigationBar.isHidden = true
        self.view.backgroundColor = UIColor.init(hex: 0xDCE4F1)
        self.view.addSubview(self.fakeTableView)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.bottomView)
        self.view.addSubview(self.navStatusBar)
        self.view.addSubview(self.topSegmentView)
        self.view.addSubview(self.emptyView)
        updateCount()
        
        self.navStatusBar.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
        self.topSegmentView.snp.makeConstraints { make in
            make.top.equalTo(self.navStatusBar.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(self.topSegmentHeight)
        }
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.bottomView.snp.top)
        }
        fakeTableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.bottomView.snp.top)
        }
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom()+64.0)
        }
        emptyView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
        loadData2()
    }
    
    func updateCount() {
        
        let submitCount = self.viewModel.certificateEntryModel?.to_be_submit_num ?? 0
        let reuploadCount = self.viewModel.certificateEntryModel?.reject_num ?? 0
        let textColor = UIColor.mainTextColor70
        let countColor = UIColor.brandMainColor
        let textFont = UIFont.PFSC_R(ofSize: 14)
        let countFont = UIFont.PFSC_B(ofSize: 16)
        let a: ASAttributedString = .init("您有 ", .font(textFont), .foreground(textColor))
        let b: ASAttributedString = .init(NSAttributedString(string: String(submitCount)), .font(countFont), .foreground(countColor))
        let c: ASAttributedString = .init(" 项待提交，", .font(textFont), .foreground(textColor))
        
        let d: ASAttributedString = .init(NSAttributedString(string: String(reuploadCount)), .font(countFont), .foreground(countColor))
        let e: ASAttributedString = .init(" 项需重传", .font(textFont), .foreground(textColor))
        totalLabel.attributed.text = a+b+c+d+e
    }
    
    func scrollToSection(_ section: Int) {
        if 0 <= section && section < self.items.count {
            // 自定义布局contentSize计算不准导致setContentOffset失效故采用此方法
            // fakeTableView 设计目的 1、每次刷新数据自动滚动到底部才能算完contentSize 2、scrollToRow后更正偏移会有抖动
            printLog("fakeTableView.contentSize \(self.fakeTableView.contentSize)")
            if self.tableView.contentSize != self.fakeTableView.contentSize {
                self.tableView.contentSize = self.fakeTableView.contentSize
            }
            
            self.fakeTableView.scrollToRow(at: IndexPath(row: 0, section: section), at: .top, animated: false)
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
                var gap = 0.0
                // 此处处理内容总长度不够滚到相应tab的差距
                let sectionRect = self.fakeTableView.rectForHeader(inSection: section)
                if self.fakeTableView.contentOffset.y >= 0.0, sectionRect.origin.y > self.fakeTableView.contentOffset.y {
                    gap = sectionRect.origin.y - self.fakeTableView.contentOffset.y
                }
                let offsetY = self.fakeTableView.contentOffset.y-k_Height_NavigationtBarAndStatuBar-self.topSegmentHeight+gap
                self.tableView.setContentOffset(CGPoint(x: 0, y: offsetY+4), animated: true)
            })
        }
    }
}

extension YHMyFileListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if 0 <= section && section < items.count {
            let model = items[section]
            if model.supplement_list.count > 0 {
                return model.supplement_list.count
            }
            return 1
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let noneCell = tableView.dequeueReusableCell(withIdentifier: YHMyFileListNoneCell.cellReuseIdentifier, for: indexPath) as? YHMyFileListNoneCell else {
            return UITableViewCell()
        }
        if 0 <= indexPath.section && indexPath.section < items.count {
            let model = items[indexPath.section]
            if model.supplement_list.count > 0 {
                guard let cell = tableView.dequeueReusableCell(withIdentifier: YHMyFileListCell.cellReuseIdentifier, for: indexPath) as? YHMyFileListCell else {
                    return UITableViewCell()
                }
                if 0 <= indexPath.row && indexPath.row < model.supplement_list.count {
                    cell.indexLabel.text = "\(indexPath.row+1)"
                    cell.model =  model.supplement_list[indexPath.row]
                    cell.isLastCell = indexPath.row == model.supplement_list.count-1
                }
                return cell
            }
        }
        return noneCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if 0 <= indexPath.section && indexPath.section < items.count {
            let model = items[indexPath.section]
            if model.supplement_list.count > 0 {
                return UITableView.automaticDimension
            }
        }
        return 72.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            let model = items[indexPath.section]
            if model.supplement_list.count > 0 {
                let supplement = model.supplement_list[indexPath.row]
                if supplement.checkStatus == YHCertificateUploadStatus.preUpload.rawValue { // 待上传
                    self.viewModel.showUploadSheetView(supplementId: supplement.id) {
                        [weak self] in
                        guard let self = self else { return }
                        DispatchQueue.main.async {
                            let vc = YHCertificateUploadContentListVC()
                            vc.orderId = self.orderId
                            vc.categoryId = model.category_id
                            vc.supplementId = supplement.id
                            self.navigationController?.pushViewController(vc)
                        }
                    }
                    return
                }
                // 非待上传的进入详情
                let vc = YHCertificateUploadContentListVC()
                vc.orderId = self.orderId
                vc.categoryId = model.category_id
                vc.supplementId = supplement.id
                self.navigationController?.pushViewController(vc)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = YHMyFileListHeaderView(frame: .zero)
        view.headerView.isHidden = true
        view.isShowCorner = items.count <= 1
        if 0 <= section && section < items.count {
            let model = items[section]
            view.titleLabel.text = model.ApplicantName
            if model.supplement_list.count > 0 {
                view.headerView.isHidden = false
            }
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if 0 <= section && section < items.count {
            let model = items[section]
            if model.supplement_list.count > 0 {
                return 103.0
            }
        }
        return 68.0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == items.count-1 {
            let view = YHMyFileListFooterView(frame: .zero)
            view.type = .qmas
            return view
        }
        let view = UIView()
        let view1 = UIView()
        view1.backgroundColor = .white
        view.addSubview(view1)
        view1.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.top.bottom.equalToSuperview()
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == items.count-1 {
           return UITableView.automaticDimension
        }
        return 0.01
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if scrollView == self.fakeTableView {
            return
        }
        
        printLog("offset: \(scrollView.contentOffset.y)")
        let segmentHeight = self.items.count <= 1 ? 0.0 : 46.0
        let gap = self.consentInsetTop-k_Height_NavigationtBarAndStatuBar-self.topSegmentHeight+segmentHeight
        self.navStatusBar.backgroundColor = scrollView.contentOffset.y > gap ? UIColor.white : UIColor.clear
        self.topSegmentView.backgroundColor = scrollView.contentOffset.y > gap ? UIColor.white : UIColor.clear
        self.topSegmentView.isHidden = scrollView.contentOffset.y < gap
        var find: Bool = false
        if items.count > 0 {
            for index in 0..<items.count {
                let rect = self.tableView.rectForHeader(inSection: index)
                // section 到顶部选择tab的距离
                let y = rect.origin.y-k_Height_NavigationtBarAndStatuBar-self.topSegmentHeight+24.0-self.tableView.contentOffset.y
                if 0.0 <= y, y < self.tableView.height-k_Height_NavigationtBarAndStatuBar-self.topSegmentHeight {
                    find = true
                    self.topSegmentView.updateSelectIndex(index)
                    self.segmentView.updateSelectIndex(index)
                    break
                }
            }
        }
        // section 没有在可见区域出现
        if !find {
            if let arr = self.tableView.indexPathsForVisibleRows, let lastIndexPath = arr.last {
                self.topSegmentView.updateSelectIndex(lastIndexPath.section)
                self.segmentView.updateSelectIndex(lastIndexPath.section)
            }
        }
    }
}

extension YHMyFileListViewController {
    
    @objc func clickSaveBtn() {
        
        YHHUD.show(.progress(message: "正在生成图片"))
        let originY = self.tableView.contentOffset.y

        if self.tableView.contentSize != self.fakeTableView.contentSize {
            self.tableView.contentSize = self.fakeTableView.contentSize
        }
        self.tableView.snp.remakeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(self.tableView.contentSize.height)
        }
        self.tableView.setNeedsLayout()
        self.tableView.layoutIfNeeded()
        
        TYSnapshotScroll.screenSnapshot(self.tableView, addMaskAfter: nil) {
            [weak self] image in
            YHHUD.hide()
            guard let self = self  else { return }
            self.tableView.snp.remakeConstraints { make in
                make.top.equalToSuperview()
                make.left.right.equalToSuperview()
                make.bottom.equalTo(self.bottomView.snp.top)
            }
            self.tableView.setNeedsLayout()
            self.tableView.layoutIfNeeded()
            
            if let img = image {
                // 裁剪
                let targetFrame = CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar-30, width: img.size.width, height: img.size.height-k_Height_NavigationtBarAndStatuBar+30)
                let croppedImage = img.cropped(to: targetFrame)
                self.saveImage(croppedImage)
                DispatchQueue.main.async {
                    self.tableView.setContentOffset(CGPoint(x: 0, y: originY), animated: false)
                }
                
            } else {
                YHHUD.flash(message: "生成图片失败")
            }
        }
    }

    func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.async {
                    UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存失败，请检查系统权限")
                }
            }
        }
    }
    
    @objc func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        if didFinishSavingWithError != nil {
            YHHUD.flash(message: "保存失败")
            return
        }
        YHHUD.flash(message: "保存成功")
    }
    
    func showEmptyView(_ show: Bool) {
        self.emptyView.isHidden = !show
        self.navStatusBar.backgroundColor = show ? UIColor.white : UIColor.clear
    }
}

extension YHMyFileListViewController {
    
    func loadData() {
        let param = ["order_id": orderId,
                     "node": "1",
                     "state": "1"] as [String: Any]
        viewModel.getCertificateFileListData(params: param) { success, error in
            self.items.removeAll()
            self.titles.removeAll()
            var isHaveData = false
            if success == true {
                for (_, item) in self.viewModel.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
                    }
                }
                
                for (index, model) in self.viewModel.arrFileListData.enumerated() {
                    if let model = model {
                        self.items.append(model)
                        self.titles.append(model.ApplicantName)
                    }
                }
                self.topSegmentView.items = self.titles
                self.segmentView.items = self.titles
                self.saveBtn.isUserInteractionEnabled = true
                self.saveBtn.layer.opacity = 1.0
                self.showEmptyView(!isHaveData)

            } else {
                self.saveBtn.isUserInteractionEnabled = false
                self.saveBtn.layer.opacity = 0.3
                YHHUD.flash(message: error?.errorMsg ?? "请求出错")
            }
            self.segmentView.isHidden = self.items.count <= 1
            self.headerView.height = self.items.count > 1 ?  self.originHeaderHeight : self.originHeaderHeight-self.topSegmentHeight
            self.tableView.reloadData()
            self.fakeTableView.tableHeaderView?.height = self.headerView.height
            self.fakeTableView.reloadData {
                let lastSection = self.items.count-1
                if 0 <= lastSection && lastSection < self.items.count {
                    let model = self.items[lastSection]
                    var lastRow = model.supplement_list.count-1
                    if lastRow < 0 {
                        lastRow = 0
                    }
                    self.tableView.setContentOffset(CGPoint.zero, animated: true)
                    self.fakeTableView.setContentOffset(CGPoint.zero, animated: false)
                    self.fakeTableView.scrollToRow(at: IndexPath(row: lastRow, section: lastSection), at: .top, animated: true)
                }
            }
        }
    }
    
    func loadData2() {
        let param = ["order_id": orderId,
                     "node": "1",
                     "state": "1"] as [String: Any]
        viewModel.getCertificateStatisticData(params: param) { success, error in
            if !success {
                YHHUD.flash(message: error?.errorMsg ?? "请求出错")
            }
            self.updateCount()
        }
    }
}
