BaseCityChooseSchoolViewController.swift 8.42 KB
//
//  BaseCityChooseSchoolViewController.swift
//  ParentAssistant
//
//  Created by 左丞 on 2018/3/9.
//  Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//

import UIKit
class BaseCityChooseSchoolViewController: UIViewController,UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!
    let firstLetterArr:[String] = ["#","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    var keys:[String] = []
    var schoolDic:[String:[School]] = [:]
    var schoolArray:[School] = []
    @IBOutlet weak var citySelectbtn: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        citySelectbtn.text = localAddress
        getData()
        // Do any additional setup after loading the view.
    }
    
    //根据关键字获取学校
    func getData(_ keyword:String=""){
        var dic:[String:AnyObject] = ["areaName":localAddress as AnyObject,"keyword":keyword as AnyObject]
        if keyword == ""{
            dic.removeValue(forKey: "keyword")
        }
        HTTPServer.shared.getAreaSchool(parameters: dic) { (str, error) in
            let json=JSON.fromString(str)
            if let ret=json{
                let er=ret["error"].string
                if let errorStr=er{
                    appDelegate.window!.makeToast(errorStr)
                }else{
                    self.schoolArray.removeAll()
                    for item in ret.contentData().arrayValue {
                        self.schoolArray.append(School(j: item))
                    }
                    self.sortData(self.schoolArray)
                }
            }else{
                
            }
        }
    }

    //对给定的学校分组
    func sortData(_ array:[School]){
        schoolDic = [:]
        for letter in firstLetterArr {
            var arr:[School] = []
            for school in array{
                if String(format: "%c",pinyinFirstLetter((school.name as NSString).character(at: 0))).uppercased() == letter{
                    arr.append(school)
                }
            }
            if arr.count > 0{
                schoolDic.updateValue(arr, forKey: letter)
            }
        }
        keys = Array(schoolDic.keys)
        keys.sort { (key1, key2) -> Bool in
            return key1 < key2
        }
        tableView.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //h获取已经选中的学校
    func getSelectSchool() -> School? {
        for (_,item) in schoolDic{
            for school in item{
                if school.isSelect{
                    return school
                }
            }
        }
        return nil
    }
    
    //下一步
    @IBAction func nextStep(_ sender: UIButton) {
        let school = getSelectSchool()
        if school == nil{
            appDelegate.window!.makeToast("请先选择学校")
            return
        }
        if !AccountManager.shared.isOnline(){
            appDelegate.window!.makeToast("请先登录")
            return
        }

        //非合作学校
        if school!.isNew == 1{
            let vc = Story.instantiateViewControllerWithIdentifier("BindingViewControllerVC", storyName: "UserCenter") as! BindingViewController
            vc.from = .select
            vc.school = school!
            self.navigationController?.pushViewController(vc, animated: true)
        //合作学校
        }else if school?.isNew == 0{
            //判断该校该家长是否有孩子
            let localNew = AccountManager.shared.isNew()
            //添加邀请码显示孩子
            if localNew == 1 {
                let vc = Story.instantiateViewControllerWithIdentifier("InvitationCodeVerificationViewControllerVC", storyName: "UserCenter") as! InvitationCodeVerificationViewController
                vc.school = school!
                self.navigationController?.pushViewController(vc, animated: true)
            //家长有孩子信息 直接显示
            }else if localNew == 0 {
                let vc = Story.instantiateViewControllerWithIdentifier("BindingViewControllerVC", storyName: "UserCenter") as! BindingViewController
                vc.from = .unReserved
                vc.school = school!
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = true
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchData(searchBar)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchData(searchBar)
    }
    
    //搜索学校
    func searchData(_ searchBar: UISearchBar){
        getData(searchBar.text!)
        searchBar.resignFirstResponder()
        searchBar.showsCancelButton = false

    }
    
    //左上角城市选择按钮点击事件
    @IBAction func citySelectBtnClick(_ sender: UITapGestureRecognizer) {
        sender.view?.isUserInteractionEnabled = false
        LZCityPickerController.showPicker(in: self
            , select: { (address, province, city, area, isSelect) in
                if isSelect{
                    sender.view?.isUserInteractionEnabled = true
                    self.selectCity(city: area!)
                }
        }) {
            sender.view?.isUserInteractionEnabled = true

        }
    }
    
    func selectCity(city: String) {
        localAddress = city

        citySelectbtn.text = city
        self.getData()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        citySelectbtn.text = localAddress
    }
    /*
    // 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.
    }
    */

    //根据indexPath找到相对应的model
    func getSchoolByIndexpath(indexPath:IndexPath)->School{
        return schoolDic[keys[indexPath.section]]![indexPath.row]

    }
    
    //所有数据全部取消选中
    func changeSchoolSelectState(){
        for (_,value) in schoolDic {
            for item in value{
                item.isSelect = false
            }
        }
    }
}

extension BaseCityChooseSchoolViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SelectSchoolList
        let item = getSchoolByIndexpath(indexPath: indexPath)
        cell.schoolName.text = item.name
        if item.isSelect{
            cell.isSelect.isHidden = false
        }else{
            cell.isSelect.isHidden = true
        }
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return schoolDic[keys[section]]!.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = getSchoolByIndexpath(indexPath: indexPath)
        changeSchoolSelectState()
        item.isSelect = !item.isSelect
        tableView.reloadData()
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keys
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keys.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return keys[section]
    }
}

class SelectSchoolList: UITableViewCell {
    
    @IBOutlet weak var isSelect: UIImageView!
    @IBOutlet weak var schoolName: UILabel!
}

class School:NSObject{
    var schoolArea:String=""//学校所在地区 ,
    var schoolId:Int = 0//学校id ,
    var name:String=""//学校名称 ,
    var state:Int=0//状态,1正常,0关闭
    var isNew:Int=0////1非合作学校,0合作学校
    var isSelect:Bool = false
    init(j:JSON){
        schoolArea = j["school_area"].stringValue
        schoolId = j["school_id"].intValue
        name = j["school_name"].stringValue
        state = j["state"].intValue
    }
    init(names:String,id:Int) {
        name = names
        schoolId=id
    }
}