//
//  CCAddImageView.swift
//  SwiftProject
//
//  Created by soldoros on 2024/1/10.
//

import UIKit


@objc protocol CCAddImageViewDelegate:NSObjectProtocol {
    
    //添加一张图
    @objc optional func CCAddImageViewAddImage(imgheight:CGFloat, image:UIImage)
    //删除一张图
    @objc optional func CCAddImageViewDeleteImage(imgheight:CGFloat, index:NSInteger)
}

//视图宽度
let AddImgWidth:CGFloat = SCREEN_Width
//左右留白
let AddLRSpace:CGFloat = 15
//顶部底部留白
let AddTBSpace:CGFloat = 15
//图片间左右留白
let AddImgLRSpace:CGFloat = 15
//图片间上下留白
let AddImgTBSpace:CGFloat = 15
//每一行4张图
let AddImgNum:CGFloat = 4
//最大图片数目
let AddImgMaxNum:CGFloat = 4
//按钮、图片的尺寸
let BtnSize:CGFloat = (AddImgWidth-2*AddLRSpace-(AddImgNum-1)*AddImgLRSpace)/AddImgNum
//视图初始化的总高度
let AddimgViewH:CGFloat = BtnSize+2*AddTBSpace

class CCAddImageView: UIView {
    
    weak var delegate:CCAddImageViewDelegate?
    
    var mImgViews:NSMutableArray?
    
    var mAddBtn:UIButton?
    var images:NSMutableArray?
    var mController:UIViewController?
    var imgheight:CGFloat?
    
    var mAddImage:CCAddImage?
    
    var controller:BaseVirtualController?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        self.bounds = CGRect.init(x: 0, y: 0, width: AddImgWidth, height: AddimgViewH)
        images = NSMutableArray()
        mImgViews = NSMutableArray()
        
        
        //显示和隐藏 30
        mAddBtn = UIButton.init(type: UIButton.ButtonType.custom)
        self.addSubview(mAddBtn!)
        mAddBtn?.bounds = CGRect.init(x: 0, y: 0, width: BtnSize, height: BtnSize)
        mAddBtn?.tag = 100
        mAddBtn?.left = AddLRSpace
        mAddBtn?.top = AddTBSpace
        mAddBtn?.setBackgroundImage(UIImage.init(named: "addImage"), for: UIControl.State.normal)
        mAddBtn?.isSelected = false
        mAddBtn?.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControl.Event.touchUpInside)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加
    @objc func buttonPressed(sender:UIButton){
        
        controller = (self.viewController() as! BaseVirtualController)
        
        if(images!.count == Int(AddImgMaxNum)){
            let str = "最多上传" + (NSString.makeStringInt(number: NSInteger(AddImgMaxNum)) as String) + "张图片"
            (self.viewController() as! BaseVirtualController).showTime(message: str as NSString)
        }else{
            
            DispatchQueue.main.async(execute: {
                self.mAddImage = CCAddImage()
                self.mAddImage!.getImagePicker(controller: self.controller!, modelType: ImagePickerModelType.image, pickerBlock: { (_ style:ImagePickerWayStyle,_ type:ImagePickerModelType,_ datas:Any) in
                    
                    let image = (datas as! UIImage)
                    self.setImg(img: image)
                    
                })
            })
        }
    }
    
    //删除
    @objc func imgBtnPressed(sender:UIButton){
        
        let index = sender.tag - 49
        let str = "删除第" + (NSString.makeStringInt(number: index) as String) + "张图片"
        CCAlert.pressentAlertControllerWith(title: str as NSString, message: "", ok: "确定", cancel: "") { (alert:UIAlertAction) in
            if(alert.title == "确定"){
                self.delateImg(index: index)
            }
        }
    }
    
    //图片tag从50开始
    func setImg(img:UIImage){
        
        images?.add(img)
        let i:NSInteger = images!.count - 1
        
        let mImgView:UIImageView = UIImageView()
        mImgView.frame = mAddBtn!.frame
        mImgView.image = img
        self.addSubview(mImgView)
        mImgView.isUserInteractionEnabled = true
        
        let mImgBtn = UIButton.init(type: UIButton.ButtonType.custom)
        mImgView.addSubview(mImgBtn)
        mImgBtn.bounds = CGRect.init(x: 0, y: 0, width: 20, height: 20)
        mImgBtn.tag = i + 50
        mImgBtn.right = mImgView.width - 1
        mImgBtn.top = 2
        mImgBtn.clipsToBounds = true
        mImgBtn.layer.cornerRadius = mImgBtn.height * 0.5
        mImgBtn.backgroundColor = UIColor.red
        mImgBtn.setTitle("-", for: UIControl.State.normal)
        mImgBtn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mImgBtn.isSelected = false
        mImgBtn.addTarget(self, action: #selector(imgBtnPressed(sender:)), for: UIControl.Event.touchUpInside)
        
         mImgViews?.add(mImgView)
        
        let left:CGFloat = CGFloat(images!.count).truncatingRemainder(dividingBy: AddImgNum)
        mAddBtn?.left = left * (BtnSize + AddImgLRSpace) + AddLRSpace
        
        let top =  Int(CGFloat(images!.count)/AddImgNum)
        mAddBtn?.top = AddTBSpace + CGFloat(top) * (BtnSize+AddImgTBSpace)
        
        self.setImgViwHeight()
        delegate?.CCAddImageViewAddImage?(imgheight: imgheight!, image: img)
    }
    
    
    //删除图片
    func delateImg(index:NSInteger){
        
        let k:NSInteger = images!.count - 1
        
        let mImgView:UIImageView = (mImgViews![k] as! UIImageView)
        mAddBtn?.frame = mImgView.frame
        mImgView.removeFromSuperview()

        images?.removeObject(at: index - 1)
        mImgViews?.removeObject(at: k)
        
        var i = 0
        for imgView:UIImageView in mImgViews as! [UIImageView]{
            
            let img = images![i] as! UIImage
            imgView.image = img
            i += 1
        }
        
        self.setImgViwHeight()
        delegate?.CCAddImageViewDeleteImage?(imgheight: imgheight!, index: index)
    }
    
    //设置图片视图的高度
    func setImgViwHeight(){
        
        if(images!.count < Int(AddImgNum-1)){
            self.height = AddimgViewH
            self.imgheight = self.height
            return
        }
        
        //计算图片数量加上按钮后占用的行数
      
        let number:CGFloat = CGFloat(images!.count + 1).truncatingRemainder(dividingBy: AddImgNum)
        let mo:NSInteger = number == 0 ? 0 : 1
        let lines:NSInteger = Int(CGFloat(self.images!.count+1)/AddImgNum) + mo
        
        let h1 = AddTBSpace * 2
        let h2 = CGFloat(lines - 1) * AddImgTBSpace
        let h3 = CGFloat(lines) * BtnSize
        self.height = h1 + h2 + h3
        self.imgheight = self.height
        
    }
    
}

