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

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.busiz.h5.req.EffectSaveReq;
import com.mortals.xhx.busiz.h5.rsp.ApiResp;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.check.model.CheckEffectRecordEntity;
import com.mortals.xhx.module.check.model.CheckEffectRecordQuery;
import com.mortals.xhx.module.check.service.CheckEffectRecordService;
import com.mortals.xhx.module.perform.dao.PerformEffectRecordDao;
import com.mortals.xhx.module.perform.model.*;
import com.mortals.xhx.module.perform.service.*;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;


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

/**
 * PerformEffectRecordService
 * 效能绩效记录信息 service实现
 *
 * @author zxfei
 * @date 2023-07-11
 */
@Service("performEffectRecordService")
@Slf4j
public class PerformEffectRecordServiceImpl extends AbstractCRUDServiceImpl<PerformEffectRecordDao, PerformEffectRecordEntity, Long> implements PerformEffectRecordService {

    @Autowired
    private CheckEffectRecordService checkEffectRecordService;
    @Autowired
    private PerformRulesCategoryService categoryService;
    @Autowired
    private PerformRulesService rulesService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private PerformStaffConfService performStaffConfService;
    @Autowired
    private PerformStaffConfDetailService performStaffConfDetailService;
    @Autowired
    private PerformErrorRecordService errorRecordService;

    @Override
    protected void saveBefore(PerformEffectRecordEntity entity, Context context) throws AppException {
        updateStaffRuleNames(entity, context);
    }

    @Override
    protected void updateBefore(PerformEffectRecordEntity entity, Context context) throws AppException {
        updateStaffRuleNames(entity, context);
    }


    private void updateStaffRuleNames(PerformEffectRecordEntity entity, Context context) {
        if (!ObjectUtils.isEmpty(entity.getRuleId())) {
            PerformRulesEntity rulesEntity = rulesService.getCache(entity.getRuleId().toString());
            entity.setRuleName(rulesEntity.getName());
            entity.setSubAddType(rulesEntity == null ? 1 : rulesEntity.getSubAddType());
        }
        if (!ObjectUtils.isEmpty(entity.getStaffId())) {
            StaffEntity staffCache = staffService.getCache(entity.getStaffId().toString());
            entity.setStaffName(staffCache == null ? "" : staffCache.getName());
            entity.setDeptName(staffCache == null ? "" : staffCache.getDeptName());
            entity.setSalaId(staffCache == null ? null : staffCache.getSalaId());
            entity.setSalaName(staffCache == null ? "" : staffCache.getSalaName());
        }
        entity.setDeductTime(new Date());
        if (ObjectUtils.isEmpty(entity.getDeductPerson())) {
            entity.setDeductPerson(context == null ? "" : context.getUser() == null ? "" : context.getUser().getRealName());
        }
    }

    @Override
    protected void saveAfter(PerformEffectRecordEntity entity, Context context) throws AppException {
        CheckEffectRecordEntity checkEffectRecordEntity = new CheckEffectRecordEntity();
        checkEffectRecordEntity.initAttrValue();
        BeanUtils.copyProperties(entity, checkEffectRecordEntity, BeanUtil.getNullPropertyNames(entity));
        checkEffectRecordEntity.setId(null);
        checkEffectRecordEntity.setRecordId(entity.getId());
        if (performStaffConfService.checkRules(entity.getStaffId(), entity.getDeptId(), entity.getRuleId())) {
            checkEffectRecordEntity.setCheckStatus(CheckStatusEnum.已处理.getValue());
            if (checkEffectRecordEntity.getSubAddType() == SubAddTypeEnum.增加.getValue()) {
                checkEffectRecordEntity.setCheckResult(CheckResultAddEnum.核查加分.getValue());
            } else {
                checkEffectRecordEntity.setCheckResult(CheckResultSubEnum.核查扣分.getValue());
            }
            checkEffectRecordEntity.setUpdateTime(new Date());
        } else {
            checkEffectRecordEntity.setCheckStatus(CheckStatusEnum.未处理.getValue());      //非自动扣分相设置为未处理
        }
        checkEffectRecordService.save(checkEffectRecordEntity, context);
    }

    @Override
    public void updateProcessStatus(Long id, Integer status) throws AppException {
        if (id == null) {
            throw new AppException("效能绩效记录Id不能为空");
        }
        PerformEffectRecordEntity entity = this.get(id);
        if (entity == null) {
            throw new AppException("无效的效能绩效记录Id");
        }
        if (status == null) {
            status = 1; //处理状态(1.未核查,2.已核查)
        }
        PerformEffectRecordEntity update = new PerformEffectRecordEntity();
        update.setId(id);
        update.setProcessStatus(status);
        update.setUpdateTime(new Date());
        dao.update(update);
    }

