package com.zjty.tynotes.job.basic.controller;

import com.zjty.tynotes.job.basic.entity.database.Work;
import com.zjty.tynotes.job.basic.entity.request.UpdateCrew;
import com.zjty.tynotes.job.basic.entity.request.UpdateWorkload;
import com.zjty.tynotes.job.basic.entity.request.WorkRo;
import com.zjty.tynotes.job.basic.entity.response.*;
import com.zjty.tynotes.job.basic.repository.WorkRepository;
import com.zjty.tynotes.job.basic.service.ConversionService;
import com.zjty.tynotes.job.basic.service.WorkService;
import com.zjty.tynotes.job.basic.service.WorkTimeService;
import com.zjty.tynotes.job.common.Action;
import com.zjty.tynotes.job.common.constant.WorkStatus;
import com.zjty.tynotes.job.status.service.BusinessTreeManagement;
import com.zjty.tynotes.misc.config.AutoDocument;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

import static org.springframework.http.ResponseEntity.ok;

/**
 * <p>Description : tynotes
 * <p>Date : 2019/4/22 15:02
 * <p>@author : C
 */
@AutoDocument
@Api(tags = "工作记录相关接口", description = "工作记录模块")
@RestController
@RequestMapping("/job/work")
@Slf4j
public class WorkController {

    @Autowired
    WorkService workService;

    @Autowired
    ConversionService conversionService;

    @Autowired
    WorkRepository workRepository;

    @Autowired
    WorkTimeService workTimeService;

    @Autowired
    private BusinessTreeManagement businessTreeManagement;



    @GetMapping(value = "/{workId}")
    @ApiOperation(value = "根据id查询工作.", notes = "在路径中指定要查询的工作id.")
    public ResponseEntity<WorkVo> findById(@PathVariable String workId) {

        return ok(conversionService.workToVo(workService.findById(workId)));

    }


    @PostMapping(value = "/save")
    @ApiOperation(value = "新增工作.", notes = "新增不可在数据中附带id.成功时返回新增数据保存的id.")
    public ResponseEntity<JobResponse> add(@RequestBody WorkRo workRo) {
        String userId = workRo.getUserId();
        String remarks = workRo.getRemarks();
        Work work = workRo.getWork();
        String workId = workService.add(work);
        if (work.getStatus().equals("ongoing")) {
            businessTreeManagement.saveAction(userId, workId, Action.PUBLISH_WORK, new Date(), remarks);
        }else {
            businessTreeManagement.saveAction(userId,workId,Action.SAVE_WORK,new Date(),remarks);
        }
        return ok(new JobResponse(workId));
    }

    @PutMapping(value = "/upDateSave")
    @ApiOperation(value = "把任务从未发布到进行中.", notes = "修改必须在数据中附带id.")
    public ResponseEntity<JobResponse> modify(@RequestBody WorkRo workRo) {
        String userId = workRo.getUserId();
        String remarks = workRo.getRemarks();
        Work newWork = workRo.getWork();
        Work oldWork = workService.findById(newWork.getId());
        String workId = workService.modify(newWork);
        businessTreeManagement.saveAction(userId,workId,Action.SAVE_PUBLISH_WORK,new Date(),remarks);
        return ok(new JobResponse(workId));
    }



    @PutMapping(value = "/delete")
    @ApiOperation(value = "根据id删除工作.", notes = "本次删除选择是否要把个人工作量以及任务工作量纳入统计中.")
    @ApiImplicitParams({
            @ApiImplicitParam(name="workId",value="任务id",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="personalWorkload",value="是否统计个人工作量",dataType="int", paramType = "query",required = true),
            @ApiImplicitParam(name="userId",value="人员id",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="workloadCount",value="是否统计任务工作量",dataType="int", paramType = "query",required = true),
            @ApiImplicitParam(name="msg",value="消息",dataType="String", paramType = "query",required = true)
    })
    public ResponseEntity<JobResponse> delete(@RequestParam String workId,
                                              @RequestParam int personalWorkload,
                                              @RequestParam String userId,
                                              @RequestParam int workloadCount,
                                              @RequestParam String msg) {

        workService.deleteWork(workId,personalWorkload,workloadCount);
        businessTreeManagement.saveAction(userId,workId,Action.DELETE_WORK,new Date(),msg);
        return ok(new JobResponse(workId));
    }

    @PutMapping(value = "/")
    @ApiOperation(value = "修改任务的组员.", notes = "修改任务的组员.")
    public ResponseEntity<JobResponse> update(@RequestBody UpdateCrew updateCrew) {

        workService.updateWorkCrew(updateCrew.getWorkId(),updateCrew.getUsers(),updateCrew.getWorkload());
        businessTreeManagement.saveAction(updateCrew.getUserid(),updateCrew.getWorkId(),Action.UPDATE_WORK_CREW,new Date(),updateCrew.getMsg());
        return ok(new JobResponse(updateCrew.getWorkId()));
    }

