//
//  NewFaceShotController.swift
//  Gengmei
//
//  Created by 刘鹿杰 on 2019/6/19.
//  Copyright © 2019 更美互动信息科技有限公司. All rights reserved.
//

import UIKit
import GMBaseSwift
import GMAlbum
import GMBase
import SnapKit
import GMKit
import GMUtil
import AVFoundation

public var didSetHuman = false
public var didSetNoHumam = false

@objcMembers
class NewFaceShotController: GMBaseController, GMFaceControllerNavigation, GMPhotoPickDismissDelegate, FaceGuideViewDelegate, GMFaceBottomViewDelegate, GMSkinGuidancePopViewDelegate, GMGeneMemoryGenderSelectViewDelegate, CAAnimationDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, GMVoiceSwitchViewDelegate {

    // 创建照相机必须使用的类
    var device: AVCaptureDevice!
    var input: AVCaptureDeviceInput!       //AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
    var output: AVCaptureVideoDataOutput!  //当启动摄像头开始捕获输入
    var imageOutPut: AVCaptureStillImageOutput? = AVCaptureStillImageOutput()
    var session: AVCaptureSession = AVCaptureSession()
    var previewLayer: AVCaptureVideoPreviewLayer!
    // 人脸识别必须使用的类
    var faceDetector: CIDetector?
    var videoDataOutputQueue: DispatchQueue?
    // 测肤使用到的属性
    var rightFace = 0
    var farFace = 0
    var nearFace = 0
    var closeEyeTimes = 0
    var isnoCheckFace = true
    var isDelayShot = true
    var getFace = 0
    var beginToTakePicture = false
    var didTakePicture = false
    var timeString: String? = nil
    var exif: AnyObject? = nil
    var imgWidth: CGFloat = 0
    var options = [String: AnyObject]()
    let faceStatePromter = FaceStatePromter()
    let notificationCenter : NotificationCenter = NotificationCenter.default
    // 面孔起源
    var geneMemoryGenderSelectView: GMGeneMemoryGenderSelectView!
    // 测肤View封装
    fileprivate var skinAIView: GMFaceSkinView!
    var skinFrontAIView: GMFaceSkinFrontView!
    var voiceView: GMVoiceSwitchView!
    fileprivate var bottomView: GMFaceBottomView!
    // 默认选中相机记录
    var cameraType: GMScanAnimationType = .scanFace
    var cameraDirection: CameraDeviceDirection = .isCameraFront
    // 灰度判断
    var skinGray = GMLaunchManager.share()?.appConfigObject.skinCameraGray
    // 是否有签到任务
    var voiceNum: Float!
    var haveTask: Bool = false
    // 记录是否距离合适
    var distanceRight: Bool = false
    // 校验是否已经埋点
    var isScanTrack: Bool = false
    var isTestTrack: Bool = false
    var isGeneTrack: Bool = false
    // 判断测肤远端上次报告是否存在
    let haveSkinLastReport = GMLaunchManager.share()?.appConfigObject.haveScanSkin
    var selectedGender = 0 // 面孔起源 选择的性别

    // 摄像头方向
    enum CameraDeviceDirection {
        case isCameraFront  // 前置照摄像头
        case isCameraBack   // 后置照摄像头
    }
    
    // MARK: -  控制器的生命周期
    
