package org.jeecg.modules.appInterface.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.InterfaceConnUtils;
import org.jeecg.modules.appInterface.entity.FbsWorkingStatistics;
import org.jeecg.modules.appInterface.mapper.FbsWorkingStatisticsMapper;
import org.jeecg.modules.appInterface.service.IFbsWorkingStatisticsService;
import org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours;
import org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHoursDescribe;
import org.jeecg.modules.fbsAbnormalWorkingHours.service.IFbsAbnormalWorkingHoursDescribeService;
import org.jeecg.modules.fbsAbnormalWorkingHours.service.IFbsAbnormalWorkingHoursService;
import org.jeecg.modules.fbsWorkshopDispatchList.entity.FbsWorkshopDispatchList;
import org.jeecg.modules.fbsWorkshopDispatchList.service.IFbsWorkshopDispatchListService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 工时统计接口
 * @author： jeecg-boot
 * @date：   2020-10-15
 * @version： V1.0
 */
@Service
@Transactional
public class FbsWorkingStatisticsServiceImpl extends ServiceImpl<FbsWorkingStatisticsMapper, FbsWorkingStatistics> implements IFbsWorkingStatisticsService {

    @Resource
    FbsWorkingStatisticsMapper fbsWorkingStatisticsMapper;

    @Resource
    IFbsWorkshopDispatchListService iFbsWorkshopDispatchListService;

    @Resource
    IFbsAbnormalWorkingHoursService iFbsAbnormalWorkingHoursService;

    @Resource
    IFbsAbnormalWorkingHoursDescribeService iFbsAbnormalWorkingHoursDescribeService;

    @Override
    public Map<String,Object> getByMaterial(String dateString) {
//        List<FbsWorkingStatistics> fbsWorkingStatisticsList=fbsWorkingStatisticsMapper.getByMaterial(dateString);
//        Map<String,Object> map=new HashMap<>();
//        if(fbsWorkingStatisticsList!=null){
//            for(FbsWorkingStatistics fbsWorkingStatistics:fbsWorkingStatisticsList){
//                map.put(fbsWorkingStatistics.getProduct(),fbsWorkingStatistics.getWorkingHours());
//            }
//        }
        Map<String,Object> map=fbsWorkingStatisticsMapper.getByMaterial(dateString);
        Map<String,Object> mapR=new LinkedHashMap<>();
        if(map!=null){

            if(map.get("生产")!=null&&Double.valueOf(String.valueOf(map.get("生产")))>0){
                mapR.put("生产",map.get("生产"));
            }
            if(map.get("其他")!=null&&Double.valueOf(String.valueOf(map.get("其他")))>0){
                mapR.put("其他（5S、会议、培训、研发）",map.get("其他"));

            }
            if(map.get("异常")!=null&&Double.valueOf(String.valueOf(map.get("异常")))>0){
                mapR.put("异常",map.get("异常"));

            }
            if(map.get("仓库")!=null&&Double.valueOf(String.valueOf(map.get("仓库")))>0){
                mapR.put("仓库",map.get("仓库"));

            }
        }

        return mapR;
    }

    @Override
    public List<FbsWorkingStatistics> getWorkingHours() {
        return fbsWorkingStatisticsMapper.getWorkingHours();
    }

    @Override
    public List<FbsWorkshopDispatchList> getWorkingHoursGroupProjectName() {
        return fbsWorkingStatisticsMapper.getWorkingHoursGroupProjectName();
    }

