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

import UIKit
import Alamofire
/*
 赴港计划书
 */

class YHHKPlanDoctumentVC: YHBaseViewController {
    var tableView: UITableView!
    
    var viewModel: YHMyDocumentsDetailViewModel = {
        let vm = YHMyDocumentsDetailViewModel()
        return vm
    }()
    
    var supplement_id: Int = 0
    var status : Int = 0
    private var canEditFlag : Bool = false
    
    private var timer : Timer?
    private var finishHandleFlag : Bool = true
    private var isSaving:  Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "赴港计划书"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        setView()
        getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        YHHUD.hide()
        finishHandleFlag = true
        cancelTimer()
    }
    
    override func backItemClick(_ sender: Any) {
        guard !isSaving else {
            return
        }
        isSaving = true
        saveOp { [weak self] _ in
            self?.isSaving = false
            if let navigationController = self?.navigationController {
                navigationController.popViewController(animated: true)
            } else {
                self?.dismiss(animated: true)
            }
        }
    }

    /// 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
        guard !isSaving else {
            return false
        }
        isSaving = true
        saveOp { [weak self] _ in
            self?.isSaving = false
            if let navigationController = self?.navigationController {
                navigationController.popViewController(animated: true)
            } else {
                self?.dismiss(animated: true)
            }
        }
        return false
    }
    
    private var bottomView : UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    lazy var bottomButton : UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_B(ofSize: 15)
        button.contentHorizontalAlignment = .center
        button.setTitle("提交", for: .normal)
        button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(clickSubmitBtn), for: .touchUpInside)
        return button
    }()
}

extension YHHKPlanDoctumentVC {
    
    
    fileprivate func cancelTimer() {
        guard self.timer != nil else {
            return
        }
        self.timer!.invalidate()
        self.timer = nil
    }
    
    
    fileprivate func startTimer() {
        cancelTimer()
        self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(3), target: self, selector: #selector(self.flipNext(sender:)), userInfo: nil, repeats:  false)
        RunLoop.current.add(self.timer!, forMode: .common)
    }
    