    override func initController() {
        super.initController()
        commonSetupNavigation()
        pageName = "face_scan"
        navigationBar.leftIcon = "NewFaceBack"
        self.fd_interactivePopDisabled = true
        if GMLoginManager.shareInstance().user.userId > 0 {
            businessId = String(GMLoginManager.shareInstance().user.userId)
        } else {
            businessId = ""
        }
        guard let extraP = AppDelegate.shareInstance().extraParam else {
            return
        }
        extraParam = extraP
        AppDelegate.shareInstance().extraParam = ""
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpFaceDetector()     // 设置人脸识别特别及音量
        setUpCamera()           // 设置照相机
        addSkinAIViewFrontUI()  // 添加测肤时前置摄像头时的UI
        addSkinAIViewBackUI()   // 添加测肤时后置摄像头时的UI
        addGeneMemoryGenderView() // 添加选择性别view
        addVoiceView()          // 添加voiceView
        addBottomView()         // 添加bottomView
        addNotification()       // 添加通知
        fetchLastReport()       // 上次报告查询
        guard var extraP = stringValueDic(extraParam) else { return}
        extraP["land_tab_name"] = self.getTabName()
        extraParam = NSString.convert(toBriefJsonString: extraP)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.session.startRunning()
        beginToTakePicture = false
        didTakePicture = false
        isDelayShot = true
        setOutputVolume() // 设置音量
        bottomView.selectedType = cameraType
        if cameraType == .scanSkin {  // AI测肤
            voiceView.isHidden = false
            geneMemoryGenderSelectView.isHidden = true
            isnoCheckFace = false
            skinFrontAIView.isHidden = cameraDirection == .isCameraFront ? false : true
            skinAIView.isHidden = cameraDirection == .isCameraBack ? false : true
            let skinLastReport = GMCache.fetchObject(atDocumentPathWithkey: "GMTestSkinIsShowData")
            let showSkinLastReport: Bool = (skinLastReport != nil || (haveSkinLastReport ?? false))
            bottomView.lastReportButton.isHidden = !showSkinLastReport
            isSkinShowNewGuide()  // 添加首次展示提示框
        } else if cameraType == .scanFace {  // AI侧脸
            geneMemoryGenderSelectView.isHidden = true
            let faceId = GMCache.fetchObject(atDocumentPathWithkey: kFace_Id)
            bottomView.lastReportButton.isHidden = (faceId == nil)
            addPopView() // 添加首次展示提示框
        } else if cameraType == .geneMemory {  // 面孔起源
            bottomView.lastReportButton.isHidden = false
            geneMemoryGenderSelectView.isHidden = false
            bottomView.albumButton.isEnabled = false
            bottomView.shotButton.isEnabled = false
            self.navigationBar.rightButton.isEnabled = false
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if status == .denied {
            alertCameraTips()
            return
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.session.stopRunning()
        distanceNotRightSetStatus()
        faceStatePromter.stopPlayVoice()
        setOutputOrigenVolume()
    }
    
    // MARK: -  辅助方法
    
    // 返回按钮
    override func backAction(_ button: UIButton) {
        super.backAction(button)
        Phobos.track("on_click_button", attributes: ["page_name": pageName, "tab_name": self.getTabName(), "button_name": "return"])
    }
    
    // 通知传值
    func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(chageCameraStatus), name: NSNotification.Name(rawValue: "GMTestSkinAnimationWebViewSenBack"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(chageCameraTofaceSkin), name: NSNotification.Name(rawValue: "GMFaceInfoSharePopToFaceSkin"), object: nil)
    }
    
    // 拍完照片以后进行跳转
    @objc func pushAction() {
        let image = Platform.isSimulator ? UIImage(named: "faceAppNormal") : UIImage(data: DataHelper.SharedDataHelper.imageData)
        let skinVC = GMTestSkinAnimationWebView()
        skinVC.image = image!
        AppDelegate.navigation.pushViewController(skinVC, animated: true)
        Phobos.track("on_click_button", attributes: ["page_name": "face_scan", "tab_name": "AI测肤", "button_name": "take_pic"])
    }
    
    // 切换到AI扫脸
    @objc func chageCameraStatus() {
        bottomView.selectedType = .scanFace
        faceBottomCellDidSelected(.scanFace)
    }
    
    // 切换到AI测肤
    @objc func chageCameraTofaceSkin() {
        bottomView.selectedType = .scanFace
        faceBottomCellDidSelected(.scanSkin)
    }
    
    func addPopView() {
        if isShowNewGuide(key: "NewFaceShotController", count: 3) {
            let popView = GMFaceShotPopView()
            view.addSubview(popView)
        }
    }
    
    internal override func rightButtonClicked(_ button: UIButton) {
        if Platform.isSimulator { return }
        changeCamera()
    }
    
    // 上次报告
    func fetchLastReport() {
        if cameraType == .scanSkin {
            // 判断是否展示上次报告按钮
            let skinLastReport = GMCache.fetchObject(atDocumentPathWithkey: "GMTestSkinIsShowData")
            let showSkinLastReport: Bool = (skinLastReport != nil || (haveSkinLastReport ?? false))
            bottomView.lastReportButton.isHidden = !showSkinLastReport
            if showSkinLastReport {
                Phobos.track("report_status", attributes: ["page_name": pageName, "type": "test"])
                isTestTrack = true
            }
        } else if cameraType == .scanFace {
            let faceId = GMCache.fetchObject(atDocumentPathWithkey: kFace_Id)
            bottomView.lastReportButton.isHidden = (faceId == nil)
            if faceId != nil {
                Phobos.track("report_status", attributes: ["page_name": pageName, "type": "scan"])
                isScanTrack = true
            }
        } else if cameraType == .geneMemory {
            let showDataStr = GMCache.fetchObject(atDocumentPathWithkey: kGMGeneMemoryLastData)
            bottomView.lastReportButton.isHidden = (showDataStr == nil)
        }
    }

    func stringValueDic(_ str: String) -> [String: Any]? {
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)as? [String: Any] {
            return dict
        }
        return Dictionary()
    }
    
