package com.xunmei.core.resumption.controller;

import com.alibaba.fastjson.JSON;
import com.xunmei.common.core.constant.SecurityConstants;
import com.xunmei.common.core.constant.SystemParameterConstant;
import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.common.redis.utils.RedisUtils;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.core.resumption.domain.Resumption;
import com.xunmei.core.resumption.dto.ResumptionTaskDataDto;
import com.xunmei.core.resumption.dto.ResumptionTaskDto;
import com.xunmei.core.resumption.dto.TaskDetailsDto;
import com.xunmei.core.resumption.service.ResumptionBusiness;
import com.xunmei.core.resumption.service.ResumptionService;
import com.xunmei.core.resumption.vo.ResumptionTaskListVo;
import com.xunmei.core.resumption.vo.ResumptionTaskVo;
import com.xunmei.core.resumption.vo.TaskDetailsVo;
import com.xunmei.system.api.RemoteConfigService;
import com.xunmei.system.api.domain.SysConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/api/resumption")
public class ResumptionController {
    @Autowired
    ResumptionBusiness resumptionBusiness;
    @Autowired
    RemoteConfigService remoteConfigService;
    @Autowired
    ResumptionService resumptionService;

    @ApiOperation(value = "所有")
    @PostMapping(value = "/taskList")
    AjaxResult taskList(@RequestBody @Valid final ResumptionTaskDto request) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(request.getDateTime()==null){
            request.setDateTime(sdf.format(new Date()));
        }
        ResumptionTaskVo taskvo = new ResumptionTaskVo();
        Map<String,Object> tasktotal = resumptionBusiness.tasktotal(request);
        taskvo.setTasktotal(tasktotal);
        return AjaxResult.success(taskvo);
    }

    @ApiOperation(value = "详情")
    @PostMapping(value = "/taskDetails")
    AjaxResult taskDetails( @RequestBody @Valid TaskDetailsDto request) throws ParseException {
        System.out.println(JSON.toJSONString(request));
        TaskDetailsVo  detailvo = new TaskDetailsVo();
        List<Map<String,Object>> tasktotal = resumptionBusiness.taskarealistnew(request);
        ResumptionTaskListVo taskObj =resumptionBusiness.getTaskObjByTaskid(request);
        SysConfig systemParame = remoteConfigService.findFirstByCode(SystemParameterConstant.NFC_SCANNING, SecurityConstants.INNER).getData();
        detailvo.setTaskarealist(tasktotal);
        detailvo.setTaskObj(taskObj);
        detailvo.setNfcScaning(systemParame.getValue());
        return AjaxResult.success(detailvo);
    }

    @ApiOperation(value = "跳转编辑")
    @PostMapping(value = "/toTaskDetails")
    AjaxResult toTaskDetails( @RequestBody @Valid final TaskDetailsDto request) throws ParseException {
        TaskDetailsVo  detailvo = new TaskDetailsVo();
        List<Map<String,Object>> tasktotal = resumptionBusiness.toTaskDetails(request);
        ResumptionTaskListVo taskObj =resumptionBusiness.getTaskObjByTaskid(request);
        SysConfig systemParame = remoteConfigService.findFirstByCode(SystemParameterConstant.NFC_SCANNING, SecurityConstants.INNER).getData();
        detailvo.setTaskarealist(tasktotal);
        detailvo.setTaskObj(taskObj);
        detailvo.setNfcScaning(systemParame.getValue());
        return AjaxResult.success(detailvo);
    }

   /* @ApiOperation(value = "保存履职数据")
    @PostMapping(value = "/submitTaskData")
    JsonResponse submitTaskData(final LoginUser user, @RequestBody @Valid final ResumptionTaskDataDto request) throws ParseException {
        int num = this.resumptionBusiness.submitTaskData(request,user);
        return JsonResponse.success(num);
    }*/

    @ApiOperation(value = "保存履职数据")
    @PostMapping(value = "/submitTaskData")
    AjaxResult submitTaskData( @RequestBody @Valid final ResumptionTaskDataDto request) throws ParseException {
        //仅当hashKey不存在时才设置
        Boolean isOk = RedisUtils.hasKey("resumption" + request.getTaskid());
        if(!isOk){
            RedisUtils.setCacheObject("resumption"+request.getTaskid(),request.getTaskid(), Duration.ofMillis(1000*20));
        }
        /*boolean flag =redisService.redisTemplate.opsForHash().putIfAbsent("resumption"+request.getTaskid(),request.getTaskid(),request.getTaskid());//redisTemplate.opsForValue().setIfAbsent("resumption"+request.getTaskid(), "resumption"+request.getTaskid());
        redisService.redisTemplate.expire("resumption"+request.getTaskid(),1000*20, TimeUnit.MILLISECONDS);*/
        if(!isOk){
            throw  new RuntimeException("请勿重复提交");
        }else{
            try {
                //final Resumption resumption = this.resumptionService.find(request.getTaskid());
                final Resumption resumption = resumptionService.findOneByTaskIdAndDate(request);
                if(resumption.getStatus().ordinal()==1||resumption.getStatus().ordinal()==2||resumption.getStatus().ordinal()==5){
                    //重复提交履职数据，先将之前提交的数据删除，然后在重新保存
                    this.resumptionBusiness.deleteTaskData(resumption);
                }
                if(resumption.getStatus().ordinal()==3){
                    throw new RuntimeException("该任务已过期不能完成提交");
                }
                int num = this.resumptionBusiness.submitTaskData(request, SecurityUtils.getLoginUser(),resumption);
                RedisUtils.deleteObject("resumption"+request.getTaskid());
                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
                return AjaxResult.success(num);
            }catch (Exception e){
                RedisUtils.deleteObject("resumption"+request.getTaskid());
                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
                return AjaxResult.error(e.getMessage());
            }finally {
                RedisUtils.deleteObject("resumption"+request.getTaskid());
                //redisService.redisTemplate.opsForHash().delete("resumption"+request.getTaskid(),request.getTaskid());
            }
        }


    }
}
