//
//  YHWorkIntroductionViewController.swift
//  galaxy
//
//  Created by EDY on 2024/2/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHWorkIntroductionViewController: YHBaseViewController {
    typealias SaveBlock = () -> ()
    var saveBlock: SaveBlock?
    var nameTextField: UITextField!
    var startTextField: UITextField!
    var endTextField: UITextField!
    var longTimeButton: UIButton!
    var messageTextField: UITextView!
    var startButton: UIButton!
    var endButton: UIButton!
    var promptsLabel: UILabel!
    var actionView: YHWorkActionView!
    var bottomView: UIView!
    var bottomButton: UIButton!
    var viewModel: YHWorkIntroductionViewModel!
    var workModel: YHWorkExperienceDetailModel?
    var dataSource: YHWorkExperienceProjectModel = YHWorkExperienceProjectModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "工作经验信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        viewModel = YHWorkIntroductionViewModel()
        setView()
        getData()   
        isShowPromptsLabel()
        // Do any additional setup after loading the view.
    }
    
    func getData() {
        viewModel?.requestIntroducetionExample(callBackBlock: { success, error in
            
        })
    }
    
    func setView() {
        view.backgroundColor = .white
        let array = ["项目名称", "项目开始时间", "项目结束时间", "项目业绩/亮点"]
        for i in 0..<array.count {
            let label = UILabel()
            label.textColor = UIColor.mainTextColor
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.text = array[i]
            view.addSubview(label)
            label.snp.makeConstraints { make in
                make.left.equalTo(18)
                make.top.equalTo(CGFloat(51 * i) + k_Height_NavigationtBarAndStatuBar)
                make.width.equalTo(100)
                make.height.equalTo(51)
            }
            if i != array.count - 1 {
                let line = UIView()
                line.backgroundColor = UIColor(hex: 0xf0f0f0)
                view.addSubview(line)
                line.snp.makeConstraints { make in
                    make.left.equalTo(18)
                    make.top.equalTo(CGFloat(51 * (i + 1)) + k_Height_NavigationtBarAndStatuBar)
                    make.right.equalTo(-18)
                    make.height.equalTo(1)
                }
            }
        }

        nameTextField = {
            let textField = UITextField()
            textField.font = UIFont.PFSC_R(ofSize: 14)
            textField.placeholder = "如方便提供，请填写"
            textField.text = dataSource.project_name
            textField.delegate = self
            return textField
        }()
        view.addSubview(nameTextField)
        nameTextField.snp.makeConstraints { make in
            make.right.equalTo(-18)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.equalTo(117)
            make.height.equalTo(51)
        }
        
        startTextField = {
            let textField = UITextField()
            textField.font = UIFont.PFSC_R(ofSize: 14)
            textField.placeholder = "开始时间"
            textField.isEnabled = false
            textField.isUserInteractionEnabled = false
            textField.text = dataSource.project_start_time
            return textField
        }()
        view.addSubview(startTextField)
        startTextField.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 52)
            make.left.equalTo(117)
            make.height.equalTo(51)
            make.right.equalTo(-18)
        }
        
        startButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(startClick), for: .touchUpInside)
            return button
        }()
        view.addSubview(startButton)
        startButton.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 52)
            make.left.equalTo(117)
            make.height.equalTo(51)
            make.right.equalTo(-18)
        }
        
        endTextField = {
            let textField = UITextField()
            textField.font = UIFont.PFSC_R(ofSize: 14)
            textField.placeholder = "结束时间"
            textField.isEnabled = false
            textField.isUserInteractionEnabled = false
            if dataSource.project_end_time != "至今" {
                textField.text = dataSource.project_end_time
            } else {
                textField.text = ""
            }
            return textField
        }()
        view.addSubview(endTextField)
        endTextField.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 104)
            make.left.equalTo(117)
            make.height.equalTo(51)
            make.right.equalTo(-18)
        }
        
        endButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(endClick), for: .touchUpInside)
            return button
        }()
        view.addSubview(endButton)
        endButton.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 104)
            make.left.equalTo(117)
            make.height.equalTo(51)
            make.right.equalTo(-18)
        }
        
        longTimeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "main_time_normal"), for: .normal)
            button.setImage(UIImage(named: "login_privacy_agree"), for: .selected)
            button.setTitleColor(UIColor.mainTextColor, for: .normal)
            button.setTitle("至今", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .right
            button.addTarget(self, action: #selector(longTimeButtonClick), for: .touchUpInside)
            if dataSource.project_end_time == "至今" {
                button.isSelected = true
            } else {
                button.isSelected = false
            }
            return button
        }()
        view.addSubview(longTimeButton)
        if dataSource.project_end_time != "至今" {
            longTimeButton.snp.makeConstraints { make in
                make.right.equalTo(-18)
                make.centerY.equalTo(endTextField.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(43)
            }
            endTextField.isHidden = false
            endButton.isHidden = false
        } else {
            longTimeButton.snp.makeConstraints { make in
                make.left.equalTo(117)
                make.centerY.equalTo(endTextField.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(43)
            }
            endTextField.isHidden = true
            endButton.isHidden = true
        }
        longTimeButton.iconInLeft(spacing: 3)
        
        
        messageTextField = {
            let textField = UITextView()
            textField.backgroundColor = UIColor.contentBkgColor
            textField.font = UIFont.PFSC_R(ofSize: 14)
            textField.layer.cornerRadius = kCornerRadius6
            textField.delegate = self
            textField.text = dataSource.project_highlights
            return textField
        }()
        view.addSubview(messageTextField)
        messageTextField.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.top.equalTo(208 + k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 124)
        }
    
        promptsLabel = {
            let prompts = UILabel()
            prompts.font = UIFont.PFSC_R(ofSize: 14)
            prompts.textColor = UIColor(hex: 0xc0c0c0)
            prompts.text = "在职期间负责的核心项目，如果负责过多个项目，请分段描述：\n\n例子：\n\n模式1、本人对XX项目展开深入研究，通过对XX方法/方式，研究出XX。此外，她还指出XX问题，反映了XX。XX的研究成果对XX产生了重要性，为XX领域/方面提供参考依据；\n\n模式2、本人在司参与了XX项目，该项目具有XX突出意义。在此项目中，XX是个难点，本人通过XX方法，实现了XX成果。在XX方面，本人通过XX方式，完成了XX工作。本人凭借在XX领域的丰富经验，推动项目在中国/海外市场取得XX成果。"
            prompts.numberOfLines = 0
            return prompts
        }()
        view.addSubview(promptsLabel)
        promptsLabel.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.right.equalTo(-22)
            make.top.equalTo(220 + k_Height_NavigationtBarAndStatuBar)
        }
        actionView = {
            let view = YHWorkActionView()
            view.exampleBlock = {[weak self] in
                guard let self = self else { return }  
                self.view.endEditing(true)
                let mainVc = YHWorkExampleViewController()
                mainVc.dataSource = self.viewModel?.introducetionExampleModels
                mainVc.type = .introduction
                mainVc.exampleBlock = {[weak self] message in
                    guard let self = self else { return }
                    self.dataSource.project_highlights = message
                    self.messageTextField.text = message
                    self.isShowPromptsLabel()
                }
                let vc = UINavigationController(rootVC: mainVc)
                vc.modalPresentationStyle = .pageSheet
                self.navigationController?.present(vc, animated: true)
            }
            view.photoBlock = {[weak self] in
                guard let self = self else { return }
                self.view.endEditing(true)
                YHImagePickerView.show() {[weak self] image in
                    guard let self = self else { return }
                    let clipperVC = YHImageClipperViewController()
                    clipperVC.setBaseImg(image, resultImgSize: CGSize(width: 300, height: 300), type: .Stay)
                    clipperVC.successClippedHandler = {[weak self] result in
                        guard let self = self else { return }
                        self.dataSource.project_highlights = result
                        self.messageTextField.text = result
                    }
                    self.navigationController?.pushViewController(clipperVC, animated: true)
                }
            }
            return view
        }()
        view.addSubview(actionView)
        actionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
        }
        bottomView = {
            let bottom = UIView()
            bottom.backgroundColor = .white
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        
        bottomButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("保存", for: .normal)
            button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(submit), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(bottomButton)
        bottomButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
            make.left.equalTo(16)
        }
    }
    
    @objc func longTimeButtonClick() {
        longTimeButton.isSelected = !longTimeButton.isSelected
        if longTimeButton.isSelected {
            longTimeButton.snp.remakeConstraints { make in
                make.left.equalTo(117)
                make.centerY.equalTo(endTextField.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(43)
            }
            endTextField.isHidden = true
            endButton.isHidden = true
        } else {
            longTimeButton.snp.remakeConstraints { make in
                make.right.equalTo(-18)
                make.centerY.equalTo(endTextField.snp.centerY)
                make.height.equalTo(32)
                make.width.equalTo(43)
            }
            endTextField.isHidden = false
            endButton.isHidden = false
        }
    }
    
    @objc func submit() {
        if longTimeButton.isSelected {
            dataSource.project_end_time = "至今"
        }
        guard let _ = dataSource.project_name else {
            YHHUD.flash(message: "您还有信息未填写")
            return
        }
        guard let _ = dataSource.project_start_time else {
            YHHUD.flash(message: "您还有信息未填写")
            return
        }
        guard let _ = dataSource.project_end_time else {
            YHHUD.flash(message: "您还有信息未填写")
            return
        }
        guard let _ = dataSource.project_highlights else {
            YHHUD.flash(message: "您还有信息未填写")
            return
        }
        viewModel?.saveWorkProjectDetail(workModel ?? YHWorkExperienceDetailModel(), projectModel: dataSource, callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                if let block = self.saveBlock {
                    block()
                }
                self.navigationController?.popViewController(animated: true)
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "")
            }
        })
    }
    
    @objc func startClick() {
        view.endEditing(true)
        YHDatePickView.show(type: .yyyymmdd, title: "选择开始时间", lastIsTaday: true, currentDay: dataSource.project_start_time ?? "") { date in
            if date > self.dataSource.project_end_time ?? "" && self.dataSource.project_end_time?.count ?? 0 > 0 && self.dataSource.project_end_time != "至今" {
                YHHUD.flash(message: "开始时间不能晚于结束时间")
            } else {
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd"
                if let selectDate = format.date(from:date) {
                    let selectTimeInterval = selectDate.timeIntervalSince1970
                    let currentTimeInterval = Date().timeIntervalSince1970
                    if selectTimeInterval > currentTimeInterval {
                        YHHUD.flash(message: "开始时间不能晚于当前时间")
                    } else {
                        self.startTextField.text = date
                        self.dataSource.project_start_time = date
                    }
                }
               
            }
        }
    }
     
    @objc func endClick() {
        view.endEditing(true)
        YHDatePickView.show(type: .yyyymmdd, title: "请选择结束时间", lastIsTaday: true, currentDay: dataSource.project_end_time ?? "") { date in
            if date < self.dataSource.project_start_time ?? "" {
                YHHUD.flash(message: "结束时间不能早于开始时间")
            } else {
                self.endTextField.text = date
                self.dataSource.project_end_time = date
            }
        }
    }
    
    func isShowPromptsLabel() {
        if messageTextField.text.count != 0 {
            promptsLabel.isHidden = true
        } else {
            promptsLabel.isHidden = false
        }
    }
}

extension YHWorkIntroductionViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        self.dataSource.project_highlights = textView.text
        if textView.text.count != 0 {
            promptsLabel.isHidden = true
        } else {
            promptsLabel.isHidden = false
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let newLength = (textView.text as NSString).length + text.count - range.length
        
        return newLength <= 2000
    }
}

extension YHWorkIntroductionViewController: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > 15 {
            return false
        }
        
        dataSource.project_name = newText
        return true
    }
}
