//
//  YHWorkExperiencePositionViewViewController.swift
//  galaxy
//
//  Created by EDY on 2024/11/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHWorkExperiencePositionViewViewController: YHBaseViewController {
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHWorkExperiencePositionViewModel!
    var baseDataSource: [YHSectionWorkExperienceModel]?
    var introductionDataSource: [YHWorkExperienceProjectModel]?
    var fileDataSource: [YHWorkExperienceFileModel]?
    var workExperienceID: String?
    var workID: Int = 0
    var orderID: Int = 0
    var positionId: Int = 0
    var isMore: Bool = false
    var isShowPrompt: Bool = false
    var isShowMessageSelect: Bool = true
    var isKeyboardShow: Bool = false
    var selectReasonIndex: Int = 5
    var selectEditItem = YHWorkExperienceFileModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHWorkExperiencePositionViewModel()
        gk_navTitle = "职位信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        setView()
        getData()
    }
    
    func getData() {
        viewModel.requestWorkPositionDetail(workID, positionId) {[weak self] success, error in
            guard let self = self else { return }
            if success ?? false {
                if self.viewModel.position.provide_certificate_type == 1 {
                    self.selectReasonIndex = 0
                } else if self.viewModel.position.provide_certificate_type == 4 {
                    self.selectReasonIndex = 1
                }
                updateDataSource()
            } else {
                self.viewModel.position.work_id = workID
                self.viewModel.position.order_id = orderID
                updateDataSource()
            }
        }
    }
    
    func getTextWithType(type: Int) -> ASAttributedString  {
        
        if type ==  0 {
           return .init("海外工作签证", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
        }
        if type ==  1 {
            let a:ASAttributedString = .init("以上均不能提供\n", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("(或将导致您的该段工作经验", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor(hex: 0x8993a2)))
            let c: ASAttributedString = .init("不被认可不予加分", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.failColor))
            let d: ASAttributedString = .init("，请尽可能准备以上材料并修改此选项)", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor(hex: 0x8993a2)))
           return a + b + c + d
        }
        return .init("", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor(alpha: 0.5)))
    }
    
    func getTipsWithType() -> [ASAttributedString] {
        return [self.getTextWithType(type: 0),
                self.getTextWithType(type: 1)]
    }
    
    
    func updateDataSource() {
        bottomView.nextButton.setTitle("提交", for: .normal)
        self.baseDataSource = self.viewModel.getBaseDataSource(false)
        self.tableView.reloadData()
    }
    
    func setView() {
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.sectionHeaderHeight = 16
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHWorkExperiencePositionListTableViewCell.self)
            tableView.register(cellWithClass: YHWorkExperiencePositionReasonTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = YHBottomNextView()
            bottom.nextblock = { [weak self] in
                bottom.nextButton.isEnabled = false
                guard let self = self else { return }
                if self.viewModel.isCanNext() {
                    self.viewModel.saveWorkPosition(callBackBlock: {[weak self] flag, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.hideFlashMessage()
                            YHHUD.flash(message: "提交成功")
                            self.navigationController?.popViewController()
                        }
                    })
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    YHHUD.flash(message: "您还有信息未填写")
                }
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                self.viewModel.saveWorkPosition(callBackBlock: {[weak self] flag, error in
                    guard let _ = self else { return }
                    if let error = error {
                        YHHUD.flash(message: error.errorMsg )
                    } else {
                        YHHUD.flash(message: "保存成功")
                    }
                })
            }
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        bottomView.layoutIfNeeded()
        bottomView.nextButton.addYinHeGradualLayer()
    }
    
    func showDeleteAlert(_ model: YHWorkExperienceProjectModel) {
        YHCommonAlertView.show("", "确定要删除该项目介绍吗？", "取消", "确认") {[weak self] in
            guard let self = self else { return }
           
        }
    }
    
}

extension YHWorkExperiencePositionViewViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.viewModel.position.is_international_work_experience == 1 {
            return 2
        } else {
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkExperiencePositionListTableViewCell.self)
            cell.dataSource = baseDataSource?[indexPath.row]
            cell.workExperienceBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
                let id = model.id
                if id != .id1 && id != .id2 && id != .id6 && id != .id10 && id != .id11 {
                    self.updateDataSource()
                }
            }
            cell.companyBlock = {[weak self] company in
                guard let self = self else { return }
//                self.viewModel.updateModel(company)
                self.updateDataSource()
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkExperiencePositionReasonTableViewCell.self)
            cell.selectItem = [self.selectReasonIndex]
            cell.dataSource = getTipsWithType()
            cell.selectBlock = {[weak self] index in
                guard let self = self else { return }
                self.selectReasonIndex = index.first ?? 5
                if self.selectReasonIndex == 0 {
                    self.viewModel.position.provide_certificate_type = 1
                } else {
                    self.viewModel.position.provide_certificate_type = 4
                }
            }
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            let array = baseDataSource?[indexPath.row].models ?? []
            var h = 0
            for i in 0..<array.count {
                let data = array[i]
                let message = data.message ?? ""
                let isShow = data.isShowPrompts ?? false
                if data.id == .id7 {
                    h = h + 72
                } else {
                    h = h + 52
                }
                if isShow && message.count == 0 {
                    h = h + 20
                }
            }
            return CGFloat(h + 52 + 14)
        } else {
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
