package com.mortals.xhx.module.staff.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.param.service.ParamService;
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.staff.dao.StaffPerformSummaryEditDao;
import com.mortals.xhx.module.staff.model.*;
import com.mortals.xhx.module.staff.service.StaffPerformSummaryEditService;
import com.mortals.xhx.module.staff.service.StaffPerformSummaryService;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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

/**
* StaffPerformSummaryEditService
* 员工绩效统计 service实现
*
* @author zxfei
* @date 2025-04-10
*/
@Service("staffPerformSummaryEditService")
@Slf4j
public class StaffPerformSummaryEditServiceImpl extends AbstractCRUDServiceImpl<StaffPerformSummaryEditDao, StaffPerformSummaryEditEntity, Long> implements StaffPerformSummaryEditService {
    @Autowired
    private StaffService staffService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private StaffPerformSummaryService staffPerformSummaryService;

    @Override
    protected StaffPerformSummaryEditEntity findBefore(StaffPerformSummaryEditEntity params, PageInfo pageInfo, Context context) throws AppException {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        if(params.getYear()==null){
            params.setYear(year);
        }
        if(params.getMonth()==null){
            params.setMonth(month);
        }
        return params;
    }

    @Override
    public StaffPerformSummaryEditEntity get(Long key, Context context) throws AppException {
        StaffPerformSummaryEditEntity entity =  this.dao.get(key);
        String value = paramService.getValueByKey(SYS_PARAM_WEIGHT);
        WeightPdu weightPdu;
        if (ObjectUtils.isEmpty(value)){
            weightPdu = new WeightPdu();
        }else {
            weightPdu = JSONObject.parseObject(value,WeightPdu.class);
        }
        computeSummary(entity,weightPdu);
        if(StringUtils.isNotEmpty(entity.getRemarkAdd())){
            List<JSONObject> jList = JSONArray.parseArray(entity.getRemarkAdd(),JSONObject.class);
            String desc = "";
            for (JSONObject jsonObject:jList){
                desc+=jsonObject.getString("name")+"("+jsonObject.getString("score")+");";
            }
            entity.setRemarkAddDesc(desc);
        }
        return entity;
    }

    @Override
    protected void findAfter(StaffPerformSummaryEditEntity params, PageInfo pageInfo, Context context, List<StaffPerformSummaryEditEntity> list) throws AppException {
        if(CollectionUtils.isNotEmpty(list)){
            String value = paramService.getValueByKey(SYS_PARAM_WEIGHT);
            WeightPdu weightPdu;
            if (ObjectUtils.isEmpty(value)){
                weightPdu = new WeightPdu();
            }else {
                weightPdu = JSONObject.parseObject(value,WeightPdu.class);
            }
            for(StaffPerformSummaryEditEntity item:list) {
                StaffEntity staffEntity = staffService.getCache(item.getStaffId().toString());
                if(staffEntity!=null){
                    item.setWorkNum(staffEntity.getWorkNum());
                    item.setPhoneNumber(staffEntity.getPhoneNumber());
                }
                computeSummary(item,weightPdu);
                if(StringUtils.isNotEmpty(item.getRemarkAdd())){
                    List<JSONObject> jList = JSONArray.parseArray(item.getRemarkAdd(),JSONObject.class);
                    String desc = "";
                    for (JSONObject jsonObject:jList){
                        desc+=jsonObject.getString("name")+"("+jsonObject.getString("score")+");";
                    }
                    item.setRemarkAddDesc(desc);
                }
            }
        }
    }

