/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.testbug.api;

import cn.gjing.tools.auth.annotation.RequiredPermissions;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.common.db.DefaultPagination;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.testbug.api.service.BugManagementApiService;
import net.northking.cctp.testbug.dto.*;
import net.northking.cctp.testbug.dto.bug.BugManageQueryDto;
import net.northking.cctp.testbug.dto.bug.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;

@Api(tags = "缺陷管理")
@RequestMapping("/v1")
@RestController
public class BugManagementQueryCtrl {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(BugManagementQueryCtrl.class);

    @Autowired
    private BugManagementApiService apiService;

    /**
     * 分页查询 调啄木鸟查询接口 缺陷管理 列表
     *
     * @param queryByPage 查询条件
     * @return 数据列表
     */
    @RequiredPermissions("ui-mtDefectManage")
    @ApiOperation(value = "啄木鸟分页查询列表：缺陷管理")
    @PostMapping(value = "/paging/query/bugList",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<ResultResponse> getBugList(
            @RequestBody @Validated BugManageQueryDto queryByPage) {
        ResultWrapper<ResultResponse> wrapper = new ResultWrapper<>();
        ResultResponse page = apiService.getBugList(queryByPage);

        return wrapper.success(page);
    }


    /**
     * 分页查询 缺陷管理 列表
     *
     * @param queryByPage 查询条件
     * @return 数据列表
     */
    @ApiOperation(value = "分页查询列表：缺陷管理")
    @PostMapping(value = "/paging/query/BugManagements",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Pagination<BugManagementDetailDto>> pagingQuery(
            @RequestBody @Validated QueryByPage<BugManagementQueryDto> queryByPage) {
        ResultWrapper<Pagination<BugManagementDetailDto>> wrapper = new ResultWrapper<>();
        Pagination<BugManagementDetailDto> page = apiService.pagingQuery(queryByPage);

        return wrapper.success(page);
    }

    @ApiOperation(value = "导出Excel：缺陷管理")
    @PostMapping(value = "/excel/export/BugManagements",
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void exportExcel(
            @RequestBody @Validated QueryByPage<BugManagementQueryDto> queryByPage,
            HttpServletResponse response) throws UnsupportedEncodingException {

        apiService.exportBugExcel(response, queryByPage);
    }

    @ApiOperation(value = "下载Excel模板：缺陷管理")
    @PostMapping(value = "/excel/template/BugManagements",
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void downloadTemplate(HttpServletResponse response) {
        String fileName = "CCTP模板-缺陷管理";
        apiService.downloadTemplate(response, fileName);
    }

    @ApiOperation(value = "导入Excel：缺陷管理")
    @PostMapping(value = "/excel/import/BugManagements",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultWrapper<Integer> importExcel(
            @RequestParam("file") MultipartFile file) {
        ResultWrapper<Integer> wrapper = new ResultWrapper<>();
        int count = apiService.importExcel(file);

        return wrapper.success(count);
    }

    @ApiOperation("查询所有缺陷发现人")
    @PostMapping("/queryBugCreatedBy")
    public ResultWrapper<List<String>> queryBugCreatedBy(@RequestBody BugManagementQueryDto dto) {

        ResultWrapper<List<String>> wrapper = new ResultWrapper<>();

        List<String> userInfoDtos = apiService.queryBugCreatedBy(dto);

        return wrapper.success(userInfoDtos);
    }

    @ApiOperation("查询所有缺陷分配人")
    @PostMapping("/queryBugReceiver")
    public ResultWrapper<List<String>> queryBugReceiver(@RequestBody BugManagementQueryDto dto) {

        ResultWrapper<List<String>> wrapper = new ResultWrapper<>();

        List<String> userInfoDtos = apiService.queryBugReceiver(dto);

        return wrapper.success(userInfoDtos);
    }

    @ApiOperation("查询模块名")
    @PostMapping("/queryModule")
    public ResultWrapper<List<String>> queryModule(@RequestBody BugManagementQueryDto dto) {

        ResultWrapper<List<String>> wrapper = new ResultWrapper<>();

        List<String> results = apiService.queryModule(dto);

        return wrapper.success(results);
    }

    @ApiOperation("查询缺陷标题")
    @PostMapping("/queryBugTitle")
    public ResultWrapper<List<String>> queryBugTitle(@RequestBody BugManagementQueryDto dto) {

        ResultWrapper<List<String>> wrapper = new ResultWrapper<>();

        List<String> results = apiService.queryBugTitle(dto);

        return wrapper.success(results);
    }

    @ApiOperation("查询缺陷编号")
    @PostMapping("/queryBugOrder")
    public ResultWrapper<List<String>> queryBugOrder(@RequestBody BugManagementQueryDto dto) {

        ResultWrapper<List<String>> wrapper = new ResultWrapper<>();

        List<String> results = apiService.queryBugOrder(dto);

        return wrapper.success(results);
    }

    @ApiOperation(value = "快速操作")
    @PostMapping(value = "/fasterOperate",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Pagination<BugManagementDetailDto>> fasterOperate(
            @RequestBody @Validated QueryByPage<BugManagementQueryDto> queryByPage) {
        ResultWrapper<Pagination<BugManagementDetailDto>> wrapper = new ResultWrapper<>();
        BugManagementQueryDto oldQuery = queryByPage.getQuery();

        BugManagementQueryDto newQuery = new BugManagementQueryDto();
        newQuery.setBugGrades(oldQuery.getBugGrades());
        newQuery.setEmergency(oldQuery.getEmergency());
        newQuery.setReceiver(oldQuery.getReceiver());
        //TODO  按项目引用的缺陷流程模板除去终态筛选
//    //调用外部接口获取缺陷状态列表
        queryByPage.setQuery(newQuery);
        Pagination<BugManagementDetailDto> page = apiService.pagingQuery(queryByPage);

        return wrapper.success(page);
    }

    /**
     * 分页查询 缺陷管理 列表 过滤
     *
     * @param queryByPage 查询条件
     * @return 数据列表
     */
    @ApiOperation(value = "分页查询列表：缺陷管理 过滤")
    @PostMapping(value = "/paging/queryFilter/BugManagements",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<DefaultPagination<BugManagementDetailDto>> pagingQueryFilter(
            @RequestBody @Validated QueryByPage<BugManagementQueryDto> queryByPage) {
        ResultWrapper<DefaultPagination<BugManagementDetailDto>> wrapper = new ResultWrapper<>();
        DefaultPagination<BugManagementDetailDto> page = apiService.pagingQueryFilter(queryByPage);

        return wrapper.success(page);
    }

    @ApiOperation("查询用户是否在项目创建或被分配缺陷")
    @PostMapping(value = "/queryUserIsCreatedBugByProId",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<Boolean> queryUserIsCreatedBugByProId(@RequestParam("projectId") String projectId,
                                                               @RequestParam(value = "userId", required = false) String userId) {

        ResultWrapper<Boolean> wrapper = new ResultWrapper<>();

        boolean results = apiService.queryUserBugByProId(projectId, userId);

        return wrapper.success(results);
    }

    @ApiOperation("查询缺陷趋势图信息")
    @PostMapping(value = "/queryTestBugChart",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<List<BugTendencyChartDetailDto>> queryTestBugChart(@RequestBody BugTendencyChartQueryDto bugTendencyChartQueryDto) {
        ResultWrapper<List<BugTendencyChartDetailDto>> wrapper = new ResultWrapper<>();
        List<BugTendencyChartDetailDto> bugTendencyChartDetailDtos = apiService.queryBugByStatus(bugTendencyChartQueryDto);
        //时间戳转化
        bugTendencyChartDetailDtos.forEach(bugTendencyChartDetailDto -> {
            bugTendencyChartDetailDto.setViewTime(new SimpleDateFormat("yyyy-MM-dd").format(bugTendencyChartDetailDto.getCreatedTime().getTime()));
            bugTendencyChartDetailDto.setCreatedTime(null);
        });
        return wrapper.success(bugTendencyChartDetailDtos);
    }

    @ApiOperation("查询高紧急程度/严重程度列表")
    @PostMapping(value = "/queryHighDegreeList",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<DefaultPagination<BugHighDegreeChartDetailDto>> queryHighDegreeList(@RequestBody QueryByPage<BugHighDegreeChartQueryDto> queryByPage) {
        ResultWrapper<DefaultPagination<BugHighDegreeChartDetailDto>> wrapper = new ResultWrapper<>();
        DefaultPagination<BugHighDegreeChartDetailDto> page = apiService.pagingQueryHighDegree(queryByPage);
        return wrapper.success(page);
    }

    @ApiOperation("按要求统计缺陷相关数据")
    @PostMapping(value = "/countBugAmount",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<CountBugDetailDto> countBugAmount(@RequestBody String projectId) {
        ResultWrapper<CountBugDetailDto> wrapper = new ResultWrapper<>();
        CountBugDetailDto countBugDetailDto = apiService.countBugAmount(projectId);
        if (null != countBugDetailDto) {
            logger.info("缺陷相关数据对象为" + countBugDetailDto.toString());
        }
        return wrapper.success(countBugDetailDto);
    }

    @ApiOperation(value = "分页查询列表：缺陷管理 过滤")
    @PostMapping(value = "/paging/queryFilter/BugManagementss",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultWrapper<DefaultPagination<BugManagementDetailDto>> pagingQueryFilter2(
            @RequestBody @Validated QueryByPage<BugManagementQueryDto> queryByPage) {
        ResultWrapper<DefaultPagination<BugManagementDetailDto>> wrapper = new ResultWrapper<>();
        DefaultPagination<BugManagementDetailDto> page = new DefaultPagination<>();

        long l = System.currentTimeMillis();
        logger.info("行260开始:0");
        //用pagehelper 查询数据
        if (queryByPage.getPageNo() <= 0) {
            queryByPage.setPageNo(1);
        }

        if (queryByPage.getPageSize() <= 0 || queryByPage.getPageSize() > 500) {
            queryByPage.setPageSize(500);
        }
        PageHelper.startPage(queryByPage.getPageNo(), queryByPage.getPageSize());
        List<BugManagementDetailDto> pageDto = apiService.pageQ(queryByPage.getQuery());
        PageInfo<BugManagementDetailDto> pageTmp = new PageInfo<>(pageDto);
        page.setRecords(pageTmp.getList());
        page.setPageNo(pageTmp.getPageNum());
        page.setPageSize(pageTmp.getPageSize());
        page.setRecordCount(pageTmp.getTotal());
        logger.info("行260结束:" + (System.currentTimeMillis() - l));
        return wrapper.success(page);
    }

}


