package com.qy.worksheetsystem.controller;

import com.google.common.collect.Maps;
import com.qy.worksheetsystem.model.MessageResult;

import com.qy.worksheetsystem.model.MessageResultV2;
import com.qy.worksheetsystem.model.entity.JobBooking;
import com.qy.worksheetsystem.service.PersonService;
import com.qy.worksheetsystem.service.PersonWorkService;
import com.qy.worksheetsystem.service.WorkCalendarService;
import com.qy.worksheetsystem.util.DateUtil;
import com.qy.worksheetsystem.util.JWTUtil;
import com.qy.worksheetsystem.vo.InsertJobWorkingVO;
import com.qy.worksheetsystem.vo.WorkHoursReport;
import com.qy.worksheetsystem.vo.WorkHoursReportEntry;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/work/personwork")
@Api(value = "工时填报",tags="工时填报")
public class PersonWorkController {
    @Autowired
    private PersonWorkService personWorkService;
    @Autowired
    private PersonService personService;

    @ApiOperation(value = "获取可填报日期的已填报小时数", notes = "获取可填报日期的已填报小时数，判断每天填报是否超8小时")
    @RequestMapping(value = "/getAvailableDateInfo", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
    })
    public MessageResult getAvailableDateInfo(@RequestHeader("token") String token, String beginTime,String endTime) {
        String number = JWTUtil.getCacheNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        int isValid = DateUtil.isValidDate(beginTime, endTime);

        if (isValid== 1) {
            return MessageResultV2.error("请输入正确的日期时间，日期格式例如2022-01-01");
        }else if (isValid== 2){
            return MessageResultV2.error("开始时间不能大于结束时间");
        }
        MessageResultV2 result = MessageResultV2.success();
        result.setData(personWorkService.getAvailableDateInfo(number,beginTime,endTime));
        return result;
    }

    @ApiOperation(value = "报工新增", notes = "报工新增")
    @RequestMapping(value = "/insertWork", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
    })
    public MessageResultV2 insertWork(@RequestHeader("token") String token, @RequestBody WorkHoursReport jobWork) {
        try {
            String number = JWTUtil.getNumber(token);
            if (StringUtils.isEmpty(number)) {
                return MessageResultV2.error("token异常");
            }
            Map<String, Object> map = new HashMap<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String beginTime = jobWork.getBeginTime();
            String endTime = jobWork.getEndTime();
            Integer Hours = 0;
            //获取员工信息
            Map<String, String> person = personService.getPersonByJobNo(number);
            Date beginDate = format.parse(beginTime);
            Date endDate = format.parse(endTime);
            Date enterDate = format.parse(person.get("enterDate"));
            if (enterDate.compareTo(beginDate) > 0) {
                return MessageResultV2.error("不能填报，入职日期之前的日期！");
            }
            map.put("jobWork",jobWork);
            map.put("person",person);
            map.put("beginDate",beginDate);
            map.put("endDate",endDate);
            map.put("beginDateStr",beginTime);
            map.put("endDateStr",endTime);
            //校验报工日期是否超过8小时
            List<Map<String,Object>> availableList = personWorkService.getAvailableDateInfo(number,beginTime,endTime);
            Map<String,Map<String,Object>> availableMap = Maps.newHashMap();
            for(Map<String,Object> objectMap : availableList){
                String date = (String) objectMap.get("date");
                availableMap.put(date,objectMap);
            }
            map.put("availableMap",availableMap);
            //开始天
            int begin = Integer.parseInt(beginTime.substring(8, 10));
            //结束天
            int end = Integer.parseInt(endTime.substring(8, 10));
            //年月
            String yearMonth = beginTime.substring(0, 8);

            map.put("begin",begin);
            map.put("end",end);
            map.put("yearMonth",yearMonth);
            StringBuilder errMsg = new StringBuilder();
            for (WorkHoursReportEntry jobWorkEntry : jobWork.getEntries()){
                String workingHours = jobWorkEntry.getWorkingHours();
                BigDecimal Hour = new BigDecimal(workingHours);
                Hours += Hour.intValue();
                String projectId = jobWorkEntry.getProjectId();
                if (StringUtils.isBlank(projectId)) {
                    return MessageResultV2.error("项目id为空");
                }
                for (int i = begin; i <= end; i++) {
                    String iday = "01";
                    if (i < 10) {
                        iday = "0" + i;
                    } else {
                        iday = i + "";
                    }
                    String reportDate = yearMonth + iday;
                    Map<String,Object> avMap = availableMap.get(reportDate);
                    BigDecimal availableWorkHous = (BigDecimal) avMap.get("availableWorkHours");
                    BigDecimal workHours = (BigDecimal) avMap.get("workHours");
                    if(availableWorkHous.compareTo(Hour)<0){
                        errMsg.append("项目："+jobWorkEntry.getProjectName()+",日期："+reportDate+",已填报："+workHours.toPlainString()+"小时,不能再填报" + Hour.toPlainString() + "小时,一天的总填报小时数需小于等于8小时!");
                        errMsg.append("\r\n");
                    }
                }
            }
            if (Hours > 8) {
                return MessageResultV2.error("报工小时数不能大于8小时");
            }
            if (errMsg.length() > 0) {
                MessageResultV2 result = new MessageResultV2();
                result.setCode(400);
                result.setMsg(errMsg.toString());
                return result;
            }
            Map<String,Object> objectMap = personWorkService.insertWork(map);
            MessageResultV2 resultV2 = MessageResultV2.success();
            resultV2.setData(objectMap);
            return resultV2;
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return MessageResultV2.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取员工报工列表", notes = "获取员工报工列表")
    @RequestMapping(value = "/getPersonWorkList", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "true已提交，false待提交", required = false, paramType = "query", dataType = "Boolean"),
    })
    public MessageResult getPersonWorkList(@RequestHeader("token") String token, String beginTime,String endTime,Boolean state) {
        String number = JWTUtil.getNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        List<Map<String,Object>> list = personWorkService.getPersonWorkList(number,beginTime,endTime,state);
        MessageResult result=MessageResult.success();
        result.add("datalist",list);
        return result;
    }
    @ApiOperation(value = "获取员工汇总信息", notes = "获取员工汇总信息")
    @RequestMapping(value = "/getPersonWorkSumInfo", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "beginTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "开始时间yyyy-MM-dd", required = true, paramType = "query", dataType = "String"),
    })
    public MessageResult getPersonWorkSumInfo(@RequestHeader("token") String token, String beginTime,String endTime,Boolean state) {
        String number = JWTUtil.getCacheNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        List<Map<String,Object>> list = personWorkService.getPersonWorkSumInfo(number,beginTime,endTime,state);
        MessageResult result=MessageResult.success();
        result.add("datalist",list);
        return result;
    }
    @ApiOperation(value = "更新", notes = "更新")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
    })
    public MessageResult update(@RequestHeader("token") String token, @RequestBody WorkHoursReport jobWork) {
        String number = JWTUtil.getCacheNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        //List<Map<String,Object>> list = personWorkService.getPersonWorkInfoById(number,id);
        MessageResultV2 result=MessageResultV2.success();
        //result.setData(list);
        return result;
    }
    @ApiOperation(value = "删除报工", notes = "删除报工")
    @RequestMapping(value = "/deleteWork", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "报工id", required = true, paramType = "query", dataType = "String"),
    })
    public MessageResult deleteWork(@RequestHeader("token") String token,  String id) {
        String number = JWTUtil.getCacheNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
         int i = personWorkService.deleteWork(number,id);
        MessageResultV2 result=MessageResultV2.success();
        //result.setData(list);
        return result;
    }

    @ApiOperation(value = "获取员工报工明细", notes = "获取员工报工明细")
    @RequestMapping(value = "/getPersonWorkInfoById", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "报工id", required = true, paramType = "query", dataType = "String"),
    })
    public MessageResult getPersonWorkInfoById(@RequestHeader("token") String token, String id) {
        String number = JWTUtil.getNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        JobBooking list = personWorkService.getPersonWorkInfoById(number,id);
        MessageResultV2 result=MessageResultV2.success();
        result.setData(list);
        return result;
    }

    @ApiOperation(value = "提交工作流", notes = "提交工作流")
    @RequestMapping(value = "/subWork", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "报工id", required = true, paramType = "query", dataType = "String"),
    })
    public MessageResult submitWork(@RequestHeader("token") String token, String id) {
        String number = JWTUtil.getCacheNumber(token);
        if (StringUtils.isEmpty(number)) {
            return MessageResult.error("token异常");
        }
        int i = personWorkService.submitWork(number,id);
        MessageResultV2 result=MessageResultV2.success();
        // result.setData(list);
        return result;
    }

}