//
//  YHInformationPerfectListVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

/*
 *信息完善列表
 */
class YHInformationPerfectListVC: YHBaseViewController {
    var orderId : Int?
    private let serviceCenterMainReqVM : YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    
    private var hasSubmitFlag : Bool = false  {
        didSet {
            submitBtn.isHidden = hasSubmitFlag
            submitHoldView.isHidden = !hasSubmitFlag
            
            if hasSubmitFlag == true {
                headerTitleDesLable.text = "您已提交信息表"
            } else {
                var name = ""
                if let applicant = serviceCenterMainReqVM.informationFillStepModel {
                    name = applicant.applicantName.defaultStringIfEmpty(detaultValue: "尊敬的客户")
                }
                headerTitleDesLable.text = "您好," + name
            }
        }
    }
    
    private lazy var headerTitleDesLable : UILabel = {
        let titleLable = UILabel(text: "您好,-")
        titleLable.font = UIFont.PFSC_B(ofSize: 21)
        titleLable.textColor = UIColor.mainTextColor
        return titleLable
    }()
    
    
    private lazy var topBkg : UIView = {
        let imagV = UIImageView()
        imagV.image = UIImage(named: "service_center_head_bkg2")
        imagV.contentMode = .scaleAspectFill
        return imagV
        
    }()
    
    var homeTableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsHorizontalScrollIndicator = false
        tableView.showsVerticalScrollIndicator = false
        tableView.register(YHInformationPerfectCell.self,forCellReuseIdentifier: YHInformationPerfectCell.cellReuseIdentifier)
        return tableView
    }()
    
    var myHeadView : UIView = {
        let view = UIView()
        return view
    }()
    
    
    var myBottomView : UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    
    var submitHoldView : UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    var submitBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
}