    @PutMapping(value = "/upDate/Workload")
    @ApiOperation(value = "修改任务的工作量、考评系数.")
    public ResponseEntity<JobResponse> updateWorkload(@RequestBody UpdateWorkload updateWorkload) {

        workService.updateWorkload(updateWorkload.getWorkId(),updateWorkload.getWorkload(),updateWorkload.getWorkCoefficient());
        businessTreeManagement.saveAction(updateWorkload.getUserId(),updateWorkload.getWorkId(),Action.UPDATE_WORKLOAD,new Date(),updateWorkload.getMsg());

        return ok(new JobResponse(updateWorkload.getWorkId()));
    }


    @PutMapping(value = "/status")
    @ApiOperation(value = "修改工作状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name="workId",value="任务id",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="userId",value="人员id",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="status",value="状态",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="msg",value="消息",dataType="String", paramType = "query",required = true),
            @ApiImplicitParam(name="re",value = "操作1是撤回2是不同",dataType="String", paramType = "query",required = true)
    })
    public ResponseEntity<JobResponse> alterTaskStatus(@RequestParam String workId,
                                                       @RequestParam String userId,
                                                       @RequestParam String status,
                                                       @RequestParam String msg,
                                                       @RequestParam String re) {

        switch (status) {
            case "ongoing":
                Work work=workService.findById(workId);

                if ("1".equals(re)){
                    //撤回
                    workService.alterTaskStatus1(workId,status,userId);
                    businessTreeManagement.saveAction(userId,workId,Action.COMMIT_BACK_WORK,new Date(),msg);
                }else{
                    workService.alterTaskStatus(workId,status,userId);
                    businessTreeManagement.saveAction(userId,workId,Action.BACK_WORK,new Date(),msg);
                    //审核不通过
                }
                break;
            case "audit":
                //执行者提交
                workService.alterTaskStatus(workId, status,userId);
                businessTreeManagement.saveAction(userId, workId, Action.COMMIT_WORK, new Date(), msg);
                break;
            case "review":
                //审核通过
                workService.alterTaskStatus(workId, status,userId);
                businessTreeManagement.saveAction(userId, workId, Action.FINISH_WORK, new Date(), msg);
                break;
            case WorkStatus.FINISHED:
                workService.alterTaskStatus(workId, status,userId);
                businessTreeManagement.saveAction(userId, workId, Action.FINISHED_WORK, new Date(), msg);
                break;
            default:
                log.warn("[job] 修改任务状态传入的参数有误，传入值为：{}", status);
                break;
        }
        return ok(new JobResponse(workId));
    }

    @PutMapping(value = "/select/subtasks/{workId}")
    @ApiOperation(value = "根据任务id是否可以提交任务", notes = "查看是否可以提交.")
    public ResponseEntity<WorkIsNotCommit> selectSubtasks(@PathVariable("workId") String workId) {

        return ok(workService.findBySuperoirId(workId));
    }

    @PutMapping(value = "/select/workload/{workId}")
    @ApiOperation(value = "根据任务id查看剩余工作量", notes = "查看任务工作量.")
    public ResponseEntity selectCount(@PathVariable("workId") String workId) {

        return ok(workService.findBySuperoirIdCount(workId));
    }

    @GetMapping(value = "/select/work/{userId}")
    @ApiOperation(value = "根据用户id查看其部门所有的任务", notes = "部门所有的任务")
    public ResponseEntity<List<WorkMpping>> selectWorkUserId(@PathVariable("userId") String userId) {

        return ok(workService.selectUserIdsWork(userId));
    }

    @GetMapping(value = "/select/work/workId/{workId}")
    @ApiOperation(value = "根据任务id查询这个任务所在任务组里面",notes = "查看任务的所有相关任务")
    public ResponseEntity<WorkMpping> selectWorkMappingWorkId(@PathVariable("workId") String workId){

        return ok(workService.selectWorkMapperWorkId(workId));
    }

    @GetMapping(value = "/select/back/{workId}")
    @ApiOperation(value = "根据任务id查询这个任务是否被退回过",notes = "查看任务是否为被退回")
    public ResponseEntity<BackResponse> selectBackWorkWorkId(@PathVariable("workId") String workId){
               if (workTimeService.selectWorkTime(workId).size()>=2){
                   return ok(new BackResponse(true));
               }else {
                   return ok(new BackResponse(false));
               }
    }

    @GetMapping(value = "/select/WorkOverTime/{userId}")
    @ApiOperation(value = "根据人员id查询所有正在进行中且组长是人员id的任务",notes = "查看进行中的任务")
    public ResponseEntity<List<WorkOverTime>> selectWorkOverTimeWorkId(@PathVariable("userId") String userId){

        return ResponseEntity.ok(workService.selectWorkToWorkOverTime(userId));
    }

//
//    @GetMapping(value = "/select/WorkOverTime/{userId}")
//    @ApiOperation(value = "转发任务接口",notes = "转发任务")
//    public ResponseEntity<> selectWorkOverTimeWorkId(@PathVariable("userId") String userId){
//
//
//        String workId = workService.add(work);
//        businessTreeManagement.saveAction(userId, workId, Action.PUBLISH_WORK, new Date(), remarks);
//        return ResponseEntity.ok(workService.selectWorkToWorkOverTime(userId));
//    }
}