    @objc fileprivate func flipNext(sender: Timer?) {
        finishHandleFlag = true
        DispatchQueue.main.async {
            
            YHHUD.hide()
            YHHUD.flash(message: "提交成功")
            self.getData()
        }
    }
    
    
    func updateUI() {
        //1、不展示 2、待确认 3、核对中 4、核对中 5、已驳回 6、已定稿
        if status > 2 {
            canEditFlag = false
            bottomView.isHidden = true
            tableView.snp.removeConstraints()
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview()
            }
        } else {
            canEditFlag = true
            bottomView.isHidden = false
            
            tableView.snp.removeConstraints()
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(bottomView.snp.top).offset(-kMargin)
            }
        }
    }
    
    //点击提交按钮
    @objc func clickSubmitBtn() {
        
        if !checkDataOK() {
            YHHUD.flash(message: "需完成所有项的填写")
            return
        }
        
        YHCommonAlertView.show("", "是否已完成对文本框的内容修改，并确认提交？", "取消", "确认") {
            self.viewModel.requestSignaturePersonalURL(callBackBlock: {[weak self] success, error in
                guard let self = self else { return }
                self.submitOp()
            })
        }
    }
    
    private func checkDataOK() -> Bool {
        if viewModel.arrHKPlanData.count > 6 {
            
            let ret0 = viewModel.arrHKPlanData[0].contentCount > 0 ? true : false
            let ret1 = viewModel.arrHKPlanData[1].contentCount > 0 ? true : false
            let ret2 = viewModel.arrHKPlanData[2].contentCount > 0 ? true : false
            let ret3 = viewModel.arrHKPlanData[3].contentCount > 0 ? true : false
            let ret4 = viewModel.arrHKPlanData[4].contentCount > 0 ? true : false
            let ret5 = viewModel.arrHKPlanData[5].contentCount > 0 ? true : false
            let ret6 = viewModel.arrHKPlanData[6].contentCount > 0 ? true : false
            
            return ret0 && ret1 && ret2 && ret3 && ret4 && ret5 && ret6
        }
        return false
    }
    
    //保存数据
    private func saveOp(completion: @escaping (Bool) -> Void) {
        
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
            let params = ["order_id":orderID,
                          "supplement_id":supplement_id,
                          "career_achievement":viewModel.arrHKPlanData[0].content,
                          "academic_achievement":viewModel.arrHKPlanData[1].content,
                          "qualifications_and_awards":viewModel.arrHKPlanData[2].content,
                          "professional_skills":viewModel.arrHKPlanData[3].content,
                          "visa_contribution":viewModel.arrHKPlanData[4].content,
                          "plan_detail":viewModel.arrHKPlanData[5].content,
                          "other":viewModel.arrHKPlanData[6].content,
                          "content_save":0]
            
            YHHUD.show(.progress(message: ""))
            viewModel.submitHKPlanDocument(params) {[weak self ] success, error in
                guard let self = self else { return }
                YHHUD.hide()
                if success {
                    YHHUD.flash(message: "保存成功")
                    self.getData()
                    completion(true)
                } else {
                    YHHUD.flash(message: error?.errorMsg ?? "保存失败")
                    completion(false)
                }
            }
            
        } else {
            YHHUD.flash(message: "订单ID 为空")
            completion(false)
        }
    }
    
    //提交数据
    private func submitOp() {
        
        if viewModel.arrHKPlanData.count > 6 {
            if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                let params = ["order_id":orderID,
                              "supplement_id":supplement_id,
                              "career_achievement":viewModel.arrHKPlanData[0].content,
                              "academic_achievement":viewModel.arrHKPlanData[1].content,
                              "qualifications_and_awards":viewModel.arrHKPlanData[2].content,
                              "professional_skills":viewModel.arrHKPlanData[3].content,
                              "visa_contribution":viewModel.arrHKPlanData[4].content,
                              "plan_detail":viewModel.arrHKPlanData[5].content,
                              "other":viewModel.arrHKPlanData[6].content,
                              "content_save":1]
                cancelTimer()
                startTimer()
                
                finishHandleFlag = false
                YHHUD.show(.progress(message: ""))
                viewModel.submitHKPlanDocument(params) {[weak self ] success, error in
                    guard let self = self else { return }
                    
                    if self.finishHandleFlag {
                        return
                    }
                    self.finishHandleFlag = true
                    
                    self.cancelTimer()
                    YHHUD.hide()
                    if success {
                        YHHUD.flash(message: "提交成功")
                        self.getData()
                    } else {
                        YHHUD.flash(message: error?.errorMsg ?? "提交失败")
                    }
                }
                
            } else {
                YHHUD.flash(message: "订单ID 为空")
            }
        } else {
            YHHUD.flash(message: "参数不合法")
        }
    }
    
    func getData() {
        YHHUD.show(.progress(message: ""))
        viewModel.requestDocumentsDetail("\(supplement_id)", callBackBlock: {[weak self] success, error in
            YHHUD.hide()
            guard let self = self else { return }
            self.status = viewModel.mainModel?.prospectus.status ?? 0
            
            self.updateUI()
            
            for item in viewModel.arrHKPlanData {
                item.canEditFlag = self.canEditFlag
            }
            self.tableView.isHidden = false
            self.tableView.reloadData()
        })
    }
    
    func setView() {
        let tipsHoldView : UIView = UIView()
        tipsHoldView.backgroundColor = UIColor(hex: 0xE8F1FF, alpha: 1.0)
        tipsHoldView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 36.0)
        bottomView.addSubview(tipsHoldView)
        tipsHoldView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.right.equalTo(0)
            make.height.equalTo(36)
        }
        
        let iconImagV : UIImageView = UIImageView(image: UIImage(named: "my_doc_tips_icon"))
        iconImagV.contentMode = .scaleAspectFill
        tipsHoldView.addSubview(iconImagV)
        iconImagV.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(kMargin)
            make.width.height.equalTo(kMargin)
        }
        
        let tipsLable : UILabel = UILabel(text: "请确认文书内容，修改完成后点击提交。")
        tipsLable.textColor = .brandMainColor
        tipsLable.font = UIFont.PFSC_M(ofSize: 12)
        tipsHoldView.addSubview(tipsLable)
        tipsLable.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(iconImagV.snp.right).offset(4)
            make.height.equalTo(20)
            make.right.equalToSuperview().offset(-kMargin)
        }
        
        bottomView.addSubview(bottomButton)
        bottomButton.snp.makeConstraints { make in
            make.top.equalTo(tipsHoldView.snp.bottom)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(48)
        }
        
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(120)
        }
        
        bottomView.layoutIfNeeded()
        bottomButton.addYinHeGradualLayer()
        
        
        
        tableView = {
            let tableView = UITableView(frame:.zero, style:.grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHHKPlanCell.self)
            tableView.register(cellWithClass: YHHKPlanTipsCell.self)
            tableView.isHidden = true
            return tableView
        }()
        
        view.addSubview(tableView)
        
        if status > 3 {
            canEditFlag = false
            bottomView.isHidden = true
            
            tableView.snp.makeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalToSuperview()
                make.bottom.equalToSuperview()
            }
        } else {
            canEditFlag = true
            bottomView.isHidden = false
            tableView.snp.makeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalToSuperview()
                make.bottom.equalTo(bottomView.snp.top).offset(-kMargin)
            }
        }
    }
}

extension YHHKPlanDoctumentVC: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHHKPlanTipsCell.self)
            cell.selectionStyle = .none
            return cell
        }
        
        
        let cell = tableView.dequeueReusableCell(withClass: YHHKPlanCell.self)
        cell.selectionStyle = .none
        cell.arrData = viewModel.arrHKPlanData
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: kMargin))
        return view
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kMargin
    }
}
