package com.ruoyi.web.controller.zb;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.other.BsCommonExample;
import com.ruoyi.system.domain.zb.ZbAutoRecord;
import com.ruoyi.system.domain.zb.ZbAutoRecordExample;
import com.ruoyi.system.domain.zb.ZbReportRecord;
import com.ruoyi.system.domain.zb.ZbWeekReportExample;
import com.ruoyi.system.domain.zb.request.WeekReportSaveRequest;
import com.ruoyi.system.domain.zb.vo.ReportRecordItem;
import com.ruoyi.system.domain.zb.vo.WeekReportPageItem;
import com.ruoyi.system.mapper.other.BsCommonMapper;
import com.ruoyi.system.mapper.zb.ZbAutoRecordMapper;
import com.ruoyi.system.mapper.zb.ZbWeekReportMapper;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.zb.ReportRecordService;
import com.ruoyi.system.service.zb.WeekReportService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * * Author: brenda
 * * 2025/1/10
 **/
@Api(tags = "周报")
@RestController
@RequestMapping("/api/zb/report")
public class WeekReportController extends BaseController {

    @Autowired
    private WeekReportService weekReportService;
    @Autowired
    private ZbWeekReportMapper weekReportMapper;
    @Autowired
    private ReportRecordService reportRecordService;
    @Autowired
    private ZbAutoRecordMapper autoRecordMapper;
    @Autowired
    private BsCommonMapper bsCommonMapper;
    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/save")
    public AjaxResult save(@RequestBody WeekReportSaveRequest request){
        request.setCreateTime(new Date());
        request.setCreateUser(getUserId());
        if(request.getPublishFlag() == 1){
            ZbWeekReportExample example = new ZbWeekReportExample();
            ZbWeekReportExample.Criteria criteria = example.createCriteria();
            criteria.andValidEqualTo((byte)1);
            criteria.andEndDateGreaterThanOrEqualTo(request.getStartDate());
            if(weekReportMapper.countByExample(example) > 0){
                return AjaxResult.error("开始日期已经存在于其余周报填报时间中！请重新选择！");
            }
        }
        weekReportService.save(request);
        return AjaxResult.success();
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody WeekReportSaveRequest request){
        request.setUpdateTime(new Date());
        request.setUpdateUser(getUserId());
        if(request.getPublishFlag() == 1){
            ZbWeekReportExample example = new ZbWeekReportExample();
            ZbWeekReportExample.Criteria criteria = example.createCriteria();
            criteria.andValidEqualTo((byte)1);
            criteria.andIdNotEqualTo(request.getId());
            criteria.andEndDateGreaterThanOrEqualTo(request.getStartDate());
            if(weekReportMapper.countByExample(example) > 0){
                return AjaxResult.error("开始日期已经存在于其余周报填报时间中！请重新选择！");
            }
        }
        weekReportService.update(request);
        return AjaxResult.success();
    }

    /**
     * 取消自动发布
     * @return
     */
    @GetMapping("/cancelAuto")
    public AjaxResult cancelAuto(){
        weekReportService.cancelAuto();
        return AjaxResult.success();
    }

    /**
     * 当前是否有自动发布的周报任务
     * @return
     */
    @GetMapping("/hasPublished")
    public AjaxResult hasPublished(){
        ZbAutoRecordExample example = new ZbAutoRecordExample();
        ZbAutoRecordExample.Criteria criteria = example.createCriteria();
        criteria.andValidEqualTo((byte)1);
        if(autoRecordMapper.countByExample(example) > 0){
           return AjaxResult.success(true);
        }
        return AjaxResult.success(false);
    }

    /**
     * 最新的自动发布的周报任务详情
     * @return
     */
    @GetMapping("/latestDetail")
    public AjaxResult latestDetail(){
        ZbAutoRecordExample example = new ZbAutoRecordExample();
        ZbAutoRecordExample.Criteria criteria = example.createCriteria();
        criteria.andValidEqualTo((byte)1);
        List<ZbAutoRecord> autoRecordList = autoRecordMapper.selectByExample(example);
        ZbAutoRecord autoRecord = autoRecordList.get(0);
        return AjaxResult.success(weekReportService.simpleDetail(autoRecord.getLastReportId()));
    }

