package com.fs.app.controller;

import com.fs.app.annotation.Login;
import com.fs.app.dto.TaskCountDto;
import com.fs.app.dto.TaskInfoDto;
import com.fs.doctor.domain.Doctor;
import com.fs.doctor.mapper.DoctorMapper;
import com.fs.doctor.service.IDoctorService;
import com.fs.system.vo.CommonCompanyInfo;
import com.fs.task.dto.TaskDeliveryDto;
import com.fs.app.service.AppTaskService;
import com.fs.audit.enums.CreditStatus;
import com.fs.common.config.LoginContextManager;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.project.domain.Project;
import com.fs.project.mapper.ProjectMapper;
import com.fs.task.domain.TaskInfo;
import com.fs.task.service.ITaskInfoService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.github.pagehelper.page.PageMethod.startPage;


@Api(tags = "项目管理接口")
@RestController
@RequestMapping(value="/app/task")
public class AppTaskController extends AppBaseController {

    @Autowired
    private AppTaskService taskService;

    @Autowired
    private ITaskInfoService taskInfoService;

    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private IDoctorService iDoctorService;
    @Autowired
    private DoctorMapper doctorMapper;

    /**
     * 查询所有项目
     */
    @ApiOperation("查询有效项目列表 项目标签字典key： project_label")
    @GetMapping("/getProjectList")
    @Login
    public AjaxResult getProjectList()
    {
        String userId = getUserId();
        Doctor doctor = doctorMapper.selectDoctorById(Long.parseLong(userId));
        CommonCompanyInfo companyIdAndCompanyUserId = getCompanyIdAndCompanyUserId(doctor.getDoctorId());
        Project project = new Project();
        project.setStatus(0);
        project.setDelFlag(0L);
        project.setCompanyId(companyIdAndCompanyUserId.getCompanyId());
        List<Project> projects = projectMapper.selectProjectList(project);
        return AjaxResult.success(projects);
    }


    /**
     * 查询任务信息列表
     */
    @ApiOperation("查询任务信息列表")
    @GetMapping("/getTaskList")
    @Login
    public TableDataInfo list(TaskInfoDto taskInfoDto)
    {
        String userId = getUserId();
        startPage();
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setDoctorId(Long.parseLong(userId));
        taskInfo.setCreateAuditStatus(CreditStatus.APPROVED.getCode());

        if (taskInfoDto.getTaskType() != null){
            taskInfo.setTaskType(Long.valueOf(taskInfoDto.getTaskType()));
        }
        if (taskInfoDto.getApplyEndTime() != null && taskInfoDto.getApplyStartTime() != null){
            taskInfo.setApplyStartTime(taskInfoDto.getApplyStartTime());
            taskInfo.setApplyEndTime(taskInfoDto.getApplyEndTime());
        }
        if (taskInfoDto.getTimeType() != null){
            taskInfo.setTimeType(taskInfoDto.getTimeType());
        }
        if (taskInfoDto.getSelectType() != null){
            taskInfo.setSelectType(taskInfoDto.getSelectType());
        }
        if (taskInfoDto.getFinishAuditStatus() != null){
            taskInfo.setFinishAuditStatus(taskInfoDto.getFinishAuditStatus());
        }


        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo);
        return getDataTable(list);
    }

    /**
     * 查询任务信息列表
     */
    @ApiOperation("查询任务统计信息")
    @GetMapping("/getTaskCountList")
    @Login
    public Map<String, Object> getTaskCountList(TaskCountDto taskCountDto)
    {
        String userId = getUserId();
        startPage();
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setDoctorId(Long.parseLong(userId));
        taskInfo.setCreateAuditStatus(CreditStatus.APPROVED.getCode());
        if (taskCountDto.getTaskType() != null){
            taskInfo.setTaskType(taskCountDto.getTaskType());
        }
        if (taskCountDto.getApplyStartTime() != null && taskCountDto.getApplyEndTime() != null){
            taskInfo.setApplyStartTime(taskCountDto.getApplyStartTime());
            taskInfo.setApplyEndTime(taskCountDto.getApplyEndTime());
        }
        if (taskCountDto.getFinishStatus() != null){
            taskInfo.setFinishStatus(taskCountDto.getFinishStatus());
        }
        if (taskCountDto.getFinishAuditStatus() != null){
            taskInfo.setFinishAuditStatus(taskCountDto.getFinishAuditStatus());
        }
        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo);

        // 统计条数
        long totalCount = list.size();

        // 统计taskIntegral字段的和
        BigDecimal totalIntegral = list.stream()
                .map(TaskInfo::getTaskIntegral)
                .filter(Objects::nonNull) // 过滤掉null值
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 获取分页信息
        PageInfo<TaskInfo> pageInfo = new PageInfo<>(list);

        // 创建Map并放入数据
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalCount", totalCount);
        result.put("totalIntegral", totalIntegral);
        result.put("pageNum", pageInfo.getPageNum());
        result.put("pageSize", pageInfo.getPageSize());
        result.put("total", pageInfo.getTotal());
        result.put("pages", pageInfo.getPages());

        return result;
    }

    /**
     * 去完成任务
     */
    @ApiOperation("去完成任务")
    @PostMapping("/completeTask")
    @Login
    public AjaxResult completeTask(@RequestBody TaskDeliveryDto taskDeliveryDto)
    {
        String userId = getUserId();
        Doctor doctor = iDoctorService.selectDoctorById(Long.parseLong(userId));
        CommonCompanyInfo commonCompanyInfo = getCompanyIdAndCompanyUserId(doctor.getDoctorId());
        taskDeliveryDto.setUserId(userId);
        taskDeliveryDto.setCompanyId(commonCompanyInfo.getCompanyId());
        taskService.completeTask(taskDeliveryDto);

        return AjaxResult.success("已完成，请等待审核");
    }

    /**
     * 获取任务信息详细信息
     */
    @ApiOperation("获取任务信息详细信息")
    @GetMapping(value = "getTaskInfo/{id}")
    public AjaxResult getTaskInfo(@PathVariable("id") Long id)
    {

        TaskInfo taskInfo = taskInfoService.selectTaskInfoById(id);
        TaskDeliveryDto taskDelivery = taskInfoService.getTaskDelivery(id);
        taskInfo.setTaskDelivery(taskDelivery);
        return AjaxResult.success(taskInfo);
    }



}
