EvaluationViewController.swift 12.6 KB
//
//  EvaluationViewController.swift
//  ParentAssistant
//
//  Created by 葛建军 on 2018/3/5.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit
import CoreLocation

class EvaluationViewController: UIViewController,CLLocationManagerDelegate,SelectCityViewControllerDelegate{
    var locationManger:CLLocationManager!
    
    @IBOutlet weak var height: NSLayoutConstraint!
    @IBOutlet weak var contentHeight: NSLayoutConstraint!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet var activityImage: [UIImageView]!
    @IBOutlet var activityName: [UILabel]!
    @IBOutlet var activityEntrance: [UIView]!
    
    
    @IBOutlet var courseImage: [UIImageView]!
    @IBOutlet var courseLabel: [UILabel]!
    @IBOutlet var attendCourse: [UIButton]!
    var toolArr:[ToolAndActivity] = []
    var activityArr:[ToolAndActivity] = []
    var leftLabel:UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "慧测慧练"
        addLeftBarBtn()
        locationAction()
        addBottomBtn()
        collectionView.register(UINib(nibName: "ChannelSelectViewCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "channelcell")
        stepUI()
        
        // Do any additional setup after loading the view.
    }
    
    func getData(){
        HTTPServer.shared.getActivityTool(["areaName":AccountManager.shared.address as AnyObject]) { (str, error) in
            httpJsonResule(jsonString: str, error: error, successHandler: { (json) in
                if json["status"]==1{
                    self.activityArr.removeAll()
                    self.toolArr.removeAll()
                    for item in json.contentData().arrayValue{
                        if item["columnType"] == 1{
                            self.activityArr.append(ToolAndActivity(j: item))
                        }else{
                            self.toolArr.append(ToolAndActivity(j: item))
                        }
                    }
                    self.setActivityValue()
                    self.collectionView.reloadData()
                }
            }, failHandler: { (error) in
                
            })
        }
    }
    
    func setActivityValue(){
        for (index,item) in activityArr.enumerated() {
            if index > 2{
                return
            }
            courseImage[index].sd_setImage(with: URL(string: (HTTPServer.HOSTImage+item.toolImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "navigationBar_backgrounImage"))
            courseLabel[index].text = item.toolName
        }
    }
    
    //定位
    func locationAction(){
        if TARGET_IPHONE_SIMULATOR==0{//判断是模拟器还是真机
            if CLLocationManager.locationServicesEnabled() && (CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() ==  .notDetermined){
                locationManger = CLLocationManager()
                locationManger.distanceFilter = 100
                locationManger.desiredAccuracy = 10
                locationManger.requestWhenInUseAuthorization()
                locationManger.delegate = self
                locationManger.allowsBackgroundLocationUpdates = false
                locationManger.startUpdatingLocation()
            }else{
                appDelegate.window!.makeToast("请在设置中打开定位功能")
            }
        }
    }
    //下方悬浮按钮
    func addBottomBtn(){
        let btn = UIButton(frame: CGRect(x: getScreenWidth()-70, y: getScreenHeight()-44 - 70, width: 50, height: 50))
        let layer = CALayer()
        layer.shadowOffset = CGSize(width:0, height:0)
        layer.backgroundColor = UIColor.white.cgColor
        layer.shadowColor = UIColor.lightGray.cgColor
        layer.shadowOpacity = 0.7;
        
        btn.layer.cornerRadius = btn.frame.height/2
        btn.layer.masksToBounds=true
        btn.setImage(#imageLiteral(resourceName: "Binding_icon_binding"), for: .normal)
        if  UIApplication.shared.statusBarFrame.size.height>20{
            btn.frame.origin = CGPoint(x: getScreenWidth()-70, y: getScreenHeight()-44 - 110)
            contentHeight.constant = getScreenHeight() - 64 - 44 - 40
        }
        layer.frame = btn.frame
        layer.cornerRadius = layer.frame.height/2;
        
        self.view.layer.addSublayer(layer)
        
        btn.addTarget(self, action: #selector(EvaluationViewController.pushToBindingViewController), for: .touchUpInside)
        self.view.addSubview(btn)

    }
    
    //左上角按钮
    func addLeftBarBtn(){
        self.navigationController?.navigationBar.barStyle = UIBarStyle.default// UIColorFromRGB(0xC5DAFF)
        let backImage = UIImage(named: "navigationBar_backgrounImage")
        self.navigationController?.navigationBar.setBackgroundImage(backImage, for: UIBarMetrics.default)
        let leftbtn = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
        leftLabel = UILabel(frame: CGRect(x: 0, y: 10, width: 60, height: 20))
        leftLabel.text = AccountManager.shared.address
        leftLabel.textColor = UIColor.white
        leftLabel.sizeToFit()
        let image = UIImageView(frame: CGRect(x: leftLabel.frame.maxX+4, y: 15, width: 16, height: 9))
        image.image = #imageLiteral(resourceName: "evaluation_icon_pushDown")
        leftbtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(EvaluationViewController.getAddreess(tap:))))
        leftbtn.addSubview(leftLabel)
        leftbtn.addSubview(image)
        leftbtn.frame.size = CGSize(width: image.frame.maxX+4, height: 40)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftbtn)
    }
    
    func stepUI(){
        for item in activityEntrance {
            item.layer.cornerRadius = 5
            item.layer.masksToBounds = true
        }
        
        for item in attendCourse {
            item.layer.cornerRadius = 5
            item.layer.masksToBounds = true
            item.layer.borderWidth=1
            item.layer.borderColor = UIColor.white.cgColor
        }
        let heights = getScreenWidth()/375*150+90 + getScreenHeight()/667*100
        height.constant = heights
        contentHeight.constant = getScreenHeight() - 64 + heights - getScreenHeight()/667*350 + 10//+10是看着有点儿显示不下
    }
    
    @objc func pushToBindingViewController(){
        let vc = Story.instantiateViewControllerWithIdentifier("BaseCityChooseSchoolViewControllerVC", storyName: "UserCenter") as! BaseCityChooseSchoolViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let curr = locations.last!
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(curr) { (arr, error) in
            if arr != nil{
                let placeMark = arr!.first
                var city = placeMark!.subLocality
                if city == nil{
                    city = placeMark!.administrativeArea
                }
                AccountManager.shared.address = city!
                self.getData()
                self.addLeftBarBtn()
            }else if error == nil && arr == nil{
                
            }else if error == nil{
                
            }
        }
        manager.stopUpdatingLocation()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
    }
    
    @objc func getAddreess(tap:UITapGestureRecognizer){
        tap.view?.isUserInteractionEnabled = false
        LZCityPickerController.showPicker(in: self
            , select: { (address, province, city, area, isSelect) in
                if isSelect{
                    tap.view?.isUserInteractionEnabled = true
                    self.selectCity(city: area!)
                }
        }) {
            tap.view?.isUserInteractionEnabled = true
        }
    }
    
    func selectCity(city: String) {
        AccountManager.shared.address = city
        self.getData()
        addLeftBarBtn()
    }
    // MARK: - 点击右上角相机按钮
    @IBAction func selectCamareAction(_ sender: UIBarButtonItem) {
        appDelegate.window!.makeToast("功能暂未上线", duration: 1, position: CSToastPositionCenter)
    }
    // MARK: - 点击学情检测
    @IBAction func detectionOfLearningAction(_ sender: UIButton) {
        appDelegate.window!.makeToast("敬请期待", duration: 1, position: CSToastPositionCenter)
    }
    
    // MARK: - 点击专项训练
    @IBAction func specialTrainingAction(_ sender: UIButton) {
        appDelegate.window!.makeToast("敬请期待", duration: 1, position: CSToastPositionCenter)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - 活动专栏点击参与
    @IBAction func attendScurse(_ sender: UIButton) {
        if sender.tag-3000 >= activityArr.count {
            return
        }
        let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController
        if activityArr[sender.tag-3000].toolUrl != "" {
            vcs.webURL = activityArr[sender.tag-3000].toolUrl
        }else{
            vcs.webURL = (HTTPServer.HOSTWAP+"/InformationDetail.aspx?id="+"\(activityArr[sender.tag-3000].toolId)"+"&areaname="+AccountManager.shared.address).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        }
        self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension EvaluationViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return toolArr.count
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (getScreenWidth()-20)/4, height: 92)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "channelcell", for: indexPath) as! ChannelSelectViewCollectionViewCell
        cell.image.sd_setImage(with: URL(string: (HTTPServer.HOSTImage+toolArr[indexPath.row].toolImage).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!), placeholderImage: UIImage(named: "evaluation_icon_highSchoolEnter"))
        cell.channelName.text = toolArr[indexPath.row].toolName
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vcs = Story.instantiateViewControllerWithIdentifier("JSViewController", storyName: "JS") as! JSViewController
        if toolArr[indexPath.row].toolUrl != "" {
            vcs.webURL = toolArr[indexPath.row].toolUrl
        }else{
            vcs.webURL = (HTTPServer.HOSTWAP+"/InformationDetail.aspx?id="+"\(toolArr[indexPath.row].toolId)"+"&areaname="+AccountManager.shared.address).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        }
        self.navigationController?.present(vcs.wrapWithNavigationController(), animated: true, completion: nil)
    }
}

class ToolAndActivity:NSObject{
    var toolId:Int=0 // 工具ID ,
    var toolName:String="" // 工具名称 ,
    var toolImage:String="" // 工具图片 ,
    var toolUrl:String="" // 工具链接 ,
    var orderById:Int=0 // 工具排序
    var columnType:Int=0//1为活动,2为工具
    init(j:JSON){
        toolId = j["toolId"].intValue
        toolName = j["toolName"].stringValue
        toolImage = j["toolImage"].stringValue
        toolUrl = j["toolUrl"].stringValue
        orderById = j["orderById"].intValue
        columnType = j["columnType"].intValue
    }
}