//
//  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
import Photos
import AppTrackingTransparency

class INRecorderController: BFBaseViewController {
    
    lazy var titleL : UILabel = {
        let l = UILabel()
        l.text = "home_title".BFLocale
        l.textAlignment = .center
        l.textColor = .white
        l.font = UIFont.systemFont(ofSize: 36)
        
        return l
    }()
    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 camaraBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "shot"), for: .normal)
        btn.setTitle("home_shoot".BFLocale, for: .normal)
        btn.setTitleColor(UIColor.init(white: 1, alpha: 0.5), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.addTarget(self, action: #selector(cameraBtnAction), for: .touchUpInside)
        btn.eventInterval = 1

        return btn
    }()
    
    lazy var photoBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "import"), for: .normal)
        btn.setTitle("home_choose".BFLocale, for: .normal)
        btn.setTitleColor(UIColor.init(white: 1, alpha: 0.5), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        btn.addTarget(self, action: #selector(addVideo), for: .touchUpInside)
        btn.eventInterval = 1
        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
    }()
    
    lazy var settingBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "set"), for: .normal)
        btn.addTarget(self, action: #selector(settingBtnAction), for: .touchUpInside)

        return btn
    }()
    
    lazy var addwxBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "addwx"), for: .normal)
        btn.addTarget(self, action: #selector(addwxAction), for: .touchUpInside)

        return btn
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        hiddenNavigation()
        // 曝光上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: nil, pageSource: .sp_homePage, commonParams: commonParams())
    }

    // MARK: - 生命周期
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 清理cache文件
        clearCacheFile(at: exportVideosDirectory)
        clearCacheFile(at: exportAudiosDirectory)
        clearCacheFile(at: recordVideosDirectory)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        view.addSubview(bgView)
        
        if(PQENVUtil.shared.channel == "Development"){
            view.addSubview(buildTimeLabel)
        }

        view.addSubview(centerView)
        view.addSubview(addwxBtn)
        view.addSubview(settingBtn)
        
        centerView.snp.makeConstraints { make in
            make.width.equalToSuperview()
            make.height.equalTo(209)
            make.center.equalToSuperview()
        }
        addwxBtn.snp.makeConstraints { make in
            make.height.equalTo(40)
            make.width.equalTo(119)
            make.right.equalTo(-10)
            make.top.equalTo(51)
        }
        settingBtn.snp.makeConstraints { make in
            make.width.height.equalTo(40)
            make.left.equalTo(10)
            make.top.equalTo(51)
        }


        
        centerView.addSubview(titleL)
        centerView.addSubview(camaraBtn)
        centerView.addSubview(photoBtn)
        
        camaraBtn.snp.makeConstraints { make in
            make.width.equalTo(130)
            make.height.equalTo(180)
            make.centerX.equalToSuperview().offset(-80)
            make.centerY.equalToSuperview()
        }
        
        photoBtn.snp.makeConstraints { make in
            make.left.equalTo(camaraBtn.snp.right).offset(30)
            make.width.height.centerY.equalTo(camaraBtn)
        }
        

        titleL.snp.makeConstraints { make in
            make.bottom.equalTo(photoBtn.snp.top).offset(-80)
            make.centerX.equalToSuperview()
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(40)
        }
        
        //欢迎界面
        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)")
            
        }
        
    }
    
    override func viewDidLayoutSubviews() {
        var btn = camaraBtn
        btn.imageEdgeInsets = UIEdgeInsets(top: -btn.titleLabel!.height - 2, left: 0, bottom: 0, right: -btn.titleLabel!.width)
        btn.titleEdgeInsets = UIEdgeInsets(top: btn.imageView!.height + 40, left: -btn.imageView!.width, bottom: 0, right: 0)
        
        btn = photoBtn
        btn.imageEdgeInsets = UIEdgeInsets(top: -btn.titleLabel!.height - 2, left: 0, bottom: 0, right: -btn.titleLabel!.width)
        btn.titleEdgeInsets = UIEdgeInsets(top: btn.imageView!.height + 40, left: -btn.imageView!.width, bottom: 0, right: 0)
    }
    
    @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_addVideoButton, pageSource: .sp_homePage,extParams:nil,commonParams: commonParams())
        }
    }
    
    @objc func cameraBtnAction() {
        if chechCameraPromission() {
            let vc = INIntroduceController()
            let ass = PHAsset()
            ass.title = "record.camera"
            vc.assets = [ass]
            navigationController?.pushViewController(vc, animated: true)
        }
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_shootVideoButton, pageSource: .sp_homePage,extParams:nil,commonParams: commonParams())
        
    }
    
    @objc func settingBtnAction() {
        let vc = INRecorderSetting()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func addwxAction(){
        let alertv = UIAlertController(title: "让我们成为微信好友", message: "我的微信号是：cjz_0216，无论你遇到什么问题，还是有功能建议，我都真诚的期待和你聊天。", preferredStyle: .alert)
        let sureAction = UIAlertAction(title: "复制微信号", style: .default, handler: { action in
            UIPasteboard.general.string = "cjz_0216"
            cShowHUB(superView: nil, msg: "已复制到剪切板")
        })
        sureAction.setValue(UIColor.hexColor(hexadecimal:"0x389AFF"), forKey: "_titleTextColor")
        alertv.addAction(sureAction)

        self.present(alertv, animated: true, completion: nil)
        
    }
    
    func chechCameraPromission() -> Bool{
        if  AVCaptureDevice.authorizationStatus(for: AVMediaType.video) != AVAuthorizationStatus.denied {
            return true
        }else {
            cShowHUB(superView: nil, msg: "record_fail_camera".BFLocale)
            return false
        }
    }
    
    @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)
        }
    }
    
    //
    func clearCacheFile(at folderPath: String) {
        if let files = try? FileManager.default.contentsOfDirectory(atPath: folderPath) {
            for file in files {
                do {
                    try FileManager.default.removeItem(at: URL(fileURLWithPath: folderPath).appendingPathComponent(file))
                } catch {
                    BFLog(1, message: "\(error), \(file)")
                }
            }
        }
    }

    
}


//点击超链接回调
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)
        }
    }
}
