//
//  YHImproveSchemeViewController.swift
//  galaxy
//
//  Created by Dufet on 2024/11/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Photos

class YHImproveSchemeViewController: YHBaseViewController {

    var orderId: Int = 0
    let viewModel = YHSchemeViewModel()

    var items:[YHImproveDetailModel] = []
    var isPass: Bool = false
    
    lazy var bgImgView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "my_scheme_improve_list_bg"))
        view.frame = CGRectMake(0, 0, KScreenWidth, 528)
        return view
    }()
    
    lazy var headerView: UIView = {
        let view = UIView()
        view.addSubview(greetLabel)
        
        let tipsLabel = UILabel()
        tipsLabel.numberOfLines = 0
        tipsLabel.font = UIFont.PFSC_R(ofSize: 14)
        tipsLabel.textColor = .white
        tipsLabel.text = "您好，根据您的信息，这是我们为您定制的提升方案，方案详情如下："
        view.addSubview(tipsLabel)
        
        let leftImgV = UIImageView(image: UIImage(named: "my_scheme_improve_wheatear_left"))
        let rightImgV = UIImageView(image: UIImage(named: "my_scheme_improve_wheatear_right"))
        view.addSubview(leftImgV)
        view.addSubview(rightImgV)
        
        greetLabel.snp.makeConstraints { make in
            make.top.equalTo(32+k_Height_NavigationtBarAndStatuBar)
            make.left.equalTo(leftImgV.snp.right).offset(8)
            make.right.equalTo(rightImgV.snp.left).offset(-8)
            make.height.equalTo(34)
        }
        
        leftImgV.snp.makeConstraints { make in
            make.width.equalTo(14)
            make.height.equalTo(24)
            make.left.equalTo(24)
            make.centerY.equalTo(greetLabel)
        }
        
        rightImgV.snp.makeConstraints { make in
            make.width.equalTo(14)
            make.height.equalTo(24)
            make.centerY.equalTo(greetLabel)
            make.right.lessThanOrEqualTo(-24)
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.top.equalTo(greetLabel.snp.bottom).offset(12)
            make.bottom.equalTo(-32)
        }
        return view
    }()
        
    lazy var greetLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_B(ofSize: 24)
        label.textColor = .init(hex: 0xFFDEC8)
        label.text = "尊敬的先生"