extension YHInformationPerfectListVC {
    func submitSweetNotify() {
        let params = ["option":1,"order_id":orderId]
        serviceCenterMainReqVM.submitSweetNotifyOp(params: params as [String : Any]) { success, error in
            if success == true {
                YHInformationFillTipsAlertView.hideCheckView()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "发生错误,请重试")
            }
        }
    }
    
    func showTipsAlert() {
        YHInformationFillTipsAlertView.showCheckView { agree in
            if agree == true {
                printLog("点击了 确认 按钮")
                self.submitSweetNotify()
            } else {
                printLog("点击了 取消 按钮")
            }
        }
    }
    
    func loadData() {
        guard let orderId = orderId else { return}
        self.serviceCenterMainReqVM.getPersonInfoFillStep(params: ["orderId":orderId]) { success, error in
            if success == true {
    
                if self.serviceCenterMainReqVM.myInfoFillStep > 6 {
                    self.hasSubmitFlag = true
                } else {
                    self.hasSubmitFlag = false
                    
                    if self.serviceCenterMainReqVM.informationFillStepModel?.step == 6 {
                        self.submitBtn.layer.opacity = 1
                        self.submitBtn.isEnabled = true
                    } else {
                        self.submitBtn.layer.opacity = 0.4
                        self.submitBtn.isEnabled = false
                    }
                }
            }
            self.homeTableView.reloadData()
        }
    }
    
    @objc func goScoreVC() {
        //我的评分
        let vc = YHScoreDetailViewController()
        vc.orderId = orderId
        vc.model = serviceCenterMainReqVM.allInfoScoreModel
        navigationController?.pushViewController(vc)
        
    }
    
    @objc func goInfoListVC( ) {
        //个人信息表预览
        goInfoListVCOp()
    }
    
    
    private func goInfoListVCOp(index : Int = 0) {
        let vc = YHPreviewMainViewController()
        vc.orderId = orderId
        vc.myDefaultIndex = index
        navigationController?.pushViewController(vc)
    }
    
    
    @objc func clickSubmitBtn() {
        
        
        YHSubmitAllInfoCheckView.showCheckView(tipMsg: "确定是否提交信息？提交后将不能修改") { agree in
            if agree == true {
                printLog("点击了 确认 按钮")
                
                self.submitAllInfo()
                
            } else {
                printLog("点击了 取消 按钮")
            }
        }
    }
    
    func submitAllInfo() {
        guard let orderId = orderId else {
            printLog("error: orderId 为空")
            return
        }
        
        
        YHHUD.show(.progress(message: "数据提交中...."))
        serviceCenterMainReqVM.submitAllInfoOp(params: ["orderId" : orderId]) { [weak self] success, error in
            YHHUD.hide()
            if success == true {
                let model =  self?.serviceCenterMainReqVM.allInfoScoreModel
                YHSubmintAllInfoSuccessTipView.showCheckView(model: model) { agree in
                    
                    //1、刷新当前界面
                    self?.loadData()
                    
                    //2、跳转其他界面
                    if agree == true {
                        self?.goScoreVC()
                    }
                }
            } else {
                let msg = error?.errorMsg ?? "操作失败"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    func setupUI() {
        gk_navTitle = "信息完善"
        gk_navBarAlpha = 1.0
        gk_navLineHidden = true
        
        view.addSubview(topBkg)
        topBkg.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(259)
        }
        
        
        view.addSubview(myBottomView)
        myBottomView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(84)
        }
        
        
        submitBtn = UIButton(type: .custom)
        submitBtn.layer.opacity = 0.4
        submitBtn.setTitle("提交信息", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        submitBtn.isEnabled = false
        
        submitBtn.layer.cornerRadius = kCornerRadius6
        submitBtn.clipsToBounds = true
        myBottomView.addSubview(submitBtn)
        
        submitBtn.addTarget(self, action: #selector(clickSubmitBtn), for: .touchUpInside)
        submitBtn.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(48)
        }
        submitBtn.layoutIfNeeded()
        submitBtn.addYinHeGradualLayer()
        
        
        submitBtn.isHidden = hasSubmitFlag
        submitHoldView.isHidden = !hasSubmitFlag
        
        myBottomView.addSubview(submitHoldView)
        submitHoldView.snp.makeConstraints { make in
            make.top.equalTo(8)
            make.left.equalTo(kMargin)
            make.right.equalTo(-kMargin)
            make.height.equalTo(48)
        }
        
        
        let scoreButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor(hex:0xffffff)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("我的评分", for: .normal)
            button.setTitleColor(UIColor.brandMainColor, for: .normal)
            button.layer.cornerRadius = kCornerRadius6
            button.layer.borderWidth = 1
            button.layer.borderColor = UIColor.brandMainColor.cgColor
            button.addTarget(self, action: #selector(goScoreVC), for: .touchUpInside)
            return button
        }()
        submitHoldView.addSubview(scoreButton)
        scoreButton.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview()
            make.right.equalTo(submitHoldView.snp.centerX).offset(-6)
        }
        
        let infoButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor(hex:0x3c86f8)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("个人信息表", for: .normal)
            button.setTitleColor(.white, for: .normal)
            button.layer.cornerRadius = kCornerRadius6
            button.clipsToBounds = true
            button.addTarget(self, action: #selector(goInfoListVC), for: .touchUpInside)
            return button
        }()
        submitHoldView.addSubview(infoButton)
        infoButton.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(submitHoldView.snp.centerX).offset(6)
        }
        infoButton.layoutIfNeeded()
        infoButton.addYinHeGradualLayer()
        
        homeTableView.delegate = self
        homeTableView.dataSource = self
        view.addSubview(homeTableView)
        homeTableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(myBottomView.snp.top)
        }
        
        
        
        
        
        
        myHeadView.addSubview(headerTitleDesLable)
        headerTitleDesLable.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(26)
        }
        
        let desLable = UILabel(text: "此表由主申请人填写，我们将会根据您的个人信息制作资料清单，请按顺序填写，提交后1-2个工作日内联系您哦~")
        desLable.font = UIFont.PFSC_R(ofSize: 12)
        desLable.numberOfLines = 0
        desLable.textColor = UIColor.mainTextColor
        desLable.lineBreakMode = .byWordWrapping
        
        myHeadView.addSubview(desLable)
        desLable.snp.makeConstraints { make in
            make.top.equalTo(headerTitleDesLable.snp.bottom).offset(10)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.bottom.equalToSuperview()
        }
        
        myHeadView.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 96)
        homeTableView.tableHeaderView = myHeadView
        homeTableView.reloadData()
    }
}

