package com.mortals.xhx.module.check.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.CheckStatusEnum;
import com.mortals.xhx.common.code.CheckTypeEnum;
import com.mortals.xhx.common.code.StaffSatusEnum;
import com.mortals.xhx.common.pdu.WeightPdu;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.common.utils.StaffPerformUtil;
import com.mortals.xhx.module.check.model.CheckWindowPerformEntity;
import com.mortals.xhx.module.check.model.vo.StaffCheckSummaryQuery;
import com.mortals.xhx.module.check.model.vo.StaffCheckSummaryVo;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptPerformStatEntity;
import com.mortals.xhx.module.dept.model.DeptPerformStatQuery;
import com.mortals.xhx.module.staff.model.*;
import com.mortals.xhx.module.staff.service.StaffPerformSummaryService;
import com.mortals.xhx.module.staff.service.StaffService;
import com.mortals.xhx.module.window.service.WindowWorkmanPerformDetailService;
import com.mortals.xhx.module.window.service.WindowWorkmanPerformService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.check.dao.CheckWindowWorkmanPerformDao;
import com.mortals.xhx.module.check.model.CheckWindowWorkmanPerformEntity;
import com.mortals.xhx.module.check.service.CheckWindowWorkmanPerformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.mortals.xhx.common.key.ParamKey.SYS_PARAM_WEIGHT;
import static com.mortals.xhx.common.key.RedisKey.KEY_CHECK_SUMMARY_CACHE;

/**
* CheckWindowWorkmanPerformService
* 窗口人员考核汇总核查 service实现
*
* @author zxfei
* @date 2024-01-17
*/
@Service("checkWindowWorkmanPerformService")
@Slf4j
public class CheckWindowWorkmanPerformServiceImpl extends AbstractCRUDServiceImpl<CheckWindowWorkmanPerformDao, CheckWindowWorkmanPerformEntity, Long> implements CheckWindowWorkmanPerformService {

    @Autowired
    private StaffPerformSummaryService staffPerformSummaryService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private WindowWorkmanPerformDetailService windowWorkmanPerformDetailService;

    @Override
    public void examine(CheckWindowWorkmanPerformEntity entity, Context context) throws AppException {
        if (entity.getId() == null) {
            throw new AppException("核查记录ID不能为空");
        }
        CheckWindowWorkmanPerformEntity temp = this.get(entity.getId());
        if (temp == null) {
            throw new AppException("核查记录ID不正确");
        }
        if(CollectionUtils.isNotEmpty(entity.getWindowWorkmanPerformDetailList())){
            windowWorkmanPerformDetailService.update(entity.getWindowWorkmanPerformDetailList(),context);
        }
        if (context != null && context.getUser() != null) {
            IUser user = context.getUser();
            entity.setUpdateUserId(user.getId());
            entity.setManageCheckPerson(user.getRealName());
        }

        entity.setManageCheckTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setCheckStatus(CheckStatusEnum.已处理.getValue()); //处理状态(1.未处理,2.已处理)
        dao.update(entity);
        StaffCheckSummaryQuery query = new StaffCheckSummaryQuery();
        query.setRecordId(temp.getRecordId());
        query.setYear(temp.getYear());
        query.setMonth(temp.getMonth());
        query.setCheckType(CheckTypeEnum.自评绩效.getValue());
        cacheService.lpush(KEY_CHECK_SUMMARY_CACHE, query);
        //summaryCheck(query);
    }

