package com.fs.app.controller;

import com.fs.app.annotation.Login;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.TaskLabelEnum;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.live.domain.LiveBroadcast;
import com.fs.live.service.ILiveBroadcastService;
import com.fs.survey.domain.DrugResearch;
import com.fs.survey.domain.SurveyTask;
import com.fs.survey.dto.PeriodDataDto;
import com.fs.survey.service.IDrugResearchService;
import com.fs.survey.service.ISurveyTaskPeriodService;
import com.fs.survey.service.ISurveyTaskService;
import com.fs.task.domain.TaskInfo;
import com.fs.task.dto.TaskStatsDTO;
import com.fs.task.enums.TaskTypeEnum;
import com.fs.task.service.ITaskInfoService;
import com.fs.task.vo.*;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务信息Controller
 *
 * @author fs
 * @date 2026-01-04
 */
@RestController
@RequestMapping("/task/info")
public class TaskInfoController extends BaseController {
    @Autowired
    private ITaskInfoService taskInfoService;
    @Autowired
    private ISurveyTaskService iSurveyTaskService;
    @Autowired
    private ISurveyTaskPeriodService surveyTaskPeriodService;
    @Autowired
    private ILiveBroadcastService liveBroadcastService;
    @Autowired
    private IDrugResearchService iDrugResearchService;
    /**
     * 查询任务信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TaskInfo taskInfo) {
        startPage();
        taskInfo.setCompanyId(taskInfo.getCompanyId());
        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo);
        return getDataTable(list);
    }


    /**
     * 任务完成统计
     *
     * @return AjaxResult
     */
    @PostMapping("/getTaskCompleteStats")
    public AjaxResult getTaskCompleteStats(@RequestBody GetTaskCompleteStatsVO param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());

        List<TaskStatsDTO> list = taskInfoService.getTaskCompleteStats(param);
        // 计算当前页的总积分和总数量
        BigDecimal totalPoints = BigDecimal.ZERO;
        Long totalCount = 0L;
        for (TaskStatsDTO dto : list) {
            if (dto.getTotalPoints() != null) {
                totalPoints = totalPoints.add(dto.getTotalPoints());
            }
            if (dto.getCount() != null) {
                totalCount += dto.getCount();
            }
        }
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        //数据
        result.put("rows", list);
        //总积分
        result.put("totalPoints", totalPoints);
        //总条数
        result.put("totalCount", totalCount);