    @Override
    public void updateTime(FbsWorkingStatistics fbsWorkingStatistics) {
        BigDecimal workingHoursBefore=new BigDecimal("0.0");
        workingHoursBefore=workingHoursBefore.add(fbsWorkingStatistics.getWorkingHours());
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        Date firstTime = fbsWorkingStatistics.getFirstTime();
        Date finalTime = fbsWorkingStatistics.getFinalTime();
        long diff = finalTime.getTime() - firstTime.getTime();
        // 计算差多少分钟
        long min = diff / nm;
        BigDecimal aa = new BigDecimal(min).divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP);
        if(aa.doubleValue()>8.0){//超过八小时按照8小时计算
            aa=new BigDecimal("8.0");
        }
        fbsWorkingStatistics.setWorkingHours(aa);//时间差
        fbsWorkingStatisticsMapper.updateById(fbsWorkingStatistics);
        //获取对应的派工单
        FbsWorkshopDispatchList fbsWorkshopDispatchList=iFbsWorkshopDispatchListService.getById(fbsWorkingStatistics.getPkWorkshopDispatchList());
        if(fbsWorkshopDispatchList!=null){
            BigDecimal manHoursCompleted=getDecimalNew(fbsWorkshopDispatchList.getManHoursCompleted());
            BigDecimal manHoursCompletedBefore=manHoursCompleted.subtract(workingHoursBefore);
            BigDecimal manHoursCompletedNow=manHoursCompletedBefore.add(fbsWorkingStatistics.getWorkingHours());
            fbsWorkshopDispatchList.setManHoursCompleted(manHoursCompletedNow.doubleValue()+"");
            iFbsWorkshopDispatchListService.updateById(fbsWorkshopDispatchList);
        }else{
            throw new RuntimeException("找不到对应的派工单！");
        }
    }

    @Override
    public void startOperation(FbsWorkingStatistics fbsWorkingStatistics,FbsWorkshopDispatchList fbsWorkshopDispatchList) {
        if(fbsWorkshopDispatchList!=null){
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            QueryWrapper<FbsAbnormalWorkingHours> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(FbsAbnormalWorkingHours::getDelFlag,"0");
            queryWrapper.eq("date_format(date,'%Y-%m-%d')",formatter.format(date));
            List<FbsAbnormalWorkingHours> fbsAbnormalWorkingHoursList=iFbsAbnormalWorkingHoursService.list(queryWrapper);
            if(fbsAbnormalWorkingHoursList!=null&&fbsAbnormalWorkingHoursList.size()>0){
                //主键id
                String fbsAbnormalWorkingHoursId=fbsAbnormalWorkingHoursList.get(0).getId();
                //生产订单号
                String productionOrderNumberName=fbsWorkshopDispatchList.getProductionOrderNumberName();
                //查询异常子表信息
                QueryWrapper<FbsAbnormalWorkingHoursDescribe> queryWrapper1=new QueryWrapper<>();
                queryWrapper1.lambda().eq(FbsAbnormalWorkingHoursDescribe::getDelFlag,"0");
                queryWrapper1.lambda().eq(FbsAbnormalWorkingHoursDescribe::getAbnormalWorkingHoursId,fbsAbnormalWorkingHoursId);
                queryWrapper1.lambda().eq(FbsAbnormalWorkingHoursDescribe::getProductionOrderNumberName,productionOrderNumberName);
                List<FbsAbnormalWorkingHoursDescribe> fbsAbnormalWorkingHoursDescribeList=iFbsAbnormalWorkingHoursDescribeService.list(queryWrapper1);
                if(fbsAbnormalWorkingHoursDescribeList==null||fbsAbnormalWorkingHoursDescribeList.size()<=0){
                    FbsAbnormalWorkingHoursDescribe fbsAbnormalWorkingHoursDescribe=new FbsAbnormalWorkingHoursDescribe();
                    fbsAbnormalWorkingHoursDescribe.setAbnormalWorkingHoursId(fbsAbnormalWorkingHoursId);
                    fbsAbnormalWorkingHoursDescribe.setProductionOrderNumberName(productionOrderNumberName);
                    fbsAbnormalWorkingHoursDescribe.setProductId(fbsWorkshopDispatchList.getProductId());
                    fbsAbnormalWorkingHoursDescribe.setProduct(fbsWorkshopDispatchList.getProduct());
                    fbsAbnormalWorkingHoursDescribe.setPlannedQuantity(fbsWorkshopDispatchList.getPlannedQuantity());
                    //获取最大排序
                    QueryWrapper<FbsAbnormalWorkingHoursDescribe> queryWrapper2=new QueryWrapper<>();
                    queryWrapper2.lambda().eq(FbsAbnormalWorkingHoursDescribe::getDelFlag,"0");
                    queryWrapper2.lambda().eq(FbsAbnormalWorkingHoursDescribe::getAbnormalWorkingHoursId,fbsAbnormalWorkingHoursId);
                    queryWrapper2.lambda().orderByDesc(FbsAbnormalWorkingHoursDescribe::getSort);
                    List<FbsAbnormalWorkingHoursDescribe> fbsAbnormalWorkingHoursDescribeList2=iFbsAbnormalWorkingHoursDescribeService.list(queryWrapper2);
                    if(fbsAbnormalWorkingHoursDescribeList2!=null&&fbsAbnormalWorkingHoursDescribeList2.size()>0){
                        fbsAbnormalWorkingHoursDescribe.setSort(fbsAbnormalWorkingHoursDescribeList2.get(0).getSort()+1);
                    }else{
                        fbsAbnormalWorkingHoursDescribe.setSort(1);
                    }
                    fbsAbnormalWorkingHoursDescribe.setDelFlag("0");
                    //保存
                    iFbsAbnormalWorkingHoursDescribeService.save(fbsAbnormalWorkingHoursDescribe);
                }

            }

        }
    }

    @Override
    public Boolean cancelWorkReport(FbsWorkingStatistics fbsWorkingStatistics) {
        Boolean result=true;
        //传入参数
        String jsonSting="{\"RUECK\":"+fbsWorkingStatistics.getRueck()+",\"RMZHL\":"+fbsWorkingStatistics.getRmzhl()+",\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00003\",\"GUID\":\"1234567890\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            System.out.println(jsonObjectResults.getJSONArray("RESULTS"));
            //获取报工工时
            BigDecimal workingHoursBefore=new BigDecimal("0.0");
            workingHoursBefore=workingHoursBefore.add(fbsWorkingStatistics.getWorkingHours());
            //获取报工数量
            BigDecimal qualifiedNumber=new BigDecimal("0.0");
            qualifiedNumber =qualifiedNumber.add(getDecimalNew(fbsWorkingStatistics.getQualifiedNumber()));
            //获取对应的派工单
            FbsWorkshopDispatchList fbsWorkshopDispatchList=iFbsWorkshopDispatchListService.getById(fbsWorkingStatistics.getPkWorkshopDispatchList());
            //
            if(fbsWorkshopDispatchList!=null){
                //派工单总工时减去当前取消的报工工时
                BigDecimal manHoursCompleted=getDecimalNew(fbsWorkshopDispatchList.getManHoursCompleted());
                BigDecimal manHoursCompletedBefore=manHoursCompleted.subtract(workingHoursBefore);
                fbsWorkshopDispatchList.setManHoursCompleted(manHoursCompletedBefore.doubleValue()+"");
                //派工单总完成数量减去当前取消的报工完成数量
                BigDecimal latestCompletedQuantity =getDecimalNew(fbsWorkshopDispatchList.getLatestCompletedQuantity());
                latestCompletedQuantity=latestCompletedQuantity.subtract(qualifiedNumber);
                fbsWorkshopDispatchList.setLatestCompletedQuantity(latestCompletedQuantity.doubleValue()+"");
                iFbsWorkshopDispatchListService.updateById(fbsWorkshopDispatchList);
            }
            //删除该报工数据
            FbsWorkingStatistics f=new FbsWorkingStatistics();
            f.setId(fbsWorkingStatistics.getId());
            f.setDelFlag("1");
            f.setIsCancel("2");
            fbsWorkingStatisticsMapper.updateById(f);
            //把当前报工id下的扫码记录的报工状态改为1可再次进行下次报工累加工时
            QueryWrapper<FbsWorkingStatistics> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(FbsWorkingStatistics::getReportId,fbsWorkingStatistics.getId());
            queryWrapper.lambda().eq(FbsWorkingStatistics::getDelFlag,"0");
            FbsWorkingStatistics updateSta=new FbsWorkingStatistics();
            updateSta.setIsCancel("1");
            fbsWorkingStatisticsMapper.update(updateSta,queryWrapper);
        }else{
            result=false;
        }
        return result;
    }

    @Override
    public void updateIsCancelAndReportIdByIds(List<String> list, String reportId) {
        fbsWorkingStatisticsMapper.updateIsCancelAndReportIdByIds(list,reportId);
    }

    @Override
    public IPage<FbsWorkingStatistics> findByPage(IPage<FbsWorkingStatistics> page, QueryWrapper<FbsWorkingStatistics> queryWrapper) {
        return fbsWorkingStatisticsMapper.findByPage(page,queryWrapper);
    }

    @Override
    public IPage<FbsWorkingStatistics> getEfficiencyReport(IPage<FbsWorkingStatistics> page, QueryWrapper<FbsWorkingStatistics> queryWrapper) {
        return fbsWorkingStatisticsMapper.getEfficiencyReport(page,queryWrapper);
    }

    public BigDecimal getDecimalNew(String d){
        if(StringUtils.isEmpty(d)){
            d="0.0";
        }
        BigDecimal decimal= new BigDecimal(d);
        return decimal;
    }
}
