//
//  YHOfficialApprovalResultVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import FSPagerView

import AttributedString

/*
 正式批 结果页
 */

class YHOfficialApprovalResultVC: YHBaseViewController {
    //背景
    lazy var bkgImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_bkg")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    //白纸
    lazy var paperImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_paper")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    //文档
    lazy var docImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_doc")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    //文档内容
    lazy var  contentView: YHOffivialApprovalSuccessView = {
        let view = YHOffivialApprovalSuccessView()
//        view.isHidden = true
        return view
    }()
    
    
    //pen
    lazy var penImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_pen")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    
    //bottom
    lazy var bottomImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_bottom_shadow")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    
    //光线
    lazy var lightImageV: UIImageView = {
        let imageV  = UIImageView()
        imageV.image = UIImage(named: "official_approval_result_top_shadow")
        imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        return imageV
    }()
    
    
    
    //bottom
    lazy var bottomContentView: UIView = {
        let view  = UIView()
        return view
    }()
    
    
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: 0xffffff, alpha: 0.6)
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize:12)
        label.text = "左滑查看其他获批信，当前"
        return label
    }()
    
    
    
    private lazy var bannerView: FSPagerView = {
        let view = FSPagerView()
        view.delegate = self
        view.dataSource = self
        view.bounces = false
        view.isInfinite = false
        view.removesInfiniteLoopForSingleItem = true
        view.alwaysBounceHorizontal = true
        view.register(YHOfficailLetterColledtionCell.self, forCellWithReuseIdentifier: YHOfficailLetterColledtionCell.cellReuseIdentifier)
        view.itemSize = CGSizeMake(268.0, 148)
        view.interitemSpacing = 20
        return view
    }()
    
    lazy var indicatorView : YHHomeBannerIndicatorView = {
        let view = YHHomeBannerIndicatorView()
        return view
    }()
    
    var dataArr: [YHOfficalLetterModel] = [] {
        didSet {
            self.indicatorView.indicatorItems = self.dataArr.count
            bannerView.reloadData()
            self.indicatorView.curIndicatorIndex = 0
            if dataArr.count > 0 {
                bannerView.reloadData()
                bannerView.selectItem(at: 0, animated: false)
                
                let aa: ASAttributedString = .init("左滑查看其他获批信，当前 ", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 0.6)))
                let bb: ASAttributedString = .init("1/\(self.dataArr.count)", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 1.0)))
                tipsLabel.attributed.text = aa + bb
                
                tipsLabel.isHidden = false
            } else {
                tipsLabel.isHidden = true
            }
        }
    }
    
    lazy var princleVM : YHPrincleViewModel = {
        let vm = YHPrincleViewModel()
        return vm
    }()
    
    
    //是否来着首页的弹窗
    var isFromHomeAlertViewFlag : Bool = false
    
    
    lazy var previewFileTool:YHFilePreviewTool = {
        let tool = YHFilePreviewTool(targetVC: UIViewController.current)
       return tool
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getApprovalLetter()
    }
}

private extension YHOfficialApprovalResultVC {
    func updateMainApplicationInfo() {
        guard let model = princleVM.lettersModel else { return  }
        contentView.dataModel = model
    }
    
    func updateLetterListInfo() {
        self.dataArr = self.princleVM.lettersModel?.list ?? []
    }
    
    //获取正式批信件列表
    func getApprovalLetter() {
        
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
            let param = ["orderId":orderID,"searchType":1]
            princleVM.getApprovalLetter(param: param) { success, error in
                if success {
                    //1、更新主申请人信息
                    self.updateMainApplicationInfo()
                    
                    //2、更新letter信息
                    self.updateLetterListInfo()
                    self.getOfficalGuildCheckStatus()
                    
                } else {
                    YHHUD.flash(message: "数据获取失败")
                }
            }
        } else {
            YHHUD.flash(message: "订单号为空")
        }
    }
    
    //上报弹窗状态
    func postAlertStatus(_ type : Int) {
        princleVM.postAlertStatus(type) { success, error in
            if success {
            } else {
            }
        }
    }
    
    //获取正式批 操作指引 确认状态
    func getOfficalGuildCheckStatus() {
        princleVM.getOfficialCheckStatus() { success, error in
            if success {
                if self.isFromHomeAlertViewFlag {
                    self.clickRightItemBtn()
                } else {
                    if !self.princleVM.isOfficialGuildCheckFlag {
                        self.princleVM.postAlertStatus(15) { success, error in}//首页 不再展示正式批 弹窗
                        
                        let view = YHOffivialApprovalSuccessCheckView.sheetView()
                        view.days = self.princleVM.lettersModel?.days ?? 0
                        view.show()
                        
                        view.block = { tag in
                            if tag == 0 {
                                self.clickRightItemBtn()
                            }
                        }
                    }
                }
            }
        }
    }
    
    func setupUI() {
        
        gk_navBarAlpha = 0.0
        gk_backImage = UIImage(named: "back_icon_white")
        addRightItem()
        
        view.addSubview(bkgImageV)
        bkgImageV.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        view.addSubview(paperImageV)
        paperImageV.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(CGFloat(200).scaleSizeFrom375px(size: 200))
            make.width.equalTo(CGFloat(294).scaleSizeFrom375px(size: 294))
            make.height.equalTo(CGFloat(530).scaleSizeFrom375px(size: 530))
        }
        paperImageV.layer.zPosition = 0
        
        
        view.addSubview(docImageV)
        docImageV.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(CGFloat(64).scaleSizeFrom375px(size: 64))
            make.width.equalTo(CGFloat(294).scaleSizeFrom375px(size: 294))
            make.height.equalTo(CGFloat(530).scaleSizeFrom375px(size: 530))
        }
        docImageV.layer.zPosition = 1
        
        docImageV.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.left.equalTo(CGFloat(50).scaleSizeFrom375px(size: 50))
            make.top.equalTo(CGFloat(140).scaleSizeFrom375px(size: 140))
            make.width.equalTo(CGFloat(294).scaleSizeFrom375px(size: 294))
            make.height.equalTo(CGFloat(530).scaleSizeFrom375px(size: 530))
        }
        contentView.transform = rotatedTransform()
        
        docImageV.addSubview(penImageV)
        penImageV.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(CGFloat(204).scaleSizeFrom375px(size: 204))
            make.right.equalToSuperview()
            make.width.equalTo(CGFloat(67).scaleSizeFrom375px(size: 67))
            make.height.equalTo(CGFloat(141).scaleSizeFrom375px(size: 141))
        }
        penImageV.layer.zPosition = 1
        
        
        
        view.addSubview(bottomImageV)
        bottomImageV.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(200)
        }
        bottomImageV.layer.zPosition = 2
        
        
        
        view.addSubview(lightImageV)
        lightImageV.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(CGFloat(543).scaleSizeFrom375px(size: 543))
        }
        lightImageV.layer.zPosition = 3
        
        
        
        
        //底部内容区域
        view.addSubview(bottomContentView)
        bottomContentView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
        }
        bottomContentView.layer.zPosition = 4
        
        bottomContentView.addSubview(tipsLabel)
        tipsLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(CGFloat(-50).scaleSizeFrom375px(size: -50))
            make.centerX.equalToSuperview()
        }
        
        
        bottomContentView.addSubview(indicatorView)
        indicatorView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(2)
            make.bottom.equalTo(tipsLabel.snp.top).offset(CGFloat(-20).scaleSizeFrom375px(size: -20))
        }
        
        
        bottomContentView.addSubview(bannerView)
        bannerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(CGFloat(148).scaleSizeFrom375px(size: 148))
            make.bottom.equalTo(indicatorView.snp.top).offset(CGFloat(-16).scaleSizeFrom375px(size: -16))
            
            make.top.equalToSuperview().offset(CGFloat(20).scaleSizeFrom375px(size: 20))
        }
        bannerView.layer.zPosition = 10
        
        
