//
//  INRecorderController.swift
//  Introduce
//
//  Created by 胡志强 on 2021/11/29.
//  首页

import BFMaterialKit
import BFRecordScreenKit
import BFUIKit
import Foundation
import UIKit
import TYAttributedLabel
import BFCommonKit
import BFAnalyzeKit

 
class INRecorderController: BFBaseViewController {
    var cUserProtocol:String = "https://weapppiccdn.yishihui.com/resources/agreements/shishuo/videoservice_\( BFLocalizedUtil.currentLanguage()).html"
    var cPrivacy:String = "https://weapppiccdn.yishihui.com/resources/agreements/shishuo/videoagreement_\( BFLocalizedUtil.currentLanguage()).html"
    
    lazy var addVideoBtn: UIButton = {
        let btn = UIButton(type: .custom)
        //        btn.setTitle("Add", for: .normal)
        btn.setImage(UIImage(named: "add"), for: .normal)
        btn.addTarget(self, action: #selector(addVideo), for: .touchUpInside)
        return btn
    }()
    
    lazy var bgView:UIImageView = {
        let bgView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
        bgView.contentMode = .scaleAspectFill
        bgView.image = UIImage(named: "homebg")
        return bgView
    }()
    
    //欢迎界面
    lazy var centerView:UIView = {
        let view = UIView.init()
        return view
        
    }()
    
    //欢迎界面
    lazy var welcomeView:UIView = {
        let view = UIView.init()
        view.backgroundColor = .white
        view.addCorner(corner:17)
        return view
        
    }()
    //欢迎界面背景
    lazy var welcomeBackView:UIView = {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: cScreenWidth, height: cScreenHeigth))
        view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6)
        return view
        
    }()
    
    lazy var welcomeTitle:UILabel = {
        let l = UILabel()
        l.text = "home_agreement_tittle".BFLocale

        l.textColor = .black
        l.font = UIFont.boldSystemFont(ofSize: 22)
        l.textAlignment = .center
        view.addSubview(l)
        return l
    }()
    
    //显示编译时间
    lazy var buildTimeLabel:UILabel = {
        let l = UILabel.init(frame: CGRect.init(x: 0, y: 120, width: cScreenWidth, height: 20))
        l.text = "打包时间：" + PQENVUtil.shared.ENBuildTime
        l.textColor = .white
        l.font = UIFont.boldSystemFont(ofSize: 18)
        l.textAlignment = .left
        return l
    }()
 
    lazy var protocolLab: TYAttributedLabel = {
   
        
        let protocolLab = TYAttributedLabel()
        protocolLab.highlightedLinkBackgroundColor = UIColor.clear
        protocolLab.backgroundColor = UIColor.clear
        protocolLab.numberOfLines = 0
        protocolLab.delegate = self
        protocolLab.font = UIFont.systemFont(ofSize: 14)
        protocolLab.text = "home_agreement_begin".BFLocale
        protocolLab.textColor = UIColor(red: 0.262, green: 0.262, blue: 0.262, alpha: 1)
        protocolLab.appendLink(withText: "home_agreement_service".BFLocale, linkFont: UIFont.systemFont(ofSize: 14), linkColor: UIColor.hexColor(hexadecimal: "#90a9d2"),  underLineStyle:CTUnderlineStyle(), linkData: cUserProtocol)
        
        protocolLab.appendLink(withText: "home_agreement_privacy".BFLocale, linkFont: UIFont.systemFont(ofSize: 14), linkColor: UIColor.hexColor(hexadecimal: "#90a9d2"), underLineStyle:CTUnderlineStyle(), linkData: cPrivacy)
        
        protocolLab.appendLink(withText: "\("home_agreement_remarks".BFLocale)\n\n", linkFont: UIFont.systemFont(ofSize: 14), linkColor: UIColor.hexColor(hexadecimal: "#434343"), underLineStyle: CTUnderlineStyle(), linkData: nil)
        
        protocolLab.appendLink(withText: "home_agreement_prompt".BFLocale, linkFont: UIFont.systemFont(ofSize: 14), linkColor: UIColor(red: 0.262, green: 0.262, blue: 0.262, alpha: 1), underLineStyle: CTUnderlineStyle(), linkData: nil)
        protocolLab.textAlignment = CTTextAlignment.left
        return protocolLab
    }()
    
    lazy var doneBtn:UIButton = {
        let doneBtn = UIButton()
        doneBtn.backgroundColor = UIColor.hexColor(hexadecimal: "#389AFF")
        doneBtn.setTitle("option_accept".BFLocale, for: .normal)
        doneBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        doneBtn.addTarget(self, action: #selector(doneAction), for: .touchUpInside)
        doneBtn.addCorner(corner: 4)
        return doneBtn
    }()
    
    lazy var cancleBtn:UIButton = {
        let cancleBtn = UIButton()
        cancleBtn.backgroundColor = UIColor.clear
        cancleBtn.setTitle("option_refuse".BFLocale, for: .normal)
        cancleBtn.setTitleColor( UIColor(red: 0.262, green: 0.262, blue: 0.262, alpha: 1), for: .normal)
        cancleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cancleBtn.addTarget(self, action: #selector(cancleAction), for: .touchUpInside)
        
        cancleBtn.addCorner(corner: 4)
        return cancleBtn
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        hiddenNavigation()
        // 曝光上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: nil, pageSource: .sp_homePage, commonParams: commonParams())
    }
    
    lazy var bottomView:UIView = {
        let bottomView = UIView(frame:CGRect.init(x: 0, y: view.frame.height - cSafeAreaHeight - 20 - 30, width: view.frame.width, height: 30))
        let userProBtn = UIButton.init(type: .custom)
        userProBtn.setTitle("hone_privacy".BFLocale, for: .normal)
        userProBtn.tag = 1
        userProBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        userProBtn.setTitleColor(UIColor.hexColor(hexadecimal: "6E7F9A"), for: .normal)
        userProBtn.addTarget(self, action: #selector(protocolClick(sender:)), for: .touchUpInside)
        
        let lineLab = UILabel()
        lineLab.text = "   |   "
        lineLab.font = UIFont.systemFont(ofSize: 13)
        lineLab.textColor = UIColor.hexColor(hexadecimal: "6E7F9A")
        
        let priProBtn = UIButton.init(type: .custom)
        priProBtn.setTitle("hone_service".BFLocale, for: .normal)
        priProBtn.tag = 2
        priProBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        priProBtn.setTitleColor(UIColor.hexColor(hexadecimal: "6E7F9A"), for: .normal)
        priProBtn.addTarget(self, action: #selector(protocolClick(sender:)), for: .touchUpInside)
        
        bottomView.addSubview(userProBtn)
        bottomView.addSubview(lineLab)
        bottomView.addSubview(priProBtn)
        lineLab.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        userProBtn.snp.makeConstraints { make in
            make.right.equalTo(lineLab.snp.left)
            make.centerY.equalToSuperview()
        }
        priProBtn.snp.makeConstraints { make in
            make.left.equalTo(lineLab.snp.right)
            make.centerY.equalToSuperview()
        }
        return bottomView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        view.addSubview(bgView)
        
        if(PQENVUtil.shared.channel == "Development"){
            view.addSubview(buildTimeLabel)
        }
      
        view.addSubview(centerView)
        view.addSubview(bottomView)
        centerView.snp.makeConstraints { make in
            make.width.equalTo(140)
            make.height.equalTo(209)
            make.center.equalToSuperview()
        }
        
        centerView.addSubview(addVideoBtn)
        addVideoBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(5)
            make.left.equalToSuperview().offset(5)
            make.width.height.equalTo(130)
        }
        
        let l = UILabel()
        l.text = "hone_star".BFLocale
        l.textColor = UIColor.hexColor(hexadecimal: "#8C9399")
        l.font = UIFont.systemFont(ofSize: 17)
        centerView.addSubview(l)
        let text = l.text
        let attributedString = NSMutableAttributedString.init(string: text!)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 7
        paragraphStyle.alignment = .center
        attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: .init(location: 0, length: l.text?.count ?? 0))
        
        l.attributedText = attributedString
        l.sizeToFit()
        l.numberOfLines = 2
        l.snp.makeConstraints { make in
            make.top.equalTo(addVideoBtn.snp.bottom).offset(19)
            make.centerX.equalToSuperview()
            make.width.equalTo(200)
            make.height.equalTo(60)
        }
        
        //欢迎界面
        if(getUserDefaults(key: "welcomeViewisshow") == nil){
            view.addSubview(welcomeBackView)
            welcomeBackView.addSubview(welcomeView)
            welcomeView.addSubview(protocolLab)
            welcomeView.addSubview(welcomeTitle)
            welcomeView.addSubview(doneBtn)
            welcomeView.addSubview(cancleBtn)
            
            welcomeView.snp.makeConstraints{ make in
                make.center.equalToSuperview()
                make.width.equalTo(280)
                make.height.equalTo(350)
            }
            
            welcomeTitle.snp.makeConstraints{ make in
                make.centerX.equalToSuperview()
                make.width.equalToSuperview()
                make.top.equalToSuperview().offset(30)
                make.height.equalTo(31)
            }
            
            protocolLab.snp.makeConstraints{ make in
                make.centerX.equalToSuperview()
                make.width.equalTo(230)
                make.top.equalTo(welcomeTitle.snp.bottom).offset(16)
                make.height.equalTo(140)
            }
            
            doneBtn.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.width.equalTo(230)
                make.height.equalTo(47)
                make.top.equalTo(protocolLab.snp.bottom).offset(30)
            }
            
            cancleBtn.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.width.equalTo(230)
                make.height.equalTo(20)
                make.top.equalTo(doneBtn.snp.bottom).offset(17)
            }
        }
        
        // add by ak 取 nsl token
        BFRecordScreenViewModel.getNlsAccessToken { [weak self] token, appkey in
            BFLog(message: "提前取一次nls appkey is \(appkey), token is \(token)")
            
        }
        
    }
    
    @objc func doneAction() {
        welcomeBackView.isHidden = true
        
        saveUserDefaults(key: "welcomeViewisshow", value: "true")
        
    }
    
    
    @objc func cancleAction() {
        welcomeBackView.isHidden = true
        
        exit(-1)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func addVideo() {
        if (getUserDefaults(key: "welcomeViewisshow") == nil) {
            welcomeBackView.isHidden = false
        }else{
            let vc = INPhotoVideosController()
            vc.hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(vc, animated: true)
            // 按钮点击
            BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_addVideo, pageSource: .sp_homePage, commonParams: commonParams())
        }
    }
    
    @objc func protocolClick(sender:UIButton) {
        var link: String?
        if sender.tag == 1 {
            link = cUserProtocol
        } else {
            link = cPrivacy
        }
        if link != nil, (link?.count ?? 0) > 0 {
            let detail = BFBaseWebViewController()
            detail.baseUrl = link
            self.navigationController?.pushViewController(detail, animated: true)
        }
    }
}


//点击超链接回调
extension INRecorderController: TYAttributedLabelDelegate {
    func attributedLabel(_: TYAttributedLabel!, textStorageClicked textStorage: TYTextStorageProtocol!, at _: CGPoint) {
        let link: String? = (textStorage as? TYLinkTextStorage)?.linkData as? String ?? ""
        if link != nil, (link?.count ?? 0) > 0 {
            let detail = BFBaseWebViewController()
            detail.baseUrl = link
            self.navigationController?.pushViewController(detail, animated: true)
        }
    }
}
