package com.mosty.yjzl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mosty.base.model.dto.yjzl.TbZdxlFgxlrwCreateDTO;
import com.mosty.base.model.dto.yjzl.TbZdxlFgxlrwIssueDTO;
import com.mosty.base.model.dto.yjzl.TbZdxlFgxlrwUpdateDTO;
import com.mosty.base.model.dto.yjzl.ZdyxlFgxlrwDto;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgxlrw;
import com.mosty.base.model.entity.yjzl.zddw.TbZdxlFgzdyrw;
import com.mosty.base.model.query.yjzl.TbZdxlFgxlrwQuery;
import com.mosty.base.model.vo.yjzl.TbZdxlFgxlrwVO;
import com.mosty.base.utils.MessageUtils;
import com.mosty.base.utils.spring.SpringValidUtils;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.entity.log.BusinessType;
import com.mosty.common.base.entity.log.Log;
import com.mosty.common.base.util.StringUtils;
import com.mosty.common.config.Excel.ExcelUtil;
import com.mosty.common.token.JwtSysUser;
import com.mosty.yjzl.service.TbZdxlFgxlrwService;
import com.mosty.yjzl.utils.TbZdxlFgxlrwUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangzhao
 * @description 指导巡逻方格巡逻任务接口
 * @modifier zhangzhao
 * @modifiedTime 2025/05/10 21:52
 * @since 2025/05/10 21:52
 */
@Api(tags = {"指导巡逻-方格巡逻任务接口"})
@RestController
@AllArgsConstructor
@RequestMapping("/tbZdxlFgxlrw")
public class TbZdxlFgxlrwController {

    /**
     * 指导巡逻方格巡逻任务表Service
     */
    private final TbZdxlFgxlrwService tbZdxlFgxlrwService;

    /**
     * 查询分页
     * @param query 实体查询对象
     * @return ResponseResult 实体返回信息分页列表
     */
    @ApiOperation(value = "查询分页")
    @GetMapping("/selectPage")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-查询分页", businessType = BusinessType.OTHER)
    public ResponseResult<IPage<TbZdxlFgxlrwVO>> selectPage(TbZdxlFgxlrwQuery query) {
        return ResponseResult.success(tbZdxlFgxlrwService.selectPage(query));
    }

    /**
     * 查询分页（需要执行的任务）
     * @param query 实体查询对象
     * @return ResponseResult 实体返回信息分页列表
     */
    @ApiOperation(value = "查询分页（需要执行的任务）")
    @GetMapping("/selectRwPage")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-查询分页（需要执行的任务）", businessType = BusinessType.OTHER)
    public ResponseResult<IPage<TbZdxlFgxlrwVO>> selectRwPage(TbZdxlFgxlrwQuery query) {
        return ResponseResult.success(tbZdxlFgxlrwService.selectRwPage(query));
    }

    @ApiOperation(value = "查询详情（需要执行的任务）")
    @GetMapping("/selectByBBdId")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-查询详情（需要执行的任务）", businessType = BusinessType.OTHER)
    public ResponseResult<TbZdxlFgxlrwVO> selectByBBdId(TbZdxlFgxlrwQuery query) {
        return ResponseResult.success(tbZdxlFgxlrwService.selectByBBdId(query));
    }

    /**
     * 查询列表
     * @param query 实体查询对象
     * @return ResponseResult 实体返回信息列表
     */
    @ApiOperation(value = "查询列表")
    @GetMapping("/selectList")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-查询列表", businessType = BusinessType.OTHER)
    public ResponseResult<List<TbZdxlFgxlrwVO>> selectList(TbZdxlFgxlrwQuery query) {
        return ResponseResult.success(tbZdxlFgxlrwService.selectList(query));
    }