    // 获取tabname
    func getTabName() -> String {
        if cameraType == .scanSkin {
            return "AI测肤"
        } else if cameraType == .scanFace {
            return "AI测脸"
        } else if cameraType == .geneMemory {
            return "AI面孔"
        }
        return ""
    }
    // MARK: - 照像机主要类及实现
    func setUpCamera () {
        // 判断是否可以使用照相机
        if !self.canUseCamera() { return }
        if Platform.isSimulator { return }
        if cameraType == .scanSkin { // skinGray = post 此时为后置摄像头， pre为前置摄像头
            cameraDirection = (skinGray == "post") ? .isCameraBack : .isCameraFront
        }
        let position: AVCaptureDevice.Position = (cameraDirection == .isCameraFront) ?  AVCaptureDevice.Position.front : AVCaptureDevice.Position.back
        // 使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
        self.device = AVCaptureDevice.default(for: AVMediaType.video)
        // 尝试获取摄像头方向
        for device in AVCaptureDevice.devices(for: AVMediaType.video) where (device as AnyObject).position == position {
            self.device = device
            break
        }
        //使用设备初始化输入
        do {
            self.input = try AVCaptureDeviceInput(device: self.device)
        } catch _ {}
        
        //生成会话，用来结合输入输出
        if self.session.canSetSessionPreset(AVCaptureSession.Preset.photo) {
            self.session.sessionPreset = AVCaptureSession.Preset.photo
        }
        // 添加输入对象
        if self.session.canAddInput(self.input) {
            self.session.addInput(self.input)
        }
        // 生成输出对象
        self.output = AVCaptureVideoDataOutput()
        self.output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable as! String: Int(kCVPixelFormatType_32BGRA)]
        self.output.alwaysDiscardsLateVideoFrames = true
        self.videoDataOutputQueue = DispatchQueue(label: "VideoDataOutputQueue", attributes: [])
        self.output.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue)
        if self.session.canAddOutput(self.output) {
            self.session.addOutput(self.output)
        }
        //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
        self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
        self.previewLayer.frame = CGRect(x: 0, y: 0, width: Constant.screenWidth, height: Constant.screenHeight - UIView.safeAreaInsetsBottom - 167)
        self.previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        // 拍照时要用
        imageOutPut!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        if self.session.canAddOutput(self.imageOutPut!) {
            self.session.addOutput(self.imageOutPut!)
        }
        self.view!.layer.insertSublayer(self.previewLayer, at: 0)
        //开始启动
        self.session.startRunning()
        // 设置闪光灯
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
            self.changeCameraFlash(flashMode: (self.cameraType == .scanSkin) ? .on : .off)
        }
    }
    
    func changeCamera() {
        if useCameraTips() { return}
        let cameraCount = AVCaptureDevice.devices(for: AVMediaType.video).count
        if cameraCount <= 1 { return }
        var newCamera: AVCaptureDevice?
        var newInput: AVCaptureDeviceInput?
        faceStatePromter.initialAudioPlayer.stop() // 点击切换照相机时， 先停止本次声音
        if input.device.position == .front {
            newCamera = self.cameraWithPosition(.back)
            cameraDirection = .isCameraBack
        } else {
            newCamera = self.cameraWithPosition(.front)
            cameraDirection = .isCameraFront
        }
        do {
            newInput = try AVCaptureDeviceInput(device: newCamera!)
        } catch let error {
            print("toggle carema failed, error = \(error)")
        }
        if newInput != nil {
            session.beginConfiguration()
            session.removeInput(input)
            if session.canAddInput(newInput!) {
                session.addInput(newInput!)
                input = newInput
                device = newCamera
            } else {
                session.addInput(self.input)
            }
            session.commitConfiguration()
        }
        // 设置相机后置时的测肤声音提示 此处需要设置延时， 不然语音提示会设置不及时
        if cameraType == .scanSkin { // 如果是测肤tab情况下 切换摄像头需要处理的事务
            skinAIView.isHidden = (cameraDirection == .isCameraFront) ? true : false
            skinFrontAIView.isHidden = (cameraDirection == .isCameraFront) ? false : true
            Phobos.track("on_click_button", attributes: ["page_name": pageName, "tab_name": "肤质分析", "button_name": "switch_camera"])
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
                self.setFaceStateInitial()
                self.changeCameraFlash(flashMode: .on)
            }
        }
    }
    
    //  拍摄照片
    @objc func shotAction() {
        if Platform.isSimulator { return }
        if !canUseCamera() { // 如果不可以使用照相机
            alertCameraTips()
            return
        }
        Phobos.track("on_click_button", attributes: ["page_name": pageName, "tab_name": self.getTabName(), "button_name": "take_pic"])
        let videoConnection = self.imageOutPut!.connection(with: AVMediaType.video)
        if videoConnection == nil {
            print("take photo failed!")
            return
        }
        imageOutPut!.captureStillImageAsynchronously(from: videoConnection!) { (imageDataSampleBuffer: CMSampleBuffer?, error: Error?) in
            if imageDataSampleBuffer == nil { return }
            if error != nil {
                self.toast("拍摄失败，重新拍摄试试")
                return
            }
            guard let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!) else { return }
            guard let image = UIImage(data: imageData) else {
                return
            }
            self.session.stopRunning()
            UIImageWriteToSavedPhotosAlbum(image, self, #selector(NewFaceShotController.image(_:didFinishSavingWithError:contextInfo:)), nil)
            
            var result = image
            if self.device.position == .front {
                result = UIImage(cgImage: image.cgImage!, scale: image.scale, orientation: .leftMirrored)
            }
            
            if self.cameraType == .geneMemory {
                let upload = GMGeneMemoryAnimationViewController()
                upload.image = result
                upload.gender = self.selectedGender
                self.pushViewController(upload)
            } else {
                let upload = GMScanAnimationController()
                upload.image = result
                self.pushViewController(upload)
            }
        }
    }
    
    // 改变摄像头方向
    func cameraWithPosition(_ position: AVCaptureDevice.Position) -> AVCaptureDevice? {
        let devices = AVCaptureDevice.devices(for: AVMediaType.video)
        for device in devices where (device as AnyObject).position == position {
            return device
        }
        return nil
    }

    // MARK: - 代理方法
    
    func faceBottomCellDidSelected(_ type: GMScanAnimationType) {
        cameraType = type
        if useCameraTips() { return}   // 判断相机权限
        distanceNotRightSetStatus()
        if type == .scanSkin {
            isnoCheckFace = false
            voiceView.isHidden = false
            geneMemoryGenderSelectView.isHidden = true
            self.navigationBar.rightButton.isEnabled = true
            skinFrontAIView.isHidden = (cameraDirection == .isCameraFront) ? false : true
            skinAIView.isHidden = (cameraDirection == .isCameraBack)  ? false : true
            setFaceStateInitial()
            isSkinShowNewGuide()   // 判断测肤是否展示弹框提醒
            // 判断上次报告是否展示
            let skinLastReport = GMCache.fetchObject(atDocumentPathWithkey: "GMTestSkinIsShowData")
            let showSkinLastReport: Bool = (skinLastReport != nil || (haveSkinLastReport ?? false))
            bottomView.lastReportButton.isHidden = !showSkinLastReport
            if (isTestTrack != true) && showSkinLastReport {
                Phobos.track("report_status", attributes: ["page_name": pageName, "type": "test"])
                isTestTrack = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
               self.changeCameraFlash(flashMode: .on) // 设置闪光灯
            }
        } else if type == .scanFace {    // 测脸
            isnoCheckFace = true
            voiceView.isHidden = true
            skinFrontAIView.isHidden = true
            skinAIView.isHidden = true
            geneMemoryGenderSelectView.isHidden = true
            bottomView.albumButton.isEnabled = true
            bottomView.shotButton.isEnabled = true
            self.navigationBar.rightButton.isEnabled = true
            addPopView()
            // 判断上次报告是否展示
            let faceId = GMCache.fetchObject(atDocumentPathWithkey: kFace_Id)
            bottomView.lastReportButton.isHidden = (faceId == nil)
            if (isScanTrack != true) && (faceId != nil) {
                Phobos.track("report_status", attributes: ["page_name": pageName, "type": "scan"])
                isScanTrack = true
            }
            faceStatePromter.stopPlayVoice() // 停止音频播放
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
               self.changeCameraFlash(flashMode: .off)
            }
        } else if type == .geneMemory { // 面孔起源
            isnoCheckFace = true
            voiceView.isHidden = true
            skinFrontAIView.isHidden = true
            skinAIView.isHidden = true
            geneMemoryGenderSelectView.isHidden = false
            bottomView.albumButton.isEnabled = false
            self.navigationBar.rightButton.isEnabled = false
            
            // 判断上次报告是否展示
            let showDataStr = GMCache.fetchObject(atDocumentPathWithkey: kGMGeneMemoryLastData)
            bottomView.lastReportButton.isHidden = (showDataStr == nil)
            faceStatePromter.stopPlayVoice() // 停止音频播放
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
                self.changeCameraFlash(flashMode: .off)
            }
        }
    }
    
    // GMGeneMemoryGenderSelectViewDelegate
    func didClickGender(_ gender: Int) {
        bottomView.albumButton.isEnabled = true
        bottomView.shotButton.isEnabled = true
        self.navigationBar.rightButton.isEnabled = true
        self.selectedGender = gender;
    }
    
    // 开关按钮， 及时停止声音
    func switchViewDidSelected(isON: Bool) {
        if isON == false {
            faceStatePromter.stopPlayVoice()
        }
    }
    
    // 判断测肤是否展示弹框提醒
    func isSkinShowNewGuide() {
        // 判断弹框提示
        if isShowNewGuide(key: "SkinTeachPopView", count: 1) {
            isnoCheckFace = true
            let skinpopview = GMTestSkinTeachPopView()
            view.addSubview(skinpopview)
        } else if isShowNewGuide(key: "SkinGuidancePopView", count: 1) {
            isnoCheckFace = true
            let guidancePopview = GMSkinGuidancePopView()
            guidancePopview.guidanceDelegate = self
            view.addSubview(guidancePopview)
        } else {
            setFaceStateInitial() // 设置测肤声音提示
        }
    }
    
    // MARK: - 相册 action
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeMutableRawPointer) {}
    
    @objc func ablumAction() {
        Phobos.track("on_click_button", attributes: ["page_name": pageName, "tab_name": self.getTabName(), "button_name": "album"])
        let toController = GMPhotoPickController(maxImageCount: 1, maxVideoCount: 0, maxCount: 1, photoDisplayType: GMPhotosDisplayImageType)
        toController.dismissDelegate = self
        toController.root.showEdit = false
        toController.root.singleSelection = true
        toController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        present(toController, animated: true, completion: nil)
    }
    
    // 关闭浮层框弹框代理
    func guidanceBtnClosePopView() {
        isnoCheckFace = false
        setFaceStateInitial() // 设置测肤声音提示
    }
    
    func dismissPhotoPick(_ infos: [GMEditPhotoInfo]) {
        if infos.count > 0 {
            let model: GMEditPhotoInfo = infos.first!
            if self.cameraType == .geneMemory {
                geneMemoryGenderSelectView.isHidden = true
                let upload = GMGeneMemoryAnimationViewController()
                upload.image = model.finshedImage
                upload.gender = selectedGender
                pushViewController(upload)
            } else {
                let upload = GMScanAnimationController()
                upload.image = model.finshedImage
                pushViewController(upload)
            }
        }
    }
    
    // 停止音频播放，并进行后置摄像头音频引导提示
    func setFaceStateInitial() {
        if (cameraType == .scanSkin) && (cameraDirection == .isCameraBack) {
            faceStatePromter.initialAudioPlayer.stop()
            faceStatePromter.state = FaceState.initial
        }
    }
    
    // 是否可以使用照相机
    func canUseCamera() -> Bool {
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if status == .denied {
            return false
        } else if status == .notDetermined {
            AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (result) in
                if result {
                    uiThread {
                        self.setUpCamera()
                    }
                }
            })
            return false
        } else {
            return true
        }
    }
    
    // MARK: 页面基本设置
    
    // 设置人脸识别特别及音量
    func setUpFaceDetector() {
        voiceNum = AVAudioSession.sharedInstance().outputVolume
        var faceDetectorOptions: [String: String]?
        faceDetectorOptions = [CIDetectorAccuracy: CIDetectorAccuracyHigh as String]
        self.faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: faceDetectorOptions)
    }
    
    func addSkinAIViewFrontUI() {
        skinFrontAIView = GMFaceSkinFrontView()
        skinFrontAIView.frame = self.view.frame
        skinFrontAIView.isHidden = true
        view.addSubview(skinFrontAIView)
    }
    
    func addGeneMemoryGenderView() {
        geneMemoryGenderSelectView = GMGeneMemoryGenderSelectView()
        geneMemoryGenderSelectView.frame = self.view.frame
        geneMemoryGenderSelectView.isHidden = true
        geneMemoryGenderSelectView.selectDelegate = self
        view.addSubview(geneMemoryGenderSelectView)
    }
    
    func addSkinAIViewBackUI() {
        skinAIView = GMFaceSkinView()
        skinAIView.frame = self.view.frame
        skinAIView.isHidden = true
        view.addSubview(skinAIView)
    }
    
    func addVoiceView() {
        voiceView = GMVoiceSwitchView()
        voiceView.frame = self.view.frame
        voiceView.delegate = self
        voiceView.isHidden = true
        view.addSubview(voiceView)
        voiceView.snp.makeConstraints { (make) in
            make.top.equalTo(OCNavigationBar.barHeight + 40)
            make.right.equalTo(-20)
            make.size.equalTo(CGSize(width: 150, height: 150))
        }
    }
    
    func addBottomView() {
        bottomView = GMFaceBottomView()
        bottomView.shotButton.addTarget(self, action: #selector(NewFaceShotController.shotAction), for: .touchUpInside)
        bottomView.albumButton.addTarget(self, action: #selector(NewFaceShotController.ablumAction), for: .touchUpInside)
        bottomView.delegate = self
        view.addSubview(bottomView)
        GMNewFaceTool.latestImage { (image) in
            if image != nil {
                DispatchQueue.main.async {
                    self.bottomView.albumButton.faceImageView.image = image
                }
            }
        }
        bottomView.snp.makeConstraints { (make) in
            make.bottom.right.left.equalToSuperview()
            make.height.equalTo(167 + UIView.safeAreaInsetsBottom)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "GMTestSkinAnimationWebViewSenBack"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "GMFaceInfoSharePopToFaceSkin"), object: nil)
        print("NewFaceShotController--delloc")
    }
}