    @Override
    public void syncEffectRecord(PerformEffectRecordQuery query, Context context) {
        log.info("同步效能绩效记录开始");
        String phpInUrl = GlobalSysInfo.getParamValue(SYS_PARAM_XNJC_URL, "http://127.0.0.1:11039/zwfw_api_xnjc");
        String xnjcUrl = phpInUrl + "/api/kq_alert/leaveList";
        Map<String, Object> params = new HashMap<>();
        params.put("start", query.getHappenTimeStart());
        params.put("end", query.getHappenTimeEnd());

        String resp = null;
        try {
            resp = HttpUtil.createPost(xnjcUrl).form(params).timeout(60000).execute().body();
            log.info("resp==>{}",resp);
            if (ObjectUtils.isEmpty(resp)) throw new AppException("请求失败！");
            ApiResp<List<EffectSaveReq>> rest = JSON.parseObject(resp, new TypeReference<ApiResp<List<EffectSaveReq>>>() {
            });
            //记录保存
            if (rest.getCode() == 0) {
                List<EffectSaveReq> list = rest.getData();
                for (EffectSaveReq effectSaveReq : list) {
                    //先判断手机号码  如果手机号码为空 再比对人的姓名
/*                    boolean isMobile = Validator.isMobile(effectSaveReq.getPhone());
                    if (!isMobile) continue;*/


                    PerformRulesEntity rule = getRule(effectSaveReq.getRuleCode());

                    if (ObjectUtils.isEmpty(rule)) continue;

                    //查询是否存在 如果没有 则保存
                    PerformEffectRecordQuery effectRecordQuery = new PerformEffectRecordQuery();
                    effectRecordQuery.setHappenTime(effectSaveReq.getHappenTime());
                    effectRecordQuery.setWindowNum(effectSaveReq.getWindowNum());
                    effectRecordQuery.setRuleId(rule.getId());
                    PerformEffectRecordEntity performEffectRecordEntity = this.selectOne(effectRecordQuery, context);
                    if (!ObjectUtils.isEmpty(performEffectRecordEntity)) {
                        performEffectRecordEntity.setRemark(effectSaveReq.getExt());
                        performEffectRecordEntity.setUpdateTime(new Date());
                        this.update(performEffectRecordEntity, context);
                    } else {
                        effect(effectSaveReq);
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常:", e);
        }
    }

    @Override
    public void syncEffectRecordImgs(PerformEffectRecordQuery query, Context context) {
        query.setRemarkNotList(Arrays.asList(""));
        query.setSnapPathList(Arrays.asList(""));
        List<PerformEffectRecordEntity> effectRecordEntities = this.find(query, context);
        log.info("图片id与地址不为空的数量:{}", effectRecordEntities.size());
        for (PerformEffectRecordEntity effectRecordEntity : effectRecordEntities) {
            try {
                getEffectRecordImgs(effectRecordEntity, context);

            } catch (Exception e) {
                log.error("请求异常：" + e.getMessage());
            }
        }
    }

    @Override
    public void getEffectRecordImgs(PerformEffectRecordEntity effectRecord, Context context) {
        String phpInUrl = GlobalSysInfo.getParamValue(SYS_PARAM_XNJC_URL, "http://127.0.0.1:11039/zwfw_api_xnjc");
        String xnjcImgUrl = phpInUrl + "/api/kq_alert/alertSnap";
        Map<String, Object> params = new HashMap<>();
        if (ObjectUtils.isEmpty(effectRecord.getRemark())) throw new AppException("remark is null");
        params.put("id", effectRecord.getRemark());

        String resp = null;
        try {
            resp = HttpUtil.createPost(xnjcImgUrl).form(params).timeout(60000).execute().body();
            if (ObjectUtils.isEmpty(resp)) throw new AppException("请求失败！");
            ApiResp<List<String>> rest = JSON.parseObject(resp, new TypeReference<ApiResp<List<String>>>() {
            });
            if (rest.getCode() == 0) {
                if (!ObjectUtils.isEmpty(rest.getData())) {
                    effectRecord.setSnapPath(rest.getData().stream().collect(Collectors.joining(",")));
                    effectRecord.setUpdateTime(new Date());
                    this.update(effectRecord, context);

                    CheckEffectRecordQuery checkEffectRecordQuery = new CheckEffectRecordQuery();
                    checkEffectRecordQuery.setRecordId(effectRecord.getId());
                    CheckEffectRecordEntity checkEffectRecordEntity = checkEffectRecordService.selectOne(checkEffectRecordQuery, context);
                    if (!ObjectUtils.isEmpty(checkEffectRecordEntity)) {
                        checkEffectRecordEntity.setSnapPath(effectRecord.getSnapPath());
                        checkEffectRecordEntity.setUpdateTime(new Date());
                        checkEffectRecordService.update(checkEffectRecordEntity, context);
                    }
                }
            }
        } catch (Exception e) {
            log.error("异常:", e);
        }
    }


    private boolean effect(EffectSaveReq req) throws AppException {
        //效能保存
        //StaffEntity staffEntity = getStaff(req.getPhone());
        StaffEntity staffEntity = getStaff(req);
        if (ObjectUtils.isEmpty(staffEntity)) return false;
        PerformRulesEntity rule = getRule(req.getRuleCode());
        PerformEffectRecordEntity recordEntity = new PerformEffectRecordEntity();
        recordEntity.initAttrValue();
        recordEntity.setSubMethod(SubMethodEnum.系统自动.getValue());
        BeanUtils.copyProperties(req, recordEntity);
        recordEntity.setStaffId(staffEntity.getId());
        recordEntity.setStaffName(staffEntity.getName());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setDeptId(staffEntity.getDeptId());
        recordEntity.setDeptName(staffEntity.getDeptName());
        recordEntity.setSalaId(staffEntity.getSalaId());
        recordEntity.setSalaName(staffEntity.getSalaName());
        recordEntity.setSubAddType(rule.getSubAddType());
        recordEntity.setScore(rule.getScore());
        recordEntity.setRuleId(rule.getId());
        recordEntity.setRuleName(rule.getName());
        recordEntity.setCategoryId(rule.getCategoryId());
        recordEntity.setCategoryName(rule.getCategoryName());
        recordEntity.setDeductPerson("系统管理员");
        recordEntity.setDeductTime(new Date());
        recordEntity.setWorkNum(staffEntity.getWorkNum());
        recordEntity.setRemark(req.getExt());
        recordEntity.setWindowNum(req.getWindowNum());
        recordEntity.setCreateUserId(1L);
        recordEntity.setCreateTime(new Date());
        PerformRulesCategoryEntity categoryEntity = categoryService.get(rule.getCategoryId());
        recordEntity.setCategoryName(categoryEntity == null ? "" : categoryEntity.getName());
        PerformEffectRecordEntity save = this.save(recordEntity);
        return save.newEntity();
    }


    private void checkStaffAutoConf(StaffEntity staffEntity, PerformRulesEntity rule) {
        Boolean rulePass = false;
        //校验当前员工是否存在自动规则中
        List<PerformStaffConfEntity> performStaffConfEntities = performStaffConfService.find(new PerformStaffConfQuery());
        for (PerformStaffConfEntity performStaffConfEntity : performStaffConfEntities) {
            String staffIds = performStaffConfEntity.getStaffIds();
            Set<String> split = StrUtil.split(staffIds, ",").stream().collect(Collectors.toSet());
            if (split.contains(staffEntity.getId().toString())) {
                //查询当前规则
                List<PerformStaffConfDetailEntity> staffConfDetailEntities = performStaffConfDetailService.find(new PerformStaffConfDetailQuery().staffConfId(performStaffConfEntity.getId()));
                for (PerformStaffConfDetailEntity staffConfDetailEntity : staffConfDetailEntities) {
                    if (staffConfDetailEntity.getRuleId() == rule.getId()) {
                        rulePass = true;
                        break;
                    }
                }
            }
            if (rulePass) break;
        }
        if (rulePass) throw new AppException("当前用户与绩效规则未配置自动核查，请在后台配置后再新增！");
    }


    private PerformRulesEntity getRule(String ruleCode) {
        if (ObjectUtils.isEmpty(ruleCode)) return null;
        PerformRulesEntity rule = rulesService.getCache(ruleCode);
        return rule;
    }

    private StaffEntity getStaff(String phone) {
        StaffEntity staffEntity = staffService.selectOne(new StaffQuery().phoneNumber(phone));
        return staffEntity;
    }

    private StaffEntity getStaff(EffectSaveReq req) {
        if (!ObjectUtils.isEmpty(req.getPhone())) {
            List<StaffEntity> staffEntityList = staffService.find(new StaffQuery().phoneNumber(req.getPhone()));
            if (staffEntityList.size() > 1) {
                //多个 比对名字
                for (StaffEntity staffEntity : staffEntityList) {
                    if (staffEntity.getName().equals(req.getStaffName())) {
                        return staffEntity;
                    }
                }

                if (!ObjectUtils.isEmpty(req.getStaffName())) {
                    StaffEntity staffEntity = staffService.selectOne(new StaffQuery().name(req.getStaffName()));
                    if (!ObjectUtils.isEmpty(staffEntity)) return staffEntity;
                }

                return staffEntityList.get(0);
            } else if (staffEntityList.size() == 1) {
                return staffEntityList.get(0);
            }
            StaffEntity staffEntity = staffService.selectOne(new StaffQuery().phoneNumber(req.getPhone()));
            if (!ObjectUtils.isEmpty(staffEntity)) return staffEntity;
        }
        if (!ObjectUtils.isEmpty(req.getStaffName())) {
            StaffEntity staffEntity = staffService.selectOne(new StaffQuery().name(req.getStaffName()));
            if (!ObjectUtils.isEmpty(staffEntity)) return staffEntity;
        }
        return null;

    }


    public static void main(String[] args) {

        ArrayList<String> strings = new ArrayList<>();
        strings.add("1111");

        System.out.println(strings.stream().collect(Collectors.joining(",")));


    }

}