    /**
     * 修改单条
     * @param dto 修改DTO对象
     * @param bindResult 校验对象
     * @return ResponseResult 实体主键ID
     */
    @ApiOperation(value = "修改单条")
    @PostMapping("update")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-修改单条", businessType = BusinessType.UPDATE)
    public ResponseResult<String> update(@RequestBody @Valid TbZdxlFgxlrwUpdateDTO dto, BindingResult bindResult){
        try {
            //基础信息校验
            String message = SpringValidUtils.getErrorsMsg(bindResult);
            if (StringUtils.isNotBlank(message)) {
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + message);
            }

            TbZdxlFgxlrw baseEntity = tbZdxlFgxlrwService.selectById(dto.getId());
            if(ObjectUtils.isEmpty(baseEntity)){
                return ResponseResult.fail(MessageUtils.getEditDataNotFoundMsg());
            }
            if(!(TbZdxlFgxlrwUtils.DICT_ITEM_D_ZDXL_FGXLRW_RWZT_CJ.equals(baseEntity.getRwZt()) || TbZdxlFgxlrwUtils.DICT_ITEM_D_ZDXL_FGXLRW_RWZT_YDC.equals(baseEntity.getRwZt()))){
                return ResponseResult.fail(MessageUtils.getEditFailMsg() + "任务已下发，不能再进行修改");
            }

            //修改
            String resultId = tbZdxlFgxlrwService.updateEntity(dto);
            if(StringUtils.isNotBlank(resultId)){
                return ResponseResult.success(resultId);
            }
            return ResponseResult.fail(MessageUtils.getEditFailMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(MessageUtils.getEditServerErrorMsg());
        }
    }

    /**
     * 导出任务（根据任务日期）
     * @param response 返回体
     * @param dto 任务日期DTO
     * @param bindResult 校验对象
     */
    @PostMapping("/exportByRwRq")
    @ApiOperation("导出任务（根据任务日期）")
    @Log(title = "指导巡逻-方格巡逻任务接口-导出任务（根据任务日期）", businessType = BusinessType.OTHER)
    public void exportByRwRq(HttpServletResponse response, @RequestBody @Valid TbZdxlFgxlrwCreateDTO dto, BindingResult bindResult) {
        try {
            //基础信息校验
            String message = SpringValidUtils.getErrorsMsg(bindResult);
            if (StringUtils.isNotBlank(message)) {
                System.out.println(MessageUtils.getExportFailMsg() + message);
            }

            //查询列表
            List<TbZdxlFgxlrw> baseList = tbZdxlFgxlrwService.selectListByRwRq(dto.getRwRq());
            if(CollectionUtils.isEmpty(baseList)){
                System.out.println(MessageUtils.getExportFailMsg() + MessageUtils.message("zdxl.fgxlrw.rwRq.export.queryNull"));
            }else{
                tbZdxlFgxlrwService.updateListRwZtToYdc(baseList);
                ExcelUtil<TbZdxlFgxlrw> util = new ExcelUtil<>(TbZdxlFgxlrw.class);
                util.exportExcel(response, baseList, "任务列表", "方格巡逻任务");
                System.out.println(baseList.size() + "");
            }
        } catch (Exception e) {
            System.out.println(MessageUtils.getExportServerErrorMsg());
        }
    }

    /**
     * 导入列表（根据导出的模板）
     * @param file 导入文件
     * @return ResponseResult 导入条数
     */
    @ApiOperation(value = "导入列表（根据导出的模板）")
    @PostMapping("/importListByMb")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-导入列表（根据导出的模板）", businessType = BusinessType.IMPORT)
    public ResponseResult<Integer> importListByMb(MultipartFile file) {
        try {
            ExcelUtil<TbZdxlFgxlrw> util = new ExcelUtil<>(TbZdxlFgxlrw.class);
            List<TbZdxlFgxlrw> fgxlrwList = util.importExcel(file.getInputStream(), 1);
            if(CollectionUtils.isEmpty(fgxlrwList)){
                return ResponseResult.fail(MessageUtils.getImportFailMsg() + "表格数据获取为空");
            }
            int resultInt = tbZdxlFgxlrwService.importListByMb(fgxlrwList);
            if(resultInt > 0){
                return ResponseResult.success(resultInt);
            }
            return ResponseResult.fail(MessageUtils.getImportFailMsg());
        } catch (Exception e) {
            return ResponseResult.fail(MessageUtils.getImportServerErrorMsg());
        }
    }


