package org.jeecg.modules.dynamicStaticAnalysis.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.dynamicStaticAnalysis.dto.AnalysisBatchQueryDTO;
import org.jeecg.modules.dynamicStaticAnalysis.dto.AnalysisBatchSaveOrUpdateDTO;
import org.jeecg.modules.dynamicStaticAnalysis.dto.CheckBatchDTO;
import org.jeecg.modules.dynamicStaticAnalysis.entity.AnalysisBatch;
import org.jeecg.modules.dynamicStaticAnalysis.service.IAnalysisBatchService;
import org.jeecg.modules.dynamicStaticAnalysis.vo.AnalysisBatchQueryVO;
import org.jeecg.modules.dynamicStaticAnalysis.vo.CheckBatchVO;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 动静态分析-分析批次表 前端控制器
 * </p>
 *
 * @author hkl
 * @since 2023-07-26
 */
@RestController
@RequestMapping("/dynamicStaticAnalysis/analysisBatch")
@Api(tags = "动静态分析-分析批次")
public class AnalysisBatchController extends JeecgController<AnalysisBatch, IAnalysisBatchService> {


    @AutoLog(value = "动静态分析-分析批次-获取检查数据")
    @ApiOperation(value = "动静态分析-分析批次-获取检查数据", notes = "动静态分析-分析批次-获取检查数据")
    @GetMapping(value = "/getCheckData")
    public Result<IPage<CheckBatchVO>> getCheckData(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    CheckBatchDTO dto) {
        Page<CheckBatchVO> pageData = new Page<>(pageNo, pageSize);
        pageData = this.service.getCheckData(pageData, dto);
        return Result.OK(pageData);
    }


    @AutoLog(value = "动静态分析-分析批次-获取列表数据")
    @ApiOperation(value = "动静态分析-分析批次-获取列表数据", notes = "动静态分析-分析批次-获取列表数据")
    @GetMapping(value = "/listRecord")
    public Result<IPage<AnalysisBatchQueryVO>> listRecord(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          AnalysisBatchQueryDTO dto) {
        Page<AnalysisBatchQueryVO> pageData = new Page<>(pageNo, pageSize);
        pageData = this.service.listRecord(pageData, dto);

        // 查询明细
        List<AnalysisBatchQueryVO> records = pageData.getRecords();
        if (ObjectUtil.isNotEmpty(records)) {
            // 新增明细
            List<String> analysisBatchIds = records.stream().map(AnalysisBatchQueryVO::getId).collect(Collectors.toList());
            List<CheckBatchVO> checkBatchList = this.service.listRecordDetail(analysisBatchIds);
            if (ObjectUtil.isNotEmpty(checkBatchList)) {
                Map<String, List<CheckBatchVO>> analysisBatchMap = checkBatchList.stream().collect(Collectors.groupingBy(CheckBatchVO::getAnalysisBatchId));
                records.forEach(record -> {
                    List<CheckBatchVO> checkBatchVOS = analysisBatchMap.get(record.getId());
                    record.setCheckBatchList(checkBatchVOS);
                });
            }


            // 获取是否可编辑列表
            List<Map<String, Object>> isEditList = this.service.getIsEditList(analysisBatchIds);
            if (ObjectUtil.isNotEmpty(isEditList)) {
                Map<String, Boolean> isEditMap = isEditList.stream().collect(
                        Collectors.toMap(
                                key -> key.get("id").toString(),
                                value -> !Convert.toBool(value.get("isEdit"))
                        )
                );
                records.forEach(record -> {
                    record.setEdit(isEditMap.get(record.getId()));
                });
            }
        }

        return Result.OK(pageData);
    }


    @AutoLog(value = "动静态分析-分析批次-新增分析批次")
    @ApiOperation(value = "动静态分析-分析批次-新增分析批次", notes = "动静态分析-分析批次-新增分析批次")
    @PostMapping(value = "/saveRecord")
    public Result<String> saveRecord(@RequestBody AnalysisBatchSaveOrUpdateDTO dto) {

        if (dto.getStartingMileage().compareTo(dto.getEndMileage()) > 0) {
            throw new JeecgBootException("起始里程不能大于结束里程");
        }
        // 去重
        AnalysisBatch exist = this.service.lambdaQuery().eq(AnalysisBatch::getAnalysisBatchCode, dto.getAnalysisBatchCode())
                .last("limit 1")
                .one();
        if (exist != null) {
            throw new JeecgBootException("【" + dto.getAnalysisBatchCode() + "】分析批次已存在");
        }


        this.service.saveRecord(dto);

        return Result.OK("操作成功");
    }


    @AutoLog(value = "动静态分析-分析批次-更新分析批次")
    @ApiOperation(value = "动静态分析-分析批次-更新分析批次", notes = "动静态分析-分析批次-更新分析批次")
    @PostMapping(value = "/updateRecord")
    public Result<String> updateRecord(@RequestBody AnalysisBatchSaveOrUpdateDTO dto) {
        if (dto.getStartingMileage().compareTo(dto.getEndMileage()) > 0) {
            throw new JeecgBootException("起始里程不能大于结束里程");
        }
        // 去重
        AnalysisBatch exist = this.service.lambdaQuery()
                .eq(AnalysisBatch::getAnalysisBatchCode, dto.getAnalysisBatchCode())
                .ne(AnalysisBatch::getId, dto.getId())
                .last("limit 1")
                .one();
        if (exist != null) {
            throw new JeecgBootException("【" + dto.getAnalysisBatchCode() + "】分析批次已存在");
        }


        this.service.updateRecord(dto);

        return Result.OK("操作成功");
    }

    @AutoLog(value = "动静态分析-分析批次-通过id删除")
    @ApiOperation(value = "动静态分析-分析批次-通过id删除", notes = "动静态分析-分析批次-通过id删除")
    @GetMapping(value = "/deleteRecord")
    public Result<String> deleteRecord(@RequestParam(name = "id", required = true) String id) {
        this.service.deleteRecord(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "动静态分析-分析批次-批量删除")
    @ApiOperation(value = "动静态分析-分析批次-批量删除", notes = "动静态分析-分析批次-批量删除")
    @GetMapping(value = "/deleteBatchRecord")
    public Result<String> deleteBatchRecord(@RequestParam(name = "ids", required = true) String ids) {
        this.service.removeByIds(Arrays.asList(ids.split(",")));

        return Result.OK("批量删除成功!");
    }


}