//        let transform = CGAffineTransform(scaleX: 1.0, y: 0.95)
//        bannerView.transformer = FSPagerViewTransformer(type:.linear)
//        bannerView.transformer?.minimumScale = 0.9
        bannerView.transformer?.minimumAlpha = 1.0
        
//        bannerView.itemSize = CGSize(width: CGFloat(268).scaleSizeFrom375px(size: 268), height: CGFloat(148).scaleSizeFrom375px(size: 148)).applying(transform)
        bannerView.reloadData()
    }
    
    private func rotatedTransform() -> CGAffineTransform {
        // 创建一个 CGAffineTransform 对象并设置旋转角度
        return CGAffineTransform(rotationAngle: -CGFloat.pi / 64) // 旋转 45 度
    }
    
    func addRightItem() {
        let searchButton = {
            let button = UIButton(type: .custom)
            button.frame = CGRect(x: 0, y: 0, width: 54, height: 24)
            button.setTitleColor(UIColor.white, for: .normal)
            button.setTitle("操作指引", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .right
            button.addTarget(self, action: #selector(self.clickRightItemBtn), for: .touchUpInside)
            return button
        }()
        let rightButtonItem =  UIBarButtonItem(customView: searchButton)
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = kMargin
    }
    
    @objc func clickRightItemBtn() {
        
        let view = YHOffivialApprovalGuildLineCheckView.sheetView()
        view.ischeckBeforeFlag = princleVM.isOfficialGuildCheckFlag
        view.block = {
            //点击了 正式批 操作指引
            if !self.princleVM.isOfficialGuildCheckFlag {
                self.princleVM.postAlertStatus(2) { success, error in
                    if success {
                        
                    } else {
                        
                    }
                    self.princleVM.isOfficialGuildCheckFlag = true
                }
            }
        }
        view.show()
    }
}


// MARK: - FSPagerView Delegate
extension YHOfficialApprovalResultVC: FSPagerViewDataSource, FSPagerViewDelegate {
    
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.dataArr.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: YHOfficailLetterColledtionCell.cellReuseIdentifier, at: index) as! YHOfficailLetterColledtionCell
        if index < dataArr.count {
            cell.dataModel = dataArr[index]
        }
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        if index < dataArr.count {
            
            let model = self.dataArr[index]
            self.previewFileTool.openXLSXRemoteFile(urlString: model.file_url_transformed, fileName: "")
            if model.read_status == 0 {
                self.princleVM.getAgreementCheck(model.archivist_id) {[weak self] success, error in
                    guard let _ = self else { return }
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    model.read_status = 1
                    self.bannerView.reloadData()
                }
            }
            
            return
        }
        
    }
    
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        self.indicatorView.curIndicatorIndex = targetIndex
        
        let aa: ASAttributedString = .init("左滑查看其他获批信，当前 ", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 0.6)))
        let bb: ASAttributedString = .init("\(targetIndex + 1)/\(self.dataArr.count)", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 1.0)))
        tipsLabel.attributed.text = aa + bb
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.indicatorView.curIndicatorIndex = pagerView.currentIndex
        
        let aa: ASAttributedString = .init("左滑查看其他获批信，当前 ", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 0.6)))
        let bb: ASAttributedString = .init("\(pagerView.currentIndex + 1)/\(self.dataArr.count)", .font(UIFont.PFSC_R(ofSize: 12)),.foreground(UIColor(hex: 0xffffff, alpha: 1.0)))
        tipsLabel.attributed.text = aa + bb
    }
}
