//
//  DialogueViewController.swift
//  MobilePortal
//
//  Created by caiyang on 2020/4/9.
//  Copyright © 2020 yin chen. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
class DialogueViewController: BaseViewController,UITextFieldDelegate {

    var delegate:DialogueViewControllerDelegate!
    var dataSource = NSMutableArray()
    var mUserInfo: Dictionary<AnyHashable, Any>!
    var mKeyBoardHeight: CGFloat!
    var mKeyBoardAnimateDuration: Double!
    var selectItemModel = DialogueListItemModel()
    var cellItemListH:CGFloat!
    var cellItemH:CGFloat!
    var tableViewTransformH:CGFloat!
    
    lazy var inputBoxView: InputBoxView = {
        let inputBoxView = InputBoxView.init(frame: CGRect(x:0, y: SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN()), width:SCREEN_WHIDTH() , height:46.67+HEIGHT_BOTTOM_MARGIN()))
        inputBoxView.backgroundColor = UIColor.white
        inputBoxView.dialogueTextF.delegate = self
        return inputBoxView
    }()
    
    lazy var myTableView: UITableView = {
        let myTableView = UITableView.init()
        self.view.addSubview(myTableView)
        myTableView.snp.makeConstraints { (make) in
            make.width.height.equalToSuperview()
            make.center.equalToSuperview()
        }
        if #available(iOS 11.0, *) {
            myTableView.contentInsetAdjustmentBehavior = .never
            myTableView.scrollIndicatorInsets = myTableView.contentInset
            myTableView.contentInset = UIEdgeInsetsMake(UIApplication.shared.statusBarFrame.size.height+44, 0, 46.67+HEIGHT_BOTTOM_MARGIN(), 0)
        }else{
            myTableView.contentInset = UIEdgeInsetsMake(0, 0, 46.67+HEIGHT_BOTTOM_MARGIN(), 0)
        }
        registerCell(myTableView, cell: DialogueLeftTableViewCell.self)
        registerCell(myTableView, cell: DialogueRightTableViewCell.self)
        registerCell(myTableView, cell: DialogueLeftSelectionTVC.self)
        registerCell(myTableView, cell: DialogueLeftContentTVC.self)
        myTableView.backgroundColor = UIColorFromRGB(rgbValue: 0xE9F2F8)
        setExtraCellLineHidden(tableView: myTableView)
        return myTableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        IQKeyboardManager.shared.enable = false
//        AccountInfo.sharedInstance().isTest = "0"
        self.view.backgroundColor = UIColorFromRGB(rgbValue: 0xE9F2F8)
        mKeyBoardHeight = 0
        cellItemListH = 0
        cellItemH = 90
        tableViewTransformH = 0
        self.initTitleBar()
        self.title = "智能问答"
        self.addInitTableView()
        self.view.addSubview(inputBoxView)
        inputText()
//        actionHttpGCD()
        /// 添加键盘监听
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        // Do any additional setup after loading the view.
    }
    override func initReturnBtn(){
        let leftN:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "return_image")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(arrowResponse))
        let rightN:UIBarButtonItem = UIBarButtonItem.init(title: "发送", style: .plain, target: self, action: #selector(actionHttpGCD))
        
        self.navigationItem.leftBarButtonItem = leftN
        self.navigationItem.rightBarButtonItem = rightN
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
//        AccountInfo.sharedInstance().isTest = "1"
        NotificationCenter.default.removeObserver(self)
    }

    // MARK: private 键盘弹出
    @objc func keyBoardWillShow(notification: Notification) {
        let userInfo = notification.userInfo! as Dictionary
        mUserInfo = userInfo
        let value = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
        let keyBoardRect = value.cgRectValue
        // 得到键盘高度
        let keyBoardHeight = keyBoardRect.size.height
        mKeyBoardHeight = keyBoardHeight
        
        // 得到键盘弹出所需时间
        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        mKeyBoardAnimateDuration = duration.doubleValue
//        showKeyboard()
        UIView.animate(withDuration: mKeyBoardAnimateDuration) {
            self.inputBoxView.frame = CGRect(x:0, y: SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN())-self.mKeyBoardHeight, width:SCREEN_WHIDTH() , height:46.67+HEIGHT_BOTTOM_MARGIN())
        }
        updateTableViewUI()
    }
    // MARK: private
    @objc func keyBoardWillHide(notification: Notification) {
        mKeyBoardHeight = 0
        UIView.animate(withDuration: mKeyBoardAnimateDuration) {
            self.inputBoxView.frame = CGRect(x:0, y: SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN()), width:SCREEN_WHIDTH() , height:46.67+HEIGHT_BOTTOM_MARGIN())
            self.myTableView.transform = CGAffineTransform(translationX: 0, y: 0)
        }
    }
    func updateTableViewUI() {
        if self.dataSource.count <= 0 {
            return
        }
        setTableViewTransform()
        //tableView 更新界面操作
        let indexPath = NSIndexPath.init(row: self.dataSource.count-1, section: 0)
        DispatchQueue.global().async {
            //print("async do something\(Thread.current)")
            DispatchQueue.main.sync {
                self.myTableView.scrollToRow(at: indexPath as IndexPath, at: .bottom, animated: true)
                self.myTableView.transform = CGAffineTransform(translationX: 0, y: -self.tableViewTransformH)
            }
        }
        
    }
    ///依据内容实现myTableView的移动
    func setTableViewTransform() {
//        print(self.cellItemListH)
        let h = SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN())-self.mKeyBoardHeight-NAV_HEIGHT()-STATUBAR_HEIGHT()
        if self.cellItemListH <= h {
            tableViewTransformH = 0
        } else if self.cellItemListH > h && self.cellItemListH < SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN()) {
            tableViewTransformH = self.cellItemListH-h
        } else if self.cellItemListH >= SCREEN_HEIGHT()-(46.67+HEIGHT_BOTTOM_MARGIN()){
            tableViewTransformH = self.mKeyBoardHeight
        }
        
    }
    
    /// 文本发送给后台
    @objc func actionHttpGCD(){
        showHintView()
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getDialogueHttpPostCmd()
        })
        group.notify(queue: DispatchQueue.main) {[weak self] in
            self?.inputBoxView.dialogueTextF.text = ""
            self?.delegate.dataSource = self?.dataSource
            self?.myTableView.delegate = self?.delegate
            self?.myTableView.reloadData()
            self?.updateTableViewUI()
            self?.hidenHintView()
        }
    }
    /// 点击文本内容 获取详情
    @objc func actionContentHttpGCD(){
        showHintView()
        queue.async(group: group, execute: {[weak self] in
            self?.group.enter()
            self?.getDialogueCountentHttpGetCmd()
        })
        group.notify(queue: DispatchQueue.main) {[weak self] in
            self?.delegate.dataSource = self?.dataSource
            self?.myTableView.delegate = self?.delegate
            self?.myTableView.reloadData()
            self?.updateTableViewUI()
            self?.hidenHintView()
        }
    }
}