    private void computeSummary(StaffPerformSummaryEditEntity StaffPerformSummaryEditEntity, WeightPdu weightPdu){

        BigDecimal reviewScore = weightPdu.reviewWeight().add(StaffPerformSummaryEditEntity.getReviewScore());  //评价
        if(reviewScore.compareTo(BigDecimal.ZERO)<0){
            reviewScore = BigDecimal.ZERO;
        }
        StaffPerformSummaryEditEntity.setReviewScore(reviewScore.setScale(2,BigDecimal.ROUND_DOWN));
        BigDecimal attendScore = weightPdu.attendWeight().add(StaffPerformSummaryEditEntity.getAttendScore()); //考勤
        if(attendScore.compareTo(BigDecimal.ZERO)<0){
            attendScore = BigDecimal.ZERO;
        }
        StaffPerformSummaryEditEntity.setAttendScore(attendScore.setScale(2,BigDecimal.ROUND_DOWN));
        BigDecimal complainScore = StaffPerformSummaryEditEntity.getComplainScore();  //自评不用加100
        if(complainScore.compareTo(BigDecimal.ZERO)==0){
            complainScore = StaffPerformUtil.SCORE100;
        }
        complainScore = complainScore.multiply(weightPdu.selfWeight());
        StaffPerformSummaryEditEntity.setComplainScore(complainScore.setScale(2,BigDecimal.ROUND_DOWN));
        BigDecimal goworkScore = weightPdu.goworkWeight().add(StaffPerformSummaryEditEntity.getGoworkScore());  //办件
        if(goworkScore.compareTo(BigDecimal.ZERO)<0){
            goworkScore = BigDecimal.ZERO;
        }
        StaffPerformSummaryEditEntity.setGoworkScore(goworkScore.setScale(2,BigDecimal.ROUND_DOWN));
        BigDecimal effectScore = weightPdu.effectWeight().add(StaffPerformSummaryEditEntity.getEffectScore());  //效能
        if(effectScore.compareTo(BigDecimal.ZERO)<0){
            effectScore = BigDecimal.ZERO;
        }
        StaffPerformSummaryEditEntity.setEffectScore(effectScore.setScale(2,BigDecimal.ROUND_DOWN));

    }


    @Override
    public void syncStaffPerformSummary(int year, int month, Long staffId) {
        List<StaffPerformSummaryEntity> list = staffPerformSummaryService.find(new StaffPerformSummaryQuery().year(year).month(month).staffId(staffId));
        List<StaffPerformSummaryEditEntity> editList = this.find(new StaffPerformSummaryEditQuery().year(year).month(month).staffId(staffId));
        //Map<String,StaffPerformSummaryEntity> map = list.stream().collect(Collectors.toMap(item->item.getYear()+"_"+item.getMonth()+"_"+item.getStaffId(),Function.identity()));
        Map<String,StaffPerformSummaryEditEntity> editMap = editList.stream().collect(Collectors.toMap(item->item.getYear()+"_"+item.getMonth()+"_"+item.getStaffId(),Function.identity()));
        List<StaffPerformSummaryEditEntity> addList = new ArrayList<>();
        List<StaffPerformSummaryEditEntity> updateList = new ArrayList<>();
        for(StaffPerformSummaryEntity item:list){
            String key = item.getYear()+"_"+item.getMonth()+"_"+item.getStaffId();
            if(editMap.containsKey(key)){
                StaffPerformSummaryEditEntity editEntity = editMap.get(key);
                item.setId(editEntity.getId());
                item.setAuditLevel(editEntity.getAuditLevel());
                item.setRecommend(editEntity.getRecommend());
                item.setRemarkAdd(editEntity.getRemarkAdd());
                item.setRemark(editEntity.getRemark());
                item.setAddTotalScore(editEntity.getAddTotalScore());
                if(editEntity.getDataType()==1){
                    BeanUtils.copyProperties(item, editEntity, BeanUtil.getNullPropertyNames(item));
                    if(editEntity.getAddTotalScore()!=null){
                        editEntity.setSumScore(editEntity.getTotalScore().add(editEntity.getAddTotalScore()));
                    }
                    updateList.add(editEntity);
                }
            }else {
                StaffPerformSummaryEditEntity editEntity = new StaffPerformSummaryEditEntity();
                BeanUtils.copyProperties(item, editEntity, BeanUtil.getNullPropertyNames(item));
                editEntity.setId(null);
                editEntity.setDataType(1);
                editEntity.setCreateTime(new Date());
                addList.add(editEntity);
            }
        }
        if(CollectionUtils.isNotEmpty(updateList)){
            this.update(updateList);
        }
        if(CollectionUtils.isNotEmpty(addList)){
            this.save(addList);
        }
    }
}