package com.bs.ct.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.core.domain.model.LoginUser;
import com.bs.ct.domain.*;
import com.bs.ct.service.*;
import com.bs.system.service.ISysDeptService;
import com.bs.system.service.ISysUserService;
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 javax.annotation.Resource;

/**
 * 任务反馈Controller
 *
 * @author bs
 * @date 2025-02-22
 */
@Api(tags = "任务反馈")
@RestController
@RequestMapping("/task/feedback")
public class CtTaskFeedbackController extends BaseController {
    @Resource
    private ICtTaskFeedbackService ctTaskFeedbackService;
    @Resource
    private ICtTaskInfoService ctTaskInfoService;
    @Autowired
    private ISysUserService userService;
    @Resource
    private ICmAttachService cmAttachService;
    @Resource
    private ICtTaskTagService ctTaskTagService;
    @Resource
    private ICtImagesFeedbackRefService ctImagesFeedbackRefService;
    @Resource
    private ICtGalleryImagesService ctGalleryImagesService;
    @Resource
    private ICtGalleryImagesTagService ctGalleryImagesTagService;
    @Autowired
    private ISysDeptService deptService;
    /**
     * 分页查询任务反馈列表
     */
    @ApiOperation("分页查询任务反馈列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CtTaskFeedback ctTaskFeedback) {
        startPage();
        LambdaQueryWrapper<CtTaskFeedback> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskFeedback);
        List<CtTaskFeedback> list = ctTaskFeedbackService.list(queryWrapper);
        return getDataTable(list);
    }

    private void setFile(List<CtTaskFeedback> list) {
        for (CtTaskFeedback ctFeedback : list) {
            List<CtImagesFeedbackRef> ctImagesFeedbackRefs = ctImagesFeedbackRefService.list(new LambdaQueryWrapper<CtImagesFeedbackRef>()
                    .eq(CtImagesFeedbackRef::getFeedbackId, ctFeedback.getId()));
            if (null != ctImagesFeedbackRefs && ctImagesFeedbackRefs.size() > 0) {
                List<Long> imageIds = ctImagesFeedbackRefs.stream()
                        .map(CtImagesFeedbackRef::getImageId)
                        .collect(Collectors.toList());
                List<CtGalleryImages> galleryImages = ctGalleryImagesService.list(new LambdaQueryWrapper<CtGalleryImages>()
                        .in(CtGalleryImages::getId, imageIds));
                List<Long> fileIds = galleryImages.stream()
                        .map(CtGalleryImages::getFileId)
                        .collect(Collectors.toList());
                List<CmAttach> cmAttachList = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().in(CmAttach::getFileId,fileIds));
                ctFeedback.setFile(cmAttachList);
            }
        }
    }

    //

    /**
     * 通过图片新增任务反馈
     */
    @ApiOperation("通过图片新增任务反馈")
    @Log(title = "通过图片新增任务反馈", businessType = BusinessType.INSERT)
    @PostMapping("/addByImage")
    public AjaxResult addByImage(@RequestBody CtTaskFeedback ctTaskFeedback) {
        List<Long> imageIds = ctTaskFeedback.getImageIds();
        Long taskId = ctTaskFeedback.getTaskId();
        List<CtTaskTag> ctTaskTags = ctTaskTagService.list(new LambdaQueryWrapper<CtTaskTag>()
                .eq(CtTaskTag::getTaskId, taskId));
        List<String> tagNamesByTag = ctTaskTags.stream()
                .map(CtTaskTag::getTagName)
                .collect(Collectors.toList());
        LoginUser loginUser = getLoginUser();
        SysDept sysDept = deptService.selectDeptById(loginUser.getDeptId());
        List<Long> notTags = new ArrayList<>();
        Map<String, List<Long>> tagImageIdMap = new HashMap<>();
        for (Long imageId : imageIds) {
            List<CtGalleryImagesTag> ctGalleryImagesTags = ctGalleryImagesTagService.list(new LambdaQueryWrapper<CtGalleryImagesTag>()
                   .eq(CtGalleryImagesTag::getImageId, imageId));
            List<String> tagNames = ctGalleryImagesTags.stream()
                    .map(CtGalleryImagesTag::getTagName)
                    .collect(Collectors.toList());
            boolean hasMatch = false;
            for (String tagName : tagNames) {
                if (tagNamesByTag.contains(tagName)) {
                    tagImageIdMap.computeIfAbsent(tagName, k -> new ArrayList<>()).add(imageId);
                    hasMatch = true;
                }
            }
            if (!hasMatch) {
                notTags.add(imageId);
            }
        }
        // 为每个标签组创建反馈任务
        for (Map.Entry<String, List<Long>> entry : tagImageIdMap.entrySet()) {
            String tagName = entry.getKey();
            List<Long> groupImageIds = entry.getValue();
            Optional<CtTaskTag> firstMatch = ctTaskTags.stream()
                    .filter(tag -> tagName.equals(tag.getTagName()))
                    .findFirst();
            if (firstMatch.isPresent()) {
                CtTaskTag tag = firstMatch.get();
                CtTaskFeedback feedback = new CtTaskFeedback();
                feedback.setTaskId(taskId);
                feedback.setTaskTagId(tag.getId());
                feedback.setImageIds(groupImageIds);
                feedback.setFeedbackTime(new Date());
                feedback.setUserId(String.valueOf(loginUser.getUserId()));
                feedback.setUserName(loginUser.getUsername());
                feedback.setBranchCode(String.valueOf(loginUser.getDeptId()));
                feedback.setUserDept(sysDept.getDeptName());
                boolean save = ctTaskFeedbackService.save(feedback);
                if (save) {
                    saveRef(feedback);
                }
            }
        }
        return success(notTags);
    }

    /**
     * 查询任务反馈列表
     */
    @ApiOperation("查询任务反馈列表")
    @GetMapping("/list")
    public AjaxResult list(CtTaskFeedback ctTaskFeedback) {
        LambdaQueryWrapper<CtTaskFeedback> queryWrapper = new LambdaQueryWrapper();
        if (-1 == ctTaskFeedback.getTaskTagId()) {
            queryWrapper.eq(CtTaskFeedback::getTaskId, ctTaskFeedback.getTaskId())
                    .eq(CtTaskFeedback::getTaskBranchId,ctTaskFeedback.getTaskBranchId())
                    .isNull(CtTaskFeedback::getTaskTagId);
        } else {
            condition(queryWrapper,ctTaskFeedback);
        }
        List<CtTaskFeedback> list = ctTaskFeedbackService.list(queryWrapper);
        setFile(list);
        return success(list);
    }

    /**
     * 通过标签查询任务反馈列表
     */
    @ApiOperation("通过标签查询任务反馈列表")
    @GetMapping("/listByTag")
    public AjaxResult listByTag(CtTaskFeedback ctTaskFeedback) {
        Map<String, Object> map = new HashMap<>();
        List<CtTaskTag> ctTaskTags = ctTaskTagService.list(new LambdaQueryWrapper<CtTaskTag>().eq(CtTaskTag::getTaskId, ctTaskFeedback.getTaskId()));
        List<CtTaskFeedback> ctTaskFeedbacks = ctTaskFeedbackService.list(new LambdaQueryWrapper<CtTaskFeedback>()
                .eq(CtTaskFeedback::getTaskId, ctTaskFeedback.getTaskId())
                .eq(CtTaskFeedback::getTaskBranchId,ctTaskFeedback.getTaskBranchId())
                .isNull(CtTaskFeedback::getTaskTagId));
        for (CtTaskTag taskTag : ctTaskTags) {
            LambdaQueryWrapper<CtTaskFeedback> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(CtTaskFeedback::getTaskTagId,taskTag.getId());
            queryWrapper.eq(CtTaskFeedback::getTaskBranchId,ctTaskFeedback.getTaskBranchId());
            List<CtTaskFeedback> list = ctTaskFeedbackService.list(queryWrapper);
            setFile(list);
            taskTag.setCtTaskFeedbacks(list);
        }
        map.put("ctTaskTags",ctTaskTags);
        map.put("ctTaskFeedbacks",ctTaskFeedbacks);
        return success(map);
    }



    /**
     * 导出任务反馈列表
     */
    @ApiOperation("导出任务反馈列表")
    @Log(title = "任务反馈导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CtTaskFeedback ctTaskFeedback) {
        LambdaQueryWrapper<CtTaskFeedback> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,ctTaskFeedback);
        List<CtTaskFeedback> list = ctTaskFeedbackService.list(queryWrapper);
        ExcelUtil<CtTaskFeedback> util = new ExcelUtil<CtTaskFeedback>(CtTaskFeedback. class);
        util.exportExcel(response, list, "任务反馈数据");
    }

    /**
     * 获取任务反馈详细信息
     */
    @ApiOperation("获取任务反馈详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ctTaskFeedbackService.getById(id));
    }

    /**
     * 新增任务反馈
     */
    @ApiOperation("新增任务反馈")
    @Log(title = "任务反馈新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CtTaskFeedback ctTaskFeedback) {
        updateFile(ctTaskFeedback);
        boolean save = ctTaskFeedbackService.save(ctTaskFeedback);
        if (save) {
            saveRef(ctTaskFeedback);
        }
        return toAjax(true);
    }

    private void saveRef(CtTaskFeedback ctTaskFeedback) {
        List<Long> imageIds = ctTaskFeedback.getImageIds();
        if (null != imageIds && imageIds.size() > 0) {
            for (Long imageId : imageIds) {
                CtImagesFeedbackRef ctImagesFeedbackRef = new CtImagesFeedbackRef();
                ctImagesFeedbackRef.setFeedbackId(ctTaskFeedback.getId());
                ctImagesFeedbackRef.setImageId(imageId);
                ctImagesFeedbackRefService.save(ctImagesFeedbackRef);
            }
        }
    }

    private void updateFile(CtTaskFeedback ctTaskFeedback) {
        Long newId = System.currentTimeMillis() + new Random().nextInt(1000);
        List<CmAttach> file = ctTaskFeedback.getFile();
        if (null != file) {
            for (CmAttach cmAttach : file) {
                cmAttach.setFileId(String.valueOf(newId));
            }
            cmAttachService.updateBatchById(file);
            ctTaskFeedback.setFileId(newId);
        }
    }

    /**
     * 修改任务反馈
     */
    @ApiOperation("修改任务反馈")
    @Log(title = "任务反馈修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CtTaskFeedback ctTaskFeedback) {
        updateFile(ctTaskFeedback);
        saveRef(ctTaskFeedback);
        return toAjax(ctTaskFeedbackService.updateById(ctTaskFeedback));
    }

    /**
     * 删除任务反馈
     */
    @ApiOperation("删除任务反馈")
    @Log(title = "任务反馈删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(ctTaskFeedbackService.removeBatchByIds(ids));
    }

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


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

        //任务id
        if(Validator.isNotEmpty(ctTaskFeedback.getTaskId())){
            queryWrapper.eq(CtTaskFeedback::getTaskId,ctTaskFeedback.getTaskId());
        }

        //任务id
        if(Validator.isNotEmpty(ctTaskFeedback.getTaskTagId())){
            queryWrapper.eq(CtTaskFeedback::getTaskTagId,ctTaskFeedback.getTaskTagId());
        }

        //机构任务id
        if(Validator.isNotEmpty(ctTaskFeedback.getTaskBranchId())){
            queryWrapper.eq(CtTaskFeedback::getTaskBranchId,ctTaskFeedback.getTaskBranchId());
        }

        //机构代码
        if(Validator.isNotEmpty(ctTaskFeedback.getBranchCode())){
            queryWrapper.eq(CtTaskFeedback::getBranchCode,ctTaskFeedback.getBranchCode());
        }

        //任务反馈时间
        if(Validator.isNotEmpty(ctTaskFeedback.getFeedbackTime())){
            queryWrapper.eq(CtTaskFeedback::getFeedbackTime,ctTaskFeedback.getFeedbackTime());
        }

        //任务完成情况
        if(Validator.isNotEmpty(ctTaskFeedback.getTaskDesc())){
            queryWrapper.eq(CtTaskFeedback::getTaskDesc,ctTaskFeedback.getTaskDesc());
        }

        //操作人员工号
        if(Validator.isNotEmpty(ctTaskFeedback.getUserId())){
            queryWrapper.eq(CtTaskFeedback::getUserId,ctTaskFeedback.getUserId());
        }

        //操作人员姓名
        if(Validator.isNotEmpty(ctTaskFeedback.getUserName())){
            queryWrapper.eq(CtTaskFeedback::getUserName,ctTaskFeedback.getUserName());
        }

        //操作人员部门
        if(Validator.isNotEmpty(ctTaskFeedback.getUserDept())){
            queryWrapper.eq(CtTaskFeedback::getUserDept,ctTaskFeedback.getUserDept());
        }

        //是否已拍照留存
        if(Validator.isNotEmpty(ctTaskFeedback.getIsPhoto())){
            queryWrapper.eq(CtTaskFeedback::getIsPhoto,ctTaskFeedback.getIsPhoto());
        }

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

        //审核人员id
        if(Validator.isNotEmpty(ctTaskFeedback.getCheckUserId())){
            queryWrapper.eq(CtTaskFeedback::getCheckUserId,ctTaskFeedback.getCheckUserId());
        }

        //审核人员姓名
        if(Validator.isNotEmpty(ctTaskFeedback.getCheckUserName())){
            queryWrapper.eq(CtTaskFeedback::getCheckUserName,ctTaskFeedback.getCheckUserName());
        }

        //审核人员部门
        if(Validator.isNotEmpty(ctTaskFeedback.getCheckUserDept())){
            queryWrapper.eq(CtTaskFeedback::getCheckUserDept,ctTaskFeedback.getCheckUserDept());
        }

        //审核时间
        if(Validator.isNotEmpty(ctTaskFeedback.getCheckDate())){
            queryWrapper.eq(CtTaskFeedback::getCheckDate,ctTaskFeedback.getCheckDate());
        }

        //审核状态
        if(Validator.isNotEmpty(ctTaskFeedback.getStatus())){
            queryWrapper.eq(CtTaskFeedback::getStatus,ctTaskFeedback.getStatus());
        }

        //审核信息
        if(Validator.isNotEmpty(ctTaskFeedback.getCheckInfo())){
            queryWrapper.eq(CtTaskFeedback::getCheckInfo,ctTaskFeedback.getCheckInfo());
        }

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

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

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

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

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

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

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

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

        }

}
