//
//  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.orderTypeString = orderTypeString
//        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 = CGSize(width: 268.0, height: 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
    var orderTypeString = ""
    var orderType: Int = 1 {
        didSet {
            if orderType == 1 {
                orderTypeString = "优秀人才入境计划"
            } else if orderType == 2 {
                orderTypeString = "高才通人才计划"
            } else if orderType == 3 {
                orderTypeString = "输入内地人才入境计划"
            }
        }
    }
    
    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, _ 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, _ in
            if success {
            } else {
            }
        }
    }
    
    // 获取正式批 操作指引 确认状态
    func getOfficalGuildCheckStatus() {
        princleVM.getOfficialCheckStatus { success, _ in
            if success {
                if self.isFromHomeAlertViewFlag {
                    self.clickRightItemBtn()
                } else {
                    if !self.princleVM.isOfficialGuildCheckFlag {
                        self.princleVM.postAlertStatus(15) { _, _ in}// 首页 不再展示正式批 弹窗
                        
                        let view = YHOffivialApprovalSuccessCheckView.sheetView()
                        view.days = self.princleVM.lettersModel?.days ?? 0
                        view.orderType = self.orderType
                        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(200.fix)
            make.width.equalTo(294.fix)
            make.height.equalTo(530.fix)
        }
        paperImageV.layer.zPosition = 0
        
        view.addSubview(docImageV)
        docImageV.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(64.fix)
            make.width.equalTo(294.fix)
            make.height.equalTo(530.fix)
        }
        docImageV.layer.zPosition = 1
        
        docImageV.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.left.equalTo(50.fix)
            make.top.equalTo(140.fix)
            make.width.equalTo(294.fix)
            make.height.equalTo(530.fix)
        }
        contentView.transform = rotatedTransform()
        
        docImageV.addSubview(penImageV)
        penImageV.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(204.fix)
            make.right.equalToSuperview()
            make.width.equalTo(67.fix)
            make.height.equalTo(141.fix)
        }
        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(543.fix)
        }
        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(-50.fix)
            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(-20.fix)
        }
        
        bottomContentView.addSubview(bannerView)
        bannerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(148.fix)
            make.bottom.equalTo(indicatorView.snp.top).offset(-16.fix)
            
            make.top.equalToSuperview().offset(20.fix)
        }
        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, _ 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 {
        guard let cell = pagerView.dequeueReusableCell(withReuseIdentifier: YHOfficailLetterColledtionCell.cellReuseIdentifier, at: index) as? YHOfficailLetterColledtionCell else {
            return FSPagerViewCell()
        }
        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] _, _ 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
    }
}