    @Override
    public List<StaffCheckSummaryVo> summaryCheck(StaffCheckSummaryQuery query) throws AppException {
        log.info("汇总自评:"+JSONObject.toJSONString(query));
        if (query.getYear()==null || query.getMonth()==null) {
            Calendar calendar = Calendar.getInstance();
            query.setYear(calendar.get(Calendar.YEAR));
            query.setMonth(calendar.get(Calendar.MONTH) + 1);
        }
        List<StaffCheckSummaryVo> summaryVoList = dao.summaryCheck(query);
        if (CollectionUtils.isNotEmpty(summaryVoList)) {
            String value = paramService.getValueByKey(SYS_PARAM_WEIGHT);
            WeightPdu weightPdu;
            if (ObjectUtils.isEmpty(value)){
                weightPdu = new WeightPdu();
            }else {
                weightPdu = JSONObject.parseObject(value,WeightPdu.class);
            }
            for (StaffCheckSummaryVo vo : summaryVoList) {
                StaffEntity staffEntity = staffService.getCache(vo.getStaffId().toString());
                if(ObjectUtils.isEmpty(staffEntity))continue;
                if(staffEntity.getStatus() == StaffSatusEnum.离职.getValue()) {
                    if(staffEntity.getLeaveDate()!=null){
                        String leaveDateStr = DateUtils.getStrDate(staffEntity.getLeaveDate());
                        String month = vo.getMonth()>9?String.valueOf(vo.getMonth()):"0"+vo.getMonth();
                        String summaryDate = vo.getYear()+"-"+month+"-01";
                        if(DateUtils.StrToDate(leaveDateStr).compareTo(DateUtils.StrToDate(summaryDate)) < 0){
                            //离职日期在统计日期之前不统计
                            continue;
                        }
                    }
                }
                if(staffEntity.getAttendCheck()==0 && staffEntity.getEffectCheck()==0 && staffEntity.getGoworkCheck()==0 && staffEntity.getComplainCheck()==0){
                    continue;
                }
                StaffPerformSummaryEntity staffPerformSummaryEntity = new StaffPerformSummaryEntity();
                staffPerformSummaryEntity.initAttrValue();
                BeanUtils.copyProperties(vo, staffPerformSummaryEntity, BeanUtil.getNullPropertyNames(vo));
                staffPerformSummaryEntity.setComplainScore(vo.getSumScore());
                StaffPerformSummaryQuery summaryQuery = new StaffPerformSummaryQuery();
                summaryQuery.setStaffId(vo.getStaffId());
                summaryQuery.setYear(vo.getYear());
                summaryQuery.setMonth(vo.getMonth());
                StaffPerformSummaryEntity temp = staffPerformSummaryService.selectOne(summaryQuery);
                if (temp != null) {
                    if (temp.getReviewScore() != null) {
                        staffPerformSummaryEntity.setReviewScore(temp.getReviewScore());
                    }
                    if (temp.getAttendScore() != null) {
                        staffPerformSummaryEntity.setAttendScore(temp.getAttendScore());
                    }
                    if (temp.getGoworkScore() != null) {
                        staffPerformSummaryEntity.setGoworkScore(temp.getGoworkScore());
                    }
                    if (temp.getEffectScore() != null) {
                        staffPerformSummaryEntity.setEffectScore(temp.getEffectScore());
                    }
                    if (temp.getOtherScore() != null) {
                        staffPerformSummaryEntity.setOtherScore(temp.getOtherScore());
                    }
                    BigDecimal erro = new BigDecimal(0);
                    erro = erro.add(staffPerformSummaryEntity.getReviewScore());
                    erro = erro.add(staffPerformSummaryEntity.getAttendScore());
                    if(staffPerformSummaryEntity.getComplainScore().compareTo(BigDecimal.ZERO)!=0){
                        BigDecimal complainScoreErro = StaffPerformUtil.SCORE100.subtract(staffPerformSummaryEntity.getComplainScore());
                        erro = erro.add(BigDecimal.ZERO.subtract(complainScoreErro));
                    }
                    erro = erro.add(staffPerformSummaryEntity.getGoworkScore());
                    erro = erro.add(staffPerformSummaryEntity.getEffectScore());
                    staffPerformSummaryEntity.setErrorScore(erro);
                    StaffPerformUtil.computeSummary(staffPerformSummaryEntity,weightPdu,staffEntity);
                    staffPerformSummaryEntity.setId(temp.getId());
                    staffPerformSummaryEntity.setUpdateTime(new Date());
                    staffPerformSummaryService.update(staffPerformSummaryEntity);
                } else {
                    staffPerformSummaryEntity.setAttendScore(BigDecimal.ZERO);
                    staffPerformSummaryEntity.setReviewScore(BigDecimal.ZERO);
                    staffPerformSummaryEntity.setGoworkScore(BigDecimal.ZERO);
                    staffPerformSummaryEntity.setEffectScore(BigDecimal.ZERO);
                    staffPerformSummaryEntity.setComplainScore(BigDecimal.ZERO);
                    staffPerformSummaryEntity.setErrorScore(StaffPerformUtil.SCORE100.subtract(vo.getSumScore()));
                    StaffPerformUtil.computeSummary(staffPerformSummaryEntity,weightPdu,staffEntity);
                    staffPerformSummaryEntity.setCreateUserId(1l);
                    staffPerformSummaryEntity.setCreateTime(new Date());
                    staffPerformSummaryService.save(staffPerformSummaryEntity);
                }
            }
        }

        return summaryVoList;
    }


}