// MARK: - UITableViewDelegate 和 UITableViewDataSource
extension YHInformationPerfectListVC : UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return serviceCenterMainReqVM.arrInfoFillStep.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return YHInformationPerfectCell.cellHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let newCell = tableView.dequeueReusableCell(withClass: YHInformationPerfectCell.self)
        newCell.selectionStyle = .none
        newCell.dataModel = serviceCenterMainReqVM.arrInfoFillStep[indexPath.row]
        return newCell
    }
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        printLog("点击了 \(indexPath.section)section  --- \(indexPath.row)row")
        
        //处理跳转逻辑
        handleJumpLogic( tapIndex : indexPath.row)
    }
    
    
    
    private func  handleJumpLogic(tapIndex : Int) {
        //开发模式下 任意跳转
#if DEBUG
        handleJumpLogicDebug(tapIndex: tapIndex)
        return
#endif
        //正式环境
        handleJumpLogicRelease(tapIndex: tapIndex)
    }
    
    private func  handleJumpLogicRelease(tapIndex : Int) {
        if self.serviceCenterMainReqVM.myInfoFillStep > 6 {
            goInfoListVCOp(index:tapIndex)
            return
        }
        
        if tapIndex <= serviceCenterMainReqVM.myInfoFillStep {
            handleJumpLogicDebug(tapIndex: tapIndex)
        } else {
            //请先完成 xxx 的填写
            if serviceCenterMainReqVM.myInfoFillStep < serviceCenterMainReqVM.arrInfoFillStep.count {
                let model = serviceCenterMainReqVM.arrInfoFillStep[serviceCenterMainReqVM.myInfoFillStep]
                let msg = "请先完成" + model.name + "填写"
                YHHUD.flash(message: msg)
            }
        }
    }
    
    private func  handleJumpLogicDebug(tapIndex : Int) {
        if tapIndex == 0 {
            if self.serviceCenterMainReqVM.informationFillStepModel?.sweet_notify_status == 0 {
                self.showTipsAlert()
                return
            }
            //主申请人信息
            let vc = YHMainApplicantInformationViewController()
            vc.orderId = orderId ?? 0
            navigationController?.pushViewController(vc)
            
        } else if tapIndex == 1 {
            //家庭程序信息
            
            let vc = YHFamilyMemberInfoListVC(orderId: orderId ?? 0)
            vc.orderId = orderId ?? 0
            navigationController?.pushViewController(vc)
            
        } else if tapIndex == 2 {
            //基本信息
            let vc = YHBasicInfoFillViewController()
            vc.orderId = orderId
            navigationController?.pushViewController(vc)
            
        } else if tapIndex == 3 {
            //学历/专业资格
            let vc = YHEducationInfoListVC()
            vc.orderId = orderId ?? 0
            navigationController?.pushViewController(vc)
            
        } else if tapIndex == 4 {
            //工作经历
            let vc = YHWorkExperienceListViewController()
            vc.orderId = orderId ?? 0
            navigationController?.pushViewController(vc)
            
        } else if tapIndex == 5 {
            //其他信息
            let vc = YHOtherInfoFillViewController()
            vc.orderId = orderId
            navigationController?.pushViewController(vc)
        } 
        else {
            
        }
    }
}