        return AjaxResult.success(result);
    }

    /**
     * 任务完成统计-总积分
     *
     * @return AjaxResult
     */
    @PostMapping("/getTaskCompleteTotal")
    public AjaxResult getTaskCompleteTotal(@RequestBody GetTaskCompleteStatsVO param) {

        BigDecimal taskCompleteStatsCount = taskInfoService.getTaskCompleteStatsCount(param);
        return AjaxResult.success(taskCompleteStatsCount);
    }

    /**
     * 任务完成统计
     *
     * @return AjaxResult
     */
    @PostMapping("/getTaskCreateStats")
    public AjaxResult getTaskCreateStats(@RequestBody GetTaskCompleteStatsVO param) {
        // 1. 分页查询
        startPage(); // 假设这是项目中的分页启动方法
        List<TaskStatsDTO> list = taskInfoService.getTaskCreateStats(param);

        // 2. 遍历当前页数据，累加总积分和总数量
        BigDecimal totalPoints = BigDecimal.ZERO;
        Long totalCount = 0L;
        for (TaskStatsDTO dto : list) {
            if (dto.getTotalPoints() != null) {
                totalPoints = totalPoints.add(dto.getTotalPoints());
            }
            if (dto.getCount() != null) {
                totalCount += dto.getCount();
            }
        }

        // 3. 构建返回数据（与上一个接口结构一致）
        Map<String, Object> result = new HashMap<>();
        result.put("rows", list);           // 当前页数据列表
        result.put("totalPoints", totalPoints); // 当前页总积分
        result.put("totalCount", totalCount);   // 当前页总数量
        return AjaxResult.success(result);
    }

    /**
     * 任务完成统计-总积分
     *
     * @return AjaxResult
     */
    @PostMapping("/getTaskCreateTotal")
    public AjaxResult getTaskCreateTotal(@RequestBody GetTaskCompleteStatsVO param) {
        BigDecimal taskCreateStatsCount = taskInfoService.getTaskCreateStatsCount(param);
        return AjaxResult.success(taskCreateStatsCount);
    }


    /**
     * 导出任务信息列表
     */
    @GetMapping("/export")
    public AjaxResult export(TaskInfo taskInfo) {
        List<TaskInfo> list = taskInfoService.selectTaskInfoList(taskInfo);
        ExcelUtil<TaskInfo> util = new ExcelUtil<TaskInfo>(TaskInfo.class);
        return util.exportExcel(list, "任务信息主数据");
    }

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

    /**
     * 新增任务信息
     */
    @PostMapping
    @Login
    public AjaxResult add(@RequestBody TaskInfoCreateVO taskInfo) {
        int taskType = taskInfo.getTaskType().intValue();
        //文件调研
        if (taskType == TaskTypeEnum.SURVEY.getCode()) {
            taskInfo.setTargetId(TaskLabelEnum.survey + "-" + taskInfo.getTargetId());
        } else if (taskType == TaskTypeEnum.DRUG.getCode()) {
            taskInfo.setTargetId(TaskLabelEnum.drug + "-" + taskInfo.getTargetId());
        } else if (taskType == TaskTypeEnum.LIVE_LECTURE.getCode()) {
            taskInfo.setTargetId(TaskLabelEnum.live + "-" + taskInfo.getTargetId());
        }

        taskInfo.setApplyTime(new Date());
        return toAjax(taskInfoService.insertTaskInfo(taskInfo));
    }

    /**
     * 修改任务信息
     */
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody TaskInfo taskInfo) {
        if (taskInfo.getId() == null) {
            throw new IllegalArgumentException("任务ID不存在！");
        }
        return toAjax(taskInfoService.updateTaskInfo(taskInfo));
    }

    /**
     * 删除任务信息
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(taskInfoService.deleteTaskInfoByIds(ids));
    }


    @PostMapping("doCreateAudit")
    public void doCreateAudit(@RequestBody TaskCreateAuditReqVO taskCreateAuditReqVO) {
        taskInfoService.doCreateAudit(taskCreateAuditReqVO);
    }


    @PostMapping("dofinishAudit")
    public void dofinishAudit(@RequestBody TaskFinishAuditReqVO taskFinishAuditReqVO) {
        taskInfoService.dofinishAudit(taskFinishAuditReqVO);
    }

    @GetMapping("getTaskCreateAuditInfo")
    public AjaxResult getTaskCreateAuditInfo(@RequestParam Long taskId) {
        return AjaxResult.success(taskInfoService.getTaskCreateAuditInfo(taskId));
    }


    @GetMapping("getTaskFinishAuditInfo")
    public AjaxResult getTaskFinishAuditInfo(@RequestParam Long taskId) {
        return AjaxResult.success(taskInfoService.getTaskFinishAuditInfo(taskId));
    }


    @PutMapping("/spotCheck")
    public AjaxResult updateSpotCheck(@Valid @RequestBody TaskSpotCheckUpdateReqVO req) {

        int rows = taskInfoService.updateSpotCheck(req);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error("更新失败");
    }

    /**
     * 复制创建任务
     */
    @Login
    @PostMapping("/copy/{taskId}")
    public AjaxResult copyTask(@PathVariable Long taskId) {
        Long newTaskId = taskInfoService.copyCreateTask(taskId);
        return AjaxResult.success("复制成功", newTaskId);
    }


    @ApiOperation("获取问卷调查主列表")
    @GetMapping("/getSurveyTaskList")
    public AjaxResult getSurveyTaskList( SurveyTask surveyTask) {
        startPage();
        surveyTask.setDoctorId(Long.valueOf(surveyTask.getUserId()));
        List<SurveyTask> surveyTaskList = iSurveyTaskService.selectSurveyTaskList(surveyTask);

        return AjaxResult.success(getDataTable(surveyTaskList));
    }



    @ApiOperation("获取用药调研主列表")
    @GetMapping("/getDrugResearchList")
    public AjaxResult getDrugResearchList(DrugResearch drugResearch) {
        startPage();
        drugResearch.setStatus(1l);
        List<DrugResearch> drugResearches = iDrugResearchService.selectDrugResearchList(drugResearch);
        return AjaxResult.success(getDataTable(drugResearches));
    }


    @ApiOperation("查询直播列表列表")
    @GetMapping("/liveList")
    public TableDataInfo liveList(LiveBroadcast liveBroadcast) {
        startPage();
        liveBroadcast.setStatus(0l);
        List<LiveBroadcast> list = liveBroadcastService.selectliveList(liveBroadcast);
        return getDataTable(list);
    }

}
