//
//  YHSelectFileSheetView.swift
//  galaxy
//
//  Created by EDY on 2024/6/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSelectFileSheetView: UIView {
    var backDate: (([YHWorkExperienceFileModel]) -> Void)?
    var centerView: UIView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var closeButton: UIButton!
    var sureButton: UIButton!
    var lineView: UIView!
    var tableView: UITableView!
    var dataSource: [YHWorkExperienceFileModel] = []
    var orderID: Int = 0 {
        didSet {
            self.viewModel.requestFileList(self.orderID) {[weak self] success, error in
                guard let self = self else { return }
                self.dataSource = self.viewModel.fileList
                self.tableView.reloadData()
            }
        }
    }
    var viewModel = YHWorkExperienceViewModel()
    var title: String = "" {
        didSet {
            titleLabel.text = title
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(484)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = title
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            label.text = "已上传文件同步"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.height.equalTo(24)
            make.width.equalTo(200)
            make.centerX.equalToSuperview()
        }
        
        subTitleLabel = {
            let label = UILabel()
            label.text = title
            label.font = UIFont.PFSC_M(ofSize: 14)
            label.textColor = UIColor.mainTextColor50
            label.numberOfLines = 0
            label.text = "快捷导入简历，帮助提升文书定制的丰富度和完善度"
            return label
        }()
        centerView.addSubview(subTitleLabel)
        subTitleLabel.snp.makeConstraints { make in
            make.top.equalTo(73)
            make.left.equalTo(21)
            make.right.equalTo(-21)
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.width.equalTo(24)
            make.top.equalTo(16)
        }
        
        sureButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确定", for: .normal)
            button.setTitleColor(UIColor.white, for: .normal)
            button.backgroundColor = UIColor.brandMainColor
            button.layer.cornerRadius = 3
            button.addTarget(self, action: #selector(sure), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(sureButton)
        sureButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.height.equalTo(48)
            make.left.equalTo(16)
            make.bottom.equalTo(-42)
        }
                
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHSelectFileCell.self)
            return tableView
        }()
        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(114)
            make.bottom.equalTo(-98)
            make.left.right.equalToSuperview()
        }
        
        centerView.layoutIfNeeded()
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(8, 8))
        let layer = CAShapeLayer()
        layer.frame = centerView.bounds
        layer.path = path.cgPath
        centerView.layer.mask = layer
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        print("处理点击手势")
        dismiss()
    }
    
    static func show(orderID: Int, callBack: @escaping (([YHWorkExperienceFileModel]) -> Void)) {
        let view = YHSelectFileSheetView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.orderID = orderID
        view.backDate = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func sure() {
        var array:[YHWorkExperienceFileModel] = []
        for item in dataSource {
            if item.isSelect {
                array.append(item)
            }
        }
        if let block = backDate {
            block(array)
        }
        dismiss()
    }
}

extension YHSelectFileSheetView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer:UIGestureRecognizer, shouldReceive touch:UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHSelectFileSheetView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHSelectFileCell.self)
        cell.updateModel(dataSource[indexPath.row])
        cell.editBlock = { [weak self] model in
            guard let self = self else { return }
            for item in dataSource {
                if item.fileUrl == model.fileUrl {
                    item.isSelect = !item.isSelect
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 69
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

class YHSelectFileCell: UITableViewCell {
    
    static let cellReuseIdentifier = "YHSelectFileCell"
    
    var editBlock:((YHWorkExperienceFileModel)->())?
    
    var whiteView: UIView!
    var iconImgV: UIImageView!
    var nameLabel: UILabel!
    var timeLabel: UILabel!
    var editBtn: UIButton!
    
    var contentItem: YHWorkExperienceFileModel!
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func updateModel(_ model: YHWorkExperienceFileModel) {
        contentItem = model
        nameLabel.text = model.fileName
        timeLabel.text = "上传于\(model.uploadedAt)"
        let suffix = model.fileUrl.pathExtension.lowercased()
        var iconImgName = ""
        
        if suffix == "jpeg" {
            iconImgName = "my_cer_type_jpg"
            
        } else if suffix == "jpg" {
            iconImgName = "my_cer_type_jpg"
            
        } else if suffix == "png" {
            iconImgName = "my_cer_type_png"
            
        } else if suffix == "pdf" {
            iconImgName = "my_cer_type_pdf"
            
        } else if suffix == "doc" || suffix == "docx" {
            iconImgName = "my_cer_type_word"
        
        } else if suffix == "ppt" || suffix == "pptx" {
            iconImgName = "my_cer_type_ppt"
        } else if suffix == "bmp" {
            iconImgName = "my_cer_type_bmp"
        } else if suffix == "tiff" {
            iconImgName = "my_cer_type_tiff"
        }
        
        iconImgV.image = UIImage(named: iconImgName)
        editBtn.isSelected = model.isSelect
    }
    
    @objc func didEditBtnClicked() {
        editBtn.isSelected = !editBtn.isSelected
        if let editBlock = editBlock {
            editBlock(contentItem)
        }
    }
    
    
    func setupUI() {
        
        self.selectionStyle = .none
        contentView.backgroundColor = .white
        
        whiteView = UIView()
        contentView.addSubview(whiteView)
        
        iconImgV = UIImageView(image:UIImage(named:"my_cer_type_jpg"))
        whiteView.addSubview(iconImgV)
        
        nameLabel = UILabel()
        nameLabel.textColor = UIColor.mainTextColor
        nameLabel.textAlignment = .left
        nameLabel.numberOfLines = 0
        nameLabel.font = UIFont.PFSC_M(ofSize:14)
        whiteView.addSubview(nameLabel)
        
        timeLabel = UILabel()
        timeLabel.textColor = UIColor.labelTextColor2
        timeLabel.textAlignment = .left
        timeLabel.font = UIFont.PFSC_R(ofSize:11)
        whiteView.addSubview(timeLabel)
        
        editBtn = UIButton()
        editBtn.setImage(UIImage(named: "main_time_normal"), for: .normal)
        editBtn.setImage(UIImage(named: "login_privacy_agree"), for: .selected)
        editBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 30, left: 30, bottom: 30, right: 30)
        editBtn.addTarget(self, action: #selector(didEditBtnClicked), for: .touchUpInside)
        whiteView.addSubview(editBtn)
        
        whiteView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-14)
        }

        iconImgV.snp.makeConstraints { make in
            make.width.height.equalTo(31)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(6)
        }
        
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImgV.snp.right).offset(18)
            make.top.equalToSuperview().offset(7)
            make.right.equalTo(editBtn.snp.left)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.left.right.equalTo(nameLabel)
            make.top.equalTo(nameLabel.snp.bottom).offset(2)
            make.bottom.equalToSuperview().offset(-7)
            make.height.equalTo(20)
        }
        
        editBtn.snp.makeConstraints { make in
            make.width.height.equalTo(16)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-37)
        }
    }
}
