package com.mortals.xhx.daemon.applicationservice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.common.code.CheckTypeEnum;
import com.mortals.xhx.common.utils.StaffPerformUtil;
import com.mortals.xhx.module.check.model.vo.StaffCheckSummaryQuery;
import com.mortals.xhx.module.check.service.*;
import com.mortals.xhx.module.staff.model.StaffPerformSummaryEntity;
import com.mortals.xhx.module.staff.service.StaffPerformSummaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.mortals.xhx.common.key.RedisKey.KEY_CHECK_SUMMARY_CACHE;
import static com.mortals.xhx.common.key.RedisKey.STAFF_PERFORM_SUMMARY;

/***
 * 绩效汇总任务执行
 */
@Component
@Slf4j
public class StaffCheckSummaryService implements IApplicationStartedService {

    protected Boolean stopped = false;

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private CheckAttendRecordService checkAttendRecordService;
    @Autowired
    private CheckEffectRecordService checkEffectRecordService;
    @Autowired
    private CheckGoworkRecordService checkGoworkRecordService;
    @Autowired
    private CheckReviewRecordService checkReviewRecordService;
    @Autowired
    private CheckComplainRecordService checkComplainRecordService;
    @Autowired
    private CheckWindowWorkmanPerformService checkWindowWorkmanPerformService;
    @Autowired
    private CheckOtherRecordService checkOtherRecordService;
    @Autowired
    private StaffPerformSummaryService staffPerformSummaryService;

    @Override
    public void start() {
        Thread sendThread = new Thread(new Runnable() {
            @Override
            public void run() {
                int waitTime = 50;
                while (!stopped) {
                    try {
                        StaffCheckSummaryQuery query = cacheService.brpop(KEY_CHECK_SUMMARY_CACHE,60, StaffCheckSummaryQuery.class);
                        if(!ObjectUtils.isEmpty(query)){
                            if(StringUtils.isNotEmpty(query.getCheckTimeStart())){
                                Date date = DateUtil.parse(query.getCheckTimeStart(),"yyyy-MM-dd");
                                query.setCheckTimeStart(DateUtil.beginOfMonth(date).toDateStr());
                                query.setCheckTimeEnd(DateUtil.endOfMonth(date).toDateStr());
                                query.setYear(DateUtil.year(date));
                                int checkMonth = DateUtil.month(date)+1;
                                query.setMonth(checkMonth);
                                Date now = new Date();
                                int nowMonth = DateUtil.month(now)+1;
                                if(checkMonth==nowMonth){
                                    //汇总当月绩效
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.add(Calendar.DAY_OF_MONTH,-1);
                                    query.setCheckTimeEnd(DateUtils.getStrDate(calendar.getTime()));
                                    query.setCheckTimeStart(DateUtil.beginOfMonth(calendar.getTime()).toDateStr());
                                }

                            }
                            //汇总前初始化绩效避免之前有扣分但被全部撤销的情况
                            Date date = DateUtils.StrToDateTime(query.getCheckTimeStart());
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            int year = calendar.get(Calendar.YEAR);
                            int month = calendar.get(Calendar.MONTH) + 1;
                            StaffPerformSummaryEntity staffPerformSummaryEntity = new StaffPerformSummaryEntity();
                            staffPerformSummaryEntity.setReviewScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setOtherScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setGoworkScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setEffectScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setComplainScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setAttendScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setTotalScore(StaffPerformUtil.SCORE100);
                            //staffPerformSummaryEntity.setAddTotalScore(BigDecimal.ZERO);
                            staffPerformSummaryEntity.setErrorScore(BigDecimal.ZERO);
                            //staffPerformSummaryEntity.setSumScore(StaffPerformUtil.SCORE100);
                            staffPerformSummaryEntity.setUpdateTime(new Date());
                            Map<String,Object> condition = new HashMap<>();
                            condition.put("year",year);
                            condition.put("month",month);
                            if(query.getStaffId()!=null){
                                condition.put("staffId",query.getStaffId());
                            }
                            //staffPerformSummaryService.getDao().update(staffPerformSummaryEntity,condition);
                            staffPerformSummaryService.getDao().updateSumScore(condition);
                            if(query.getCheckType() == CheckTypeEnum.考勤绩效.getValue()){
                                checkAttendRecordService.summaryCheck(query);
                            }
                            if(query.getCheckType() == CheckTypeEnum.效能绩效.getValue()){
                                checkEffectRecordService.summaryCheck(query);
                            }
                            if(query.getCheckType() == CheckTypeEnum.办件绩效.getValue()){
                                checkGoworkRecordService.summaryCheck(query);
                            }
                            if(query.getCheckType() == CheckTypeEnum.评价绩效.getValue()){
                                checkReviewRecordService.summaryCheck(query);
                                checkComplainRecordService.summaryCheck(query);
                            }
                            if(query.getCheckType() == CheckTypeEnum.自评绩效.getValue()){
                                checkWindowWorkmanPerformService.summaryCheck(query);
                            }
                            if(query.getCheckType() == CheckTypeEnum.其它绩效.getValue()){
                                checkOtherRecordService.summaryCheck(query);
                            }
                            if(query.getCheckType()==null){
                                log.info("绩效分数汇总开始:"+ JSONObject.toJSONString(query));
                                checkAttendRecordService.summaryCheck(query);
                                checkEffectRecordService.summaryCheck(query);
                                checkGoworkRecordService.summaryCheck(query);
                                checkReviewRecordService.summaryCheck(query);
                                checkComplainRecordService.summaryCheck(query);
                                checkWindowWorkmanPerformService.summaryCheck(query);
                                checkOtherRecordService.summaryCheck(query);
                                log.info("绩效分数汇总完成");
                                cacheService.set(STAFF_PERFORM_SUMMARY, DateUtils.getCurrStrDateTime());
                            }
                        }


                        try {
                            Thread.sleep(waitTime);
                        } catch (InterruptedException e2) {
                        }

                    } catch (Exception e) {
                      //  log.error("异常", e);

                        try {
                            Thread.sleep(waitTime);
                        } catch (InterruptedException e2) {
                        }
                    }
                }
            }
        });
        sendThread.start();
    }

    @Override
    public void stop() {
        log.info("停止服务..");
        this.stopped = true;
    }

    @Override
    public int getOrder() {
        return 30;
    }

}
