
import UIKit
enum AreaStyle {
    case 省市区街道
    case 省市区
}

class VC_SelectArea: UIViewController {
    @IBOutlet var subMainView: UIView!
    @IBOutlet weak var cancelBtn: UIButton!
    //  已选
    var selAreaArr = [[String:Any]]()
    // 列表
    var listArr = [[String:Any]]()
    // 选择结束
    var pickerEndCall:((String,String)->Void)?
    // 样式
    var style:AreaStyle = .省市区街道
    var requstIndex = 0 //省市区 请求次数
    
    @IBOutlet weak var curCollectionView: UICollectionView!
    @IBOutlet weak var curTableView: UITableView!
    
    var isAllDataBack = false
    var pickerAllDataBack:((String,[[String:Any]])->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        cancelBtn.layer.cornerRadius = 22
        cancelBtn.layer.masksToBounds = true
        requestData()
    }
    
    func requestData(){
        var param = [String:Any]()
        param["areaLevel"] = selAreaArr.count
        if let curArea = selAreaArr.last {
            param["parentId"] = curArea.stringForKey("areaId")
        }
        let cNet = TWOCNetwork(url: "/app/v2/basicInformation/getArea",andParam: param)
        cNet.successCall = { [weak self] (result) in
            if let data = result["data"] as? [String:Any] {
                self?.requstIndex += 1
                if let theDatas = data["areaList"] as? [[String:Any]] {
                    
                    if theDatas.isEmpty {
                        self?.pickerEnd()
                    }else{
                        if self?.style == .省市区 {
                            if self?.requstIndex == 4 {
                                self?.pickerEnd()
                            }
                        }
                        self?.listArr = theDatas
                        self?.curTableView.reloadData()
                        self?.curCollectionView.reloadData()
                     }
                }else{
                    self?.pickerEnd()
                }
                
            }else{
                hud_error("请求出错了，请稍后再试~".languageString())
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    @IBAction func cancelAction(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    func pickerEnd() {
        if isAllDataBack {
            if let endAreaDict = selAreaArr.last, let thePicker = pickerAllDataBack {
                thePicker(endAreaDict.stringForKey("areaId"),selAreaArr.filter({!$0.stringValue(forKey: "parentId").isEmpty}))
            }
        }else{
            let x = selAreaArr.reduce("") { (theName, theAreaDict) -> String in
                let curAreaName = theAreaDict.stringForKey("areaName")
                return (theName == curAreaName) ? theName : (theName+curAreaName)
            }
            
            if let endAreaDict = selAreaArr.last, let thePicker = pickerEndCall {
                thePicker(endAreaDict.stringForKey("areaId"),x)
            }
        }
        dismiss(animated: true, completion: nil)
    }
    
}


extension VC_SelectArea: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return section == 0 ? selAreaArr.count : 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AreaCollectionCell", for: indexPath) as! AreaCollectionCell
            cell.titleLabel.text = selAreaArr[indexPath.row].stringForKey("areaName")
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "defaultCell", for: indexPath)
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 1 {
            return CGSize(width: 100, height: 50)
        }
        let showName = selAreaArr[indexPath.row].stringForKey("areaName")
        let newSize = NSString(string: showName).boundingRect(with: CGSize(width: 500, height: 30), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 17)], context: nil)
        
        return CGSize(width: (newSize.width+16+10), height: 50)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
            return 0.001
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            selAreaArr.removeSubrange(indexPath.row..<selAreaArr.count)
            requestData()
        }
    }
    
    
}

extension VC_SelectArea: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 46
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AreaListCell", for: indexPath) as! AreaListCell
        cell.titleLabel.text = listArr[indexPath.row].stringForKey("areaName")
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selAreaArr.append(listArr[indexPath.row])
        requestData()
    }
    
}


class AreaCollectionCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!
}

class AreaListCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!
}
