package com.bs.ct.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.config.BsConfig;
import com.bs.common.utils.file.FileUploadUtils;
import com.bs.common.utils.file.FileUtils;
import com.bs.ct.domain.CtTaskFeedback;
import com.bs.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.ct.domain.CtGalleryImages;
import com.bs.ct.service.ICtGalleryImagesService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 图库图片Controller
 *
 * @author bs
 * @date 2025-02-22
 */
@Api(tags = "图库图片")
@RestController
@RequestMapping("/gallery/images")
public class CtGalleryImagesController extends BaseController {
    @Resource
    private ICtGalleryImagesService ctGalleryImagesService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ICmAttachService cmAttachService;
    /**
     * 分页查询图库图片列表
     */
    @ApiOperation("分页查询图库图片列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CtGalleryImages ctGalleryImages) {
        startPage();
        LambdaQueryWrapper<CtGalleryImages> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryImages);
        List<CtGalleryImages> list = ctGalleryImagesService.list(queryWrapper);
        setFile(list);
        return getDataTable(list);
    }

    private void setFile(List<CtGalleryImages> list) {
        for (CtGalleryImages ctGalleryImages : list) {
            List<CmAttach> cmAttachList = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId,ctGalleryImages.getFileId()));
            ctGalleryImages.setFile(cmAttachList);
        }
    }

    /**
     * 查询图库图片列表
     */
    @ApiOperation("查询图库图片列表")
    @GetMapping("/list")
    public AjaxResult list(CtGalleryImages ctGalleryImages) {
        LambdaQueryWrapper<CtGalleryImages> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryImages);
        List<CtGalleryImages> list = ctGalleryImagesService.list(queryWrapper);
        return success(list);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, String fileId, Long cataId, String imageTitle, Date photoTime,Date uploadTime,
                                 String isOpen,String keyWords,String remarks
                                 ) throws Exception
    {
        try
        {
            Long newId = System.currentTimeMillis() + new Random().nextInt(1000);
            CtGalleryImages ctGalleryImages = new CtGalleryImages();
            ctGalleryImages.setCataId(cataId);
            ctGalleryImages.setImageTitle(imageTitle);
            ctGalleryImages.setPhotoTime(photoTime);
            ctGalleryImages.setUploadTime(uploadTime);
            ctGalleryImages.setIsOpen(isOpen);
            ctGalleryImages.setKeyWords(keyWords);
            ctGalleryImages.setRemarks(remarks);
            ctGalleryImages.setFileId(newId);
            // 上传文件路径
            String filePath = BsConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String newFileName = FileUtils.getName(fileName);
            String originalFilename = file.getOriginalFilename();
            CmAttach cmAttach = new CmAttach();
            cmAttach.setFileId(String.valueOf(newId));
            cmAttach.setFileSort(1L);
            cmAttach.setAttachName(newFileName);
            cmAttach.setAttachContentType(file.getContentType());
            cmAttach.setAttachFileSize(file.getSize());
            cmAttach.setAttachFileUrl(fileName);
            cmAttach.setOldName(originalFilename);
            cmAttach.setVersionNo("1");
            cmAttach.setRemark("");
            boolean save = cmAttachService.save(cmAttach);
            if (save) {
                Long id = cmAttach.getId();
                AjaxResult ajax = AjaxResult.success();
                ajax.put("cmAttach", cmAttach);
                ctGalleryImages.setImageName(originalFilename);
                ctGalleryImages.setImagePath(fileName);
                ctGalleryImages.setImageSize(BigDecimal.valueOf(file.getSize()));
                ctGalleryImages.setFileId(newId);
                boolean saveImage = ctGalleryImagesService.save(ctGalleryImages);
                return ajax;
            }
            return null;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 导出图库图片列表
     */
    @ApiOperation("导出图库图片列表")
    @Log(title = "图库图片导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CtGalleryImages ctGalleryImages) {
        LambdaQueryWrapper<CtGalleryImages> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctGalleryImages);
        List<CtGalleryImages> list = ctGalleryImagesService.list(queryWrapper);
        ExcelUtil<CtGalleryImages> util = new ExcelUtil<CtGalleryImages>(CtGalleryImages. class);
        util.exportExcel(response, list, "图库图片数据");
    }

    /**
     * 获取图库图片详细信息
     */
    @ApiOperation("获取图库图片详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ctGalleryImagesService.getById(id));
    }

    /**
     * 新增图库图片
     */
    @ApiOperation("新增图库图片")
    @Log(title = "图库图片新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CtGalleryImages ctGalleryImages) {
        return toAjax(ctGalleryImagesService.save(ctGalleryImages));
    }

    /**
     * 修改图库图片
     */
    @ApiOperation("修改图库图片")
    @Log(title = "图库图片修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CtGalleryImages ctGalleryImages) {
        return toAjax(ctGalleryImagesService.updateById(ctGalleryImages));
    }

    /**
     * 删除图库图片
     */
    @ApiOperation("删除图库图片")
    @Log(title = "图库图片删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(ctGalleryImagesService.removeBatchByIds(ids));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CtGalleryImages> queryWrapper,CtGalleryImages ctGalleryImages){


        //id
        if(Validator.isNotEmpty(ctGalleryImages.getId())){
            queryWrapper.eq(CtGalleryImages::getId,ctGalleryImages.getId());
        }

        //目录id
        if(Validator.isNotEmpty(ctGalleryImages.getCataId())){
            queryWrapper.eq(CtGalleryImages::getCataId,ctGalleryImages.getCataId());
        }

        //图片名称
        if(Validator.isNotEmpty(ctGalleryImages.getImageName())){
            queryWrapper.eq(CtGalleryImages::getImageName,ctGalleryImages.getImageName());
        }

        //图片标题
        if(Validator.isNotEmpty(ctGalleryImages.getImageTitle())){
            queryWrapper.eq(CtGalleryImages::getImageTitle,ctGalleryImages.getImageTitle());
        }

        //图片路径
        if(Validator.isNotEmpty(ctGalleryImages.getImagePath())){
            queryWrapper.eq(CtGalleryImages::getImagePath,ctGalleryImages.getImagePath());
        }

        //图片大小
        if(Validator.isNotEmpty(ctGalleryImages.getImageSize())){
            queryWrapper.eq(CtGalleryImages::getImageSize,ctGalleryImages.getImageSize());
        }

        //图片拍摄时间
        if(Validator.isNotEmpty(ctGalleryImages.getPhotoTime())){
            queryWrapper.eq(CtGalleryImages::getPhotoTime,ctGalleryImages.getPhotoTime());
        }

        //图片上传时间
        if(Validator.isNotEmpty(ctGalleryImages.getUploadTime())){
            queryWrapper.eq(CtGalleryImages::getUploadTime,ctGalleryImages.getUploadTime());
        }

        //是否公开
        if(Validator.isNotEmpty(ctGalleryImages.getIsOpen())){
            queryWrapper.eq(CtGalleryImages::getIsOpen,ctGalleryImages.getIsOpen());
        }

        //图片关键字
        if(Validator.isNotEmpty(ctGalleryImages.getKeyWords())){
            queryWrapper.eq(CtGalleryImages::getKeyWords,ctGalleryImages.getKeyWords());
        }

        //附件id
        if(Validator.isNotEmpty(ctGalleryImages.getFileId())){
            queryWrapper.eq(CtGalleryImages::getFileId,ctGalleryImages.getFileId());
        }

        //备注
        if(Validator.isNotEmpty(ctGalleryImages.getRemarks())){
            queryWrapper.eq(CtGalleryImages::getRemarks,ctGalleryImages.getRemarks());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(ctGalleryImages.getDelFlag())){
            queryWrapper.eq(CtGalleryImages::getDelFlag,ctGalleryImages.getDelFlag());
        }

        //创建部门
        if(Validator.isNotEmpty(ctGalleryImages.getCreateDept())){
            queryWrapper.eq(CtGalleryImages::getCreateDept,ctGalleryImages.getCreateDept());
        }

        //创建人
        if(Validator.isNotEmpty(ctGalleryImages.getCreateBy())){
            queryWrapper.eq(CtGalleryImages::getCreateBy,ctGalleryImages.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(ctGalleryImages.getCreateTime())){
            queryWrapper.eq(CtGalleryImages::getCreateTime,ctGalleryImages.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(ctGalleryImages.getUpdateBy())){
            queryWrapper.eq(CtGalleryImages::getUpdateBy,ctGalleryImages.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(ctGalleryImages.getUpdateTime())){
            queryWrapper.eq(CtGalleryImages::getUpdateTime,ctGalleryImages.getUpdateTime());
        }

        //租户ID
        if(Validator.isNotEmpty(ctGalleryImages.getTenantId())){
            queryWrapper.eq(CtGalleryImages::getTenantId,ctGalleryImages.getTenantId());
        }

        }

}
