//
//  GoodsManageListVC.swift
//  GeliBusinessPlatform
//
//  Created by 刘俊宏 on 2020/4/21.
//  Copyright © 2020 junye lu. All rights reserved.
//

import UIKit
import ViewAnimator
import SkeletonView

class GoodsManageListVC: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout,HeaderSelectViewDelegate,SelectContentViewDelegate,UISearchBarDelegate, SearchBarViewDelegate, GoodsCollectionViewCellDelegate,ProductDetailViewControllerDelegate, GeliAlertViewDelegate,EPViewControllerDelegate{
    
    let UserToken = UserDefaults.standard.value(forKey: "user_token")
    
    var collection : UICollectionView? = nil
    var layout = UICollectionViewFlowLayout()
//    private let animations = [AnimationType.from(direction: .bottom, offset: 150*glscale)]
    private let animations = [AnimationType.vector(CGVector(dx: 0, dy: 150*glscale))]
    weak var showSelectV: SelectContentView! = nil
    weak var selectV: HeaderSelectView! = nil
    @IBOutlet weak var collectionBgView: UIView!
    @IBOutlet weak var changeBgView: UIView!
    @IBOutlet weak var searchBgView: UIView!
    @IBOutlet weak var contentView: UIView!
    weak var searchV: SearchBarView? = nil
    //MARK:--请求字段
    var pageNum = 1
    var pageSearchNum = 1
    var keyword = ""
    var sort = 1
    var isShow = 2
    var goodsType = 0
    //MARK:--数据处理字段
    var items = Array<GoodsResModel>()
    var itemsSearch = Array<GoodsResModel>()
    var itemsAllCount = 0
    var selectIndexArr = [0,0,0]
    var showSelectvIndex = 0
    var isSearch = false
    //MARK:--添加初始化
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.init(named: "白色背景色")
        //searchbar
        let searchBr = SearchBarView.init()
        self.searchBgView.addSubview(searchBr)
        searchBr.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.centerY.equalToSuperview()
            make.height.equalTo(35)
        }
        searchV = searchBr
        searchBr.placeholderStr = "请输入商品名称"
        searchBr.cornerRadius = 35/2.0
        searchBr.delegate = self
        searchBr.delegateL = self
        
        let selectView = HeaderSelectView()
        changeBgView.addSubview(selectView)
        selectView.snp.makeConstraints { (make) in
            make.left.top.right.bottom.equalTo(0);
        }
        selectView.delegate = self
        selectV = selectView
        
        layout.headerReferenceSize = CGSize(width: 375*glscale, height: 50*glscale)
        
        self.collection = UICollectionView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
        
        self.collection?.delegate = self
        self.collection?.dataSource = self
        self.collection?.backgroundColor = UIColor.init(named: "app底色")
        self.collectionBgView.addSubview(self.collection!)
        self.collection?.snp.makeConstraints({ (make) in
            make.left.top.right.bottom.equalTo(0);
        })
        self.collection?.register(UINib(nibName: "GoodsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "GoodsCollectionViewCell")
        
        self.collection?.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerIdentifier")
        
        //下拉刷新相关设置
        headerMJ.setRefreshingTarget(self, refreshingAction: #selector(loadData))
        self.collection!.mj_header = headerMJ
        //上拉加载相关设置
        footerMJ.setRefreshingTarget(self, refreshingAction: #selector(loadMoreData))
        self.collection!.mj_footer = footerMJ
        self.collection?.mj_header?.beginRefreshing()
        NotificationCenter.default.addObserver(self, selector: #selector(jpushServiceNotification(notion:)), name: NSNotification.Name(rawValue: "jpushServiceNotification1"), object: nil)
        
    }
    //MARK:--jpushServiceNotification
    @objc func jpushServiceNotification(notion:Notification) {
        let dict = notion.userInfo! as NSDictionary
        print("123123 ==",dict.allKeys)
        let vc = MsgCenterViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK:--整理排序数据
    func getSortData (){
        for i in 0..<selectIndexArr.count{
            let index = selectIndexArr[i]
            if i == 0 {
                goodsType = 0
                if index == 1{
                    goodsType = 1
                }else if index == 2{
                    goodsType = 5
                }
            }else if i == 1{
                isShow = 2
                if index == 1{
                    isShow = 0
                }else if index == 2{
                    isShow = 1
                }
            }else if i == 2{
                sort = index + 1
            }
        }
    }
    //MARK:--加载数据
    @objc func loadData(){
        var page = 1
        if isSearch{
            pageSearchNum = 1
            page = pageSearchNum
        }else{
            pageNum = 1
            page = pageNum
        }
        getSortData ()
        
        itemsAllCount = 0
        goodsList(["user_token":UserToken as Any,"keyword":keyword,"goods_type":goodsType,"sort":sort,"is_show":isShow,"page":page], success: { (data) in
            let dataM = data as! GoodsListModel
            if self.isSearch {
                self.pageSearchNum = 2
                self.itemsSearch.removeAll()
                dataM.data?.goods_res?.forEach({ (model) in
                    self.itemsSearch.append(model)
                    self.itemsAllCount = dataM.data?.count as! Int
                })
            }else{
                self.pageNum = 2
                self.items.removeAll()
                dataM.data?.goods_res?.forEach({ (model) in
                    self.items.append(model)
                    self.itemsAllCount = dataM.data?.count as! Int
                })
            }
            //collection动画效果
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.33) {
                self.collection?.reloadData()
                self.collection?.mj_header?.endRefreshing()
                self.collection?.mj_footer?.resetNoMoreData()
                self.collection?.performBatchUpdates({
                    UIView.animate(views: self.collection!.orderedVisibleCells,
                                   animations: self.animations, completion: {
                                    
                    })
                }, completion: nil)
            }
            if dataM.data?.count == 0 {
                self.collection?.mj_footer?.endRefreshingWithNoMoreData()
            }else{
                self.collection?.mj_footer?.endRefreshing()
            }
        }) { (error) in
            self.collection?.mj_header?.endRefreshing()
        }
    }
    //MARK:--加载更多数据
    @objc func loadMoreData(){
        var page = 2
        if isSearch{
            page = pageSearchNum
        }else{
            page = pageNum
        }
        getSortData ()
        
        
        goodsList(["user_token":UserToken as Any,"keyword":keyword,"goods_type":goodsType,"sort":sort,"is_show":isShow,"page":page], success: { (data) in
            let dataM = data as! GoodsListModel
            if (dataM.data?.goods_res!.count)! > 0 {
                if self.isSearch {
                    self.pageSearchNum += 1
                    dataM.data?.goods_res?.forEach({ (model) in
                        self.itemsSearch.append(model)
                    })
                }else{
                    self.pageNum += 1
                    dataM.data?.goods_res?.forEach({ (model) in
                        self.items.append(model)
                    })
                }
                self.collection?.reloadData()
                self.collection?.mj_footer?.endRefreshing()
                
            }else{
                self.collection?.mj_footer?.endRefreshingWithNoMoreData()
            }
            
        }) { (error) in
            self.collection?.mj_footer?.endRefreshing()
            
        }
    }
    //MARK:--搜索模块
    //MAKR:--调起搜索后添加个蒙版本
    var blackBtnView:UIButton! = nil
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        print("调起搜索后添加个蒙版本")
        if showSelectV != nil {
            showSelectV.removeFromSuperview()
            selectV.colseBytitleArr(arr: [], index:showSelectvIndex)
            
        }
        blackBtnView = UIButton ()
        blackBtnView.backgroundColor = UIColor.init(named: "提示视图背景色")
        view.addSubview(blackBtnView)
        blackBtnView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(changeBgView.snp_top)
        }
        blackBtnView.addTarget(self, action: #selector(removeBlackBtnView), for: .touchUpInside)
        return true
    }
    @objc func removeBlackBtnView(){
        if blackBtnView != nil {
            blackBtnView.removeFromSuperview()
            searchV!.resignFirstResponder()
        }
    }
    
    //MARK:--搜索按钮代理
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("点击搜索关键字进行--\(searchBar.text)")
        searchBar.resignFirstResponder()
        if blackBtnView != nil {
            blackBtnView.removeFromSuperview()
        }
        isSearch = true
        keyword = searchBar.text!
        self.collection?.mj_header?.beginRefreshing()
        
    }
    //MARK:--清空搜索代理
    func clearSearchAction() {
        
    }
    //MARK:--编辑即将结束
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        print("编辑即将结束了--")
        removeBlackBtnView()
        if keyword.count > 0 {
            keyword = searchBar.text!
            if keyword.count == 0 {
                isSearch = false
                loadData()
            }
        }
    }
    //MARK:--新增触发
    @IBAction func addNewGoodsAction(_ sender: UIButton) {
        print("新增触发-")
        if blackBtnView != nil {
            blackBtnView.removeFromSuperview()
            searchV!.resignFirstResponder()
        }
        if showSelectV != nil {
            showSelectV.removeFromSuperview()
            selectV.colseBytitleArr(arr: [], index:showSelectvIndex)
            
        }
        let vc = ProductDetailViewController()
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    //MARK:--新增回调刷新
    func EPViewControllerFinishEdit() {
        self.collection?.mj_header?.beginRefreshing()
    }
    func reloadDataByProductDetailViewController() {
        self.collection?.mj_header?.beginRefreshing()
        
    }
    //MARK:--下拉视图模块
    func showAction(sender: Int) {
        showSelectvIndex = sender
        let showSelectView = SelectContentView()
        showSelectView.delegate = self
        self.view.window?.addSubview(showSelectView)
        showSelectView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(changeBgView.snp_bottom)
        }
        
        showSelectV = showSelectView
        switch sender {
        case 0:
            do {
                showSelectView.dataArr = ["全部商品", "普通商品", "预售商品"]
                showSelectView.selectIndx = selectIndexArr[0]
                
            }
            break
        case 1:
            do {
                showSelectView.dataArr = ["全部", "下架", "上架"]
                showSelectView.selectIndx = selectIndexArr[1]
                
            }
            break
        case 2:
            do {
                showSelectView.dataArr = ["新增时间最新排序", "新增时间最早排序", "销量最多排序", "销量最少排序"]
                showSelectView.selectIndx = selectIndexArr[2]
                
            }
            break
        default: break
            
        }
        
    }
    func colseAction(sender: Int) {
        if showSelectV != nil {
            showSelectV.removeFromSuperview()
        }
    }
    func didselectCell(sender: Int) {
        selectIndexArr[showSelectvIndex] = sender
        var arr:[String] = []
        if showSelectvIndex == 0 {
            let arr1 = ["全部商品", "普通商品", "预售商品"]
            arr.append(arr1[sender])
        }else if showSelectvIndex == 1{
            let arr2 = ["全部", "下架", "上架"]
            arr.append(arr2[sender])
        }else if showSelectvIndex == 2{
            let arr1 = ["新增时间最新排序", "新增时间最早排序", "销量最多排序", "销量最少排序"]
            arr.append(arr1[sender])
        }
        selectV.colseBytitleArr(arr: arr, index:showSelectvIndex)
        loadData()
    }
    func selectContentvRemoveForSup() {
        selectV.colseBytitleArr(arr: [], index:showSelectvIndex)
    }
    
    //MARK:--collectionView所有代理
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let headerV = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerIdentifier", for: indexPath)
        
        headerV.subviews.forEach { (view) in
            view.removeFromSuperview()
        }
        let headerLbl = UILabel(frame: CGRect(x: 15*glscale, y: 10*glscale, width: 100*glscale, height: 20*glscale))
        if isSearch {
            if itemsSearch.count > 0 {
                headerLbl.text = "共" + StringByInt(number: self.itemsAllCount) + "件商品"
            }else{
                headerLbl.text = ""
            }
        }else{
            if items.count > 0 {
                headerLbl.text = "共" + StringByInt(number: self.itemsAllCount) + "件商品"
            }else{
                headerLbl.text = ""
            }
        }
        
        headerLbl.textColor = UIColor.init(named: "标题字颜色")
        headerLbl.font = UIFont.systemFont(ofSize: 13)
        headerV.addSubview(headerLbl)
        return headerV
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: self.contentView.bounds.width, height: 30*glscale)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if isSearch {
            return itemsSearch.count
        }
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GoodsCollectionViewCell", for: indexPath) as! GoodsCollectionViewCell
        var rowModel:GoodsResModel! = nil
        if isSearch {
            rowModel = self.itemsSearch[indexPath.row]
        }else{
            rowModel = self.items[indexPath.row]
        }
        
        cell.delegate = self
        cell.goodsName.text = rowModel.goods_name
        cell.speatrr.text = rowModel.spec_str
        cell.priceLbl.text = "¥" + rowModel.price!
        
        cell.goodsImgV.sd_setImage(with: URL(string: SERVERCE_ImageHost + rowModel.goods_thumb!))
        
        if rowModel.is_show == 1 {
            cell.leftBtn.setTitle("下架", for: .normal)
            cell.rightBtn.setTitle("入库", for: .normal)
        }else if rowModel.is_show == 0{
            cell.leftBtn.setTitle("入库", for: .normal)
            cell.rightBtn.setTitle("上架", for: .normal)
            
        }
        cell.lgBtn.tag = indexPath.row
        cell.leftBtn.tag = indexPath.row
        cell.rightBtn.tag = indexPath.row
        cell.codeBtn.tag = indexPath.row
        cell.goodsName.showSkeleton(transition: .crossDissolve(0.25))
        cell.priceLbl.showSkeleton(transition: .crossDissolve(0.25))
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            cell.goodsName.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.25))
            cell.priceLbl.hideSkeleton(reloadDataAfter: true, transition: .crossDissolve(0.25))
            
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 165*glscale, height: 283*glscale)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 15*glscale, left: 15*glscale, bottom: 15*glscale, right: 15*glscale)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("选中===\(indexPath)")
        let item = collection?.cellForItem(at: indexPath) as! GoodsCollectionViewCell
        let vc = EPViewController()
        vc.delegate = self
        vc.titleStrArr = [item.leftBtn.titleLabel!.text!,item.rightBtn.titleLabel!.text!]
        let data = items[indexPath.row]
        vc.goods_id = data.goods_id
        vc.sku_id = data.sku_id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    //MARK:---cell delegate 选中
    func selectListsIndex(index: Int) {
        let idx = IndexPath(item: index, section: 0)
        let item = collection?.cellForItem(at: idx) as! GoodsCollectionViewCell
        
        let vc = EPViewController()
        vc.delegate = self
        vc.titleStrArr = [item.leftBtn.titleLabel!.text!,item.rightBtn.titleLabel!.text!]
        let data = items[index]
        vc.goods_id = data.goods_id
        vc.sku_id = data.sku_id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK:-- cell delegate 上下架,入库
    func sureGeliAlertViewAction(sender: UIButton) {
        if sender.tag == 1001{
            
            onOff(["user_token":UserToken as Any,"goods_id":changeGoodsResModel!.goods_id as Any,"is_show":0], success: { (data) in
                let dataM = data as! UpDataModel
                if dataM.code == 1 {
                    HUD.flash(.label("提交成功"), delay: 1.2)
                    self.collection?.mj_header?.beginRefreshing()
                    
                }
            }) { (erro) in
                
            }
        }else if sender.tag == 1002 {
            
            
            onOff(["user_token":UserToken as Any,"goods_id":changeGoodsResModel!.goods_id as Any,"is_show":1], success: { (data) in
                let dataM = data as! UpDataModel
                if dataM.code == 1 {
                    HUD.flash(.label("提交成功"), delay: 1.2)
                    self.collection?.mj_header?.beginRefreshing()
                    
                }
            }) { (erro) in
                
            }
        }
    }
    var changeGoodsResModel: GoodsResModel? = nil
    func changeGoodsIsShow(isTrue: Bool, byIndex: Int) {
        //左按钮为false 右按钮为true
        let rowModel = self.items[byIndex]
        changeGoodsResModel = rowModel
        //添加提示
        if rowModel.is_show == 1 {
            if isTrue {
                print("入库哦哦")
                //                HUD.flash(.label("敬请期待"),delay: 1.2)
                //                return
                let vc = NewRKVc()
                //                let vc = NewCKVc()
                vc.sku_id = changeGoodsResModel?.sku_id
                vc.goods_id = changeGoodsResModel?.goods_id
                self.navigationController?.pushViewController(vc, animated: true)
                //                let vc = RuKuViewController()
                //                vc.barTitle = "入库"
                //                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                print("下架啦")
                let alertView = GeliAlertView(frame: self.view.window!.bounds)
                alertView.delegate = self;
                alertView.tishiLbl.text = ""
                alertView.titileLbl.text = "是否下架商品?"
                alertView.rightBtn.setAttributedTitle(NSAttributedString(string: "确认"), for: .normal)
                alertView.rightBtn.tag = 1001
                self.view.window?.addSubview(alertView)
                
                
            }
        }else{
            if isTrue {
                print("赶紧上架")
                let alertView = GeliAlertView(frame: self.view.window!.bounds)
                alertView.delegate = self;
                alertView.tishiLbl.text = ""
                alertView.titileLbl.text = "是否上架商品?"
                alertView.rightBtn.setAttributedTitle(NSAttributedString(string: "确认"), for: .normal)
                alertView.rightBtn.tag = 1002
                self.view.window?.addSubview(alertView)
                
            }else{
                print("入库哦哦")
                let vc = NewRKVc()
                vc.sku_id = changeGoodsResModel?.sku_id
                vc.goods_id = changeGoodsResModel?.goods_id
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        
    }
    func upDataByGoodsId(goodsId:String) {
        
    }
}