//        label.lineBreakMode = .byTruncatingMiddle
        return label
    }()

    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame:.zero, style:.grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHImproveTargetListCell.self, forCellReuseIdentifier: YHImproveTargetListCell.cellReuseIdentifier)
        tableView.register(YHIHKIdentityPlanCell.self, forCellReuseIdentifier: YHIHKIdentityPlanCell.cellReuseIdentifier)
        tableView.bounces = false
        tableView.backgroundView = self.bgView
        return tableView
    }()
    
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.addSubview(saveBtn)
        view.addSubview(leftBtn)
        view.addSubview(rightBtn)
        
        saveBtn.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(10)
            make.right.equalTo(leftBtn.snp.left).offset(-10)
            make.height.equalTo(46)
        }
        leftBtn.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.width.equalTo(94)
            make.right.equalTo(rightBtn.snp.left).offset(-10)
            make.height.equalTo(46)
        }
        rightBtn.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.right.equalTo(-16)
            make.height.equalTo(46)
            make.width.equalTo(158)
        }
        
        return view
    }()
    
    lazy var bgView: UIView = {
        let v = UIView()
        v.backgroundColor = .init(hex: 0xF8F9FB)
        v.addSubview(bgImgView)
        bgImgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(528)
        }
        return v
    }()
    
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.setTitle("重新选择提升目标", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didRightBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var leftBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .white
        btn.layer.borderColor = UIColor.brandMainColor.cgColor
        btn.layer.borderWidth = 1.0
        btn.setTitle("修改信息", for: .normal)
        btn.setTitleColor(.brandMainColor, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.addTarget(self, action: #selector(didLeftBtnClicked), for: .touchUpInside)
        btn.layer.cornerRadius = kCornerRadius3
        return btn
    }()
    
    lazy var saveBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(clickSaveBtn), for: .touchUpInside)

        let imgV = UIImageView()
        imgV.image = UIImage(named: "my_scheme_improve_save")
        btn.addSubview(imgV)
        
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 11)
        label.textColor = .mainTextColor
        label.text = "保存至手机"
        label.textAlignment = .center
        btn.addSubview(label)
        
        imgV.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(btn.snp.centerY).offset(5)
        }
        label.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(imgV.snp.bottom)
            make.height.equalTo(15)
        }
        return btn
    }()
    
    @objc func didLeftBtnClicked() {
        self.modifyInfo()
    }
    
    @objc func didRightBtnClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        view.backgroundColor = .init(hex: 0xF8F9FB)
        
        gk_navTitle = "提升方案"
        gk_navTitleColor = .white
        gk_backImage = UIImage(named: "back_icon_white")
        gk_navigationBar.backgroundColor = .clear
        
        self.view.addSubview(bgImgView)
        self.view.addSubview(tableView)
        self.view.addSubview(bottomView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(0)
            make.bottom.equalTo(bottomView.snp.top)
        }
        bottomView.isHidden = isPass
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(isPass ? 0.0 : 64+k_Height_safeAreaInsetsBottom())
        }
    
        view.bringSubviewToFront(gk_navigationBar)
        tableView.reloadData()
        tableView.isHidden = true
        bottomView.isHidden = true
        
        requestData()
    }
    
    override func backItemClick(_ sender: Any) {
        if isPass {
            // 进入上级我的方案界面
            self.navigationController?.popViewController(animated: true)
            
        } else { // 进入服务tab页
            self.navigationController?.popToRootViewController(animated: false)
            goTabBarBy(tabType: .service)
        }
    }

    func requestData() {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getImproveDetail(orderId: orderId) {
            [weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            items.removeAll()
            items.append(contentsOf: viewModel.improveDetailModel.improvePlanItem)
            tableView.reloadData()
            tableView.isHidden = false
            bottomView.isHidden = false
            var name = viewModel.improveDetailModel.username
            if name.count > 5 {
                name = String(name.prefix(5)) + "..."
            }
            greetLabel.text = "尊敬的\(name)\(viewModel.improveDetailModel.sex)"
        }
    }
    
    func modifyInfo() {
        YHHUD.show(.progress(message: "修改中..."))
        viewModel.modifyInfo(orderId: orderId) {
            [weak self] success, error in
            guard let self = self else { return }
            YHHUD.hide()
            if success {
                let vc = YHInformationPerfectListVC()
                vc.orderId = orderId
                navigationController?.pushViewController(vc)
                return
            }
            YHHUD.flash(message: error?.errorMsg ?? "修改失败")
        }
    }
}


extension YHImproveSchemeViewController : UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: YHIHKIdentityPlanCell.cellReuseIdentifier, for: indexPath) as! YHIHKIdentityPlanCell
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: YHImproveTargetListCell.cellReuseIdentifier, for: indexPath) as! YHImproveTargetListCell
        cell.arr = self.items
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                        
        if indexPath.row == 1 {
            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            goTabBarBy(tabType: .home)
            NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToHomePageIdentityTabNotification, object: nil)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return self.headerView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
}

extension YHImproveSchemeViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollY = scrollView.contentOffset.y
        if scrollY >= 44.0 {
            gk_navigationBar.backgroundColor = .init(hex: 0x082F84)
            
        } else {
            gk_navigationBar.backgroundColor = .clear
        }
    }
}

extension YHImproveSchemeViewController {
    
    @objc func clickSaveBtn() {
        
        YHHUD.show(.progress(message: "正在生成图片"))
        let originY = self.tableView.contentOffset.y
        
        self.tableView.scrollToRow(at: IndexPath(row: 1, section: 0), at: .bottom, animated: true)
        
        sleep(1)

        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.left.right.equalToSuperview()
                make.top.equalTo(0)
                make.bottom.equalTo(self.bottomView.snp.top)
            }
            self.tableView.setNeedsLayout()
            self.tableView.layoutIfNeeded()
            
            if let img = image {
                let targetFrame = CGRectMake(0, k_Height_NavigationtBarAndStatuBar, img.size.width, img.size.height-k_Height_NavigationtBarAndStatuBar)
                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: "保存成功")
    }
}