    /**
     * 简易详情
     * @return
     */
    @GetMapping("/simpleDetail/{id}")
    public AjaxResult simpleDetail(@PathVariable("id")String id){
        return AjaxResult.success(weekReportService.simpleDetail(id));
    }

    /**
     * 详细的带用户完成情况的详情
     * @return
     */
    @GetMapping("/detail/{id}")
    public AjaxResult detail(@PathVariable("id")String id){
        return AjaxResult.success(weekReportService.reportWithUserDetail(id, getUserId()));
    }

    /**
     * 用户完成情况分页
     * @param pageNum
     * @param pageSize
     * @param recordId
     * @return
     */
    @GetMapping("/user/page")
    public AjaxResult page(@RequestParam("pageNum") int pageNum,
                           @RequestParam("pageSize") int pageSize,
                           @RequestParam(value = "recordId")String recordId){
        List<String> canSeeList = weekReportService.canSeeUserList(getUserId(), recordId);
        if(CollectionUtils.isEmpty(canSeeList)){
            return AjaxResult.success(new PageInfo<>(new ArrayList<>()));
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<ReportRecordItem> pageInfo = reportRecordService.pageFinishedUser(recordId, canSeeList);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 周报分页
     * @param pageNum
     * @param pageSize
     * @param title
     * @param year
     * @param week
     * @return
     */
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") int pageNum,
                           @RequestParam("pageSize") int pageSize,
                           @RequestParam(value = "title", required = false)String title,
                           @RequestParam(value = "year", required = false)String year,
                           @RequestParam(value = "week", required = false)String week){
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<WeekReportPageItem> pageInfo = weekReportService.page(title, year, week, getUserId());
        return AjaxResult.success(pageInfo);
    }

    /**
     * 完成情况
     * @param reportId
     * @return
     */
    @GetMapping("/finishCondition/{reportId}")
    public AjaxResult finishedCondition(@PathVariable("reportId")String reportId){
        return AjaxResult.success(reportRecordService.finishCondition(reportId, getUserId()));
    }

    /**
     * 填写周报
     * @param request
     * @return
     */
    @PostMapping("/record/save")
    public AjaxResult save(@RequestBody ZbReportRecord request){
        if(StringUtils.isBlank(request.getId())){
            request.setSubmitTime(new Date());
        }
        request.setUserId(getUserId());
        SysUser sysUser = sysUserService.selectUserById(getUserId());
        request.setDepId(sysUser.getDeptId().toString());
        reportRecordService.save(request);
        return AjaxResult.success();
    }

    /**
     * app端分页列表
     * @param pageNum
     * @param pageSize
     * @param title
     * @return
     */
    @GetMapping("/app/page")
    public AjaxResult specialWorkPage(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
                                      @RequestParam(value = "title", required = false)String title){
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<WeekReportPageItem> pageInfo = weekReportService.pageForApp(getUserId(), title, pageNum, pageSize);
        return AjaxResult.success(pageInfo);
    }

    /**
     * APP周报详情
     * @return
     */
    @GetMapping("/app/detail/{id}")
    public AjaxResult appDetail(@PathVariable("id")String id){
        return AjaxResult.success(reportRecordService.weekReportDetail(id, getUserId()));
    }

    /**
     * APP周报可修改/填报信息
     * @return
     */
    @GetMapping("/app/detail/permission/{id}")
    public AjaxResult appDetailOtherInfo(@PathVariable("id")String id){
        return AjaxResult.success(reportRecordService.appReportDetail(getLoginUser().getUser(), id));
    }

    /**
     * 周报字典
     * @return
     */
    @GetMapping("/reportDictList")
    public AjaxResult userTree(){
        BsCommonExample bsCommonExample = new BsCommonExample();
        BsCommonExample.Criteria criteria = bsCommonExample.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andCodeLike("week_report_summary");
        criteria.andParentIdIsNull();
        List<BsCommon> commonList = bsCommonMapper.selectByExample(bsCommonExample);
        return AjaxResult.success(commonList.get(0));
    }
}