    @ApiOperation(value = "导入列表（自定义任务导入）")
    @PostMapping("/importListByMbZdy")
    @JwtSysUser
    @Log(title = "指导巡逻-方格自定义任务接口-导入列表（根据导出的模板）", businessType = BusinessType.IMPORT)
    public ResponseResult<Integer> importListByMbZdy(MultipartFile file) {
        try {
            ExcelUtil<TbZdxlFgzdyrw> util = new ExcelUtil<>(TbZdxlFgzdyrw.class);
            List<TbZdxlFgzdyrw> fgxlrwList = util.importExcel(file.getInputStream(), 1);
            if(CollectionUtils.isEmpty(fgxlrwList)){
                return ResponseResult.fail(MessageUtils.getImportFailMsg() + "表格数据获取为空");
            }
            int resultInt = tbZdxlFgxlrwService.importListByMbZdy(fgxlrwList);
            if(resultInt > 0){
                return ResponseResult.success(resultInt);
            }
            return ResponseResult.fail(MessageUtils.getImportFailMsg());
        } catch (Exception e) {
            return ResponseResult.fail(MessageUtils.getImportServerErrorMsg());
        }
    }

    /**
     * 下发任务
     * @param dto 下发DTO对象
     * @return ResponseResult 实体主键ID
     */
    @ApiOperation(value = "下发任务")
    @PostMapping("issueList")
    @JwtSysUser
    @Log(title = "指导巡逻-方格巡逻任务接口-下发任务", businessType = BusinessType.UPDATE)
    public ResponseResult<Integer> issueList(@RequestBody TbZdxlFgxlrwIssueDTO dto){
        try {
            //基础信息校验
            if(ObjectUtils.isEmpty(dto) || StringUtils.isBlank(dto.getIds())){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "请选择需要下发的任务");
            }

            List<TbZdxlFgxlrw> entityList = tbZdxlFgxlrwService.selectListByIds(dto.getIds());
            if(CollectionUtils.isEmpty(entityList)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "您选择的任务不存在，请刷新页面后重新下发");
            }

            List<TbZdxlFgxlrw> issueList = entityList.stream()
                    .filter(entity -> TbZdxlFgxlrwUtils.DICT_ITEM_D_ZDXL_FGXLRW_RWZT_CJ.equals(entity.getRwZt()) || TbZdxlFgxlrwUtils.DICT_ITEM_D_ZDXL_FGXLRW_RWZT_YDC.equals(entity.getRwZt()))
                    .collect(Collectors.toList());
            if(CollectionUtils.isEmpty(issueList)){
                return ResponseResult.fail(MessageUtils.getSaveFailMsg() + "您选择的任务都已下发，请选择其他任务");
            }

            //下发
            int resultInt = tbZdxlFgxlrwService.issueList(issueList);
            if(resultInt > 0){
                //返回
                return ResponseResult.success(resultInt);
            }
            return ResponseResult.fail(MessageUtils.getSaveFailMsg());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(MessageUtils.getSaveServerErrorMsg());
        }
    }

    @ApiOperation(value = "添加自定义巡逻任务")
    @PostMapping("addZdyxlFgxlrw")
    @JwtSysUser
    public ResponseResult<TbZdxlFgxlrw> addZdyxlFgxlrw(@RequestBody ZdyxlFgxlrwDto dto){
        return ResponseResult.success(tbZdxlFgxlrwService.addZdyxlFgxlrw(dto));
    }

    @ApiOperation(value = "修改自定义巡逻任务")
    @PostMapping("editZdyxlFgxlrw")
    @JwtSysUser
    public ResponseResult<TbZdxlFgxlrw> editZdyxlFgxlrw(@RequestBody ZdyxlFgxlrwDto dto){
        return ResponseResult.success(tbZdxlFgxlrwService.editZdyxlFgxlrw(dto));
    }

    @ApiOperation(value = "添加自定义巡逻任务")
    @PostMapping("delZdyxlFgxlrw")
    @JwtSysUser
    public ResponseResult<Boolean> delZdyxlFgxlrw(@RequestBody ZdyxlFgxlrwDto dto){
        return ResponseResult.success(tbZdxlFgxlrwService.delZdyxlFgxlrw(dto));
    }

}
