package com.jwipc.spe.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jwipc.constant.EnableStatus;
import com.jwipc.exception.DaoException;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.security.dto.CurrentUserDTO;
import com.jwipc.spe.convert.SupAppraiseTemplateConvert;
import com.jwipc.spe.convert.SupTemDimensionConvert;
import com.jwipc.spe.convert.SupTemQuotaConvert;
import com.jwipc.spe.dto.PlanFieldDTO;
import com.jwipc.spe.dto.SupAppraiseTemplateBaseDTO;
import com.jwipc.spe.dto.SupAppraiseTemplateSaveDTO;
import com.jwipc.spe.dto.SupTemQuotaDTO;
import com.jwipc.spe.entity.SupAppraiseResultDetail;
import com.jwipc.spe.entity.SupAppraiseTemplate;
import com.jwipc.spe.entity.SupTemDimension;
import com.jwipc.spe.entity.SupTemQuota;
import com.jwipc.spe.logic.SupAppraiseTemplateLogic;
import com.jwipc.spe.model.po.MaterialBatchQualifiedPO;
import com.jwipc.spe.model.po.SupAppraiseTemplatePO;
import com.jwipc.spe.model.query.SupAppraiseTemplateQuery;
import com.jwipc.spe.service.*;
import com.jwipc.sys.client.SupplierEmailClient;
import com.jwipc.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Al
 * @create 2024-02-28 16:08
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SupAppraiseTemplateLogicImpl implements SupAppraiseTemplateLogic {
    private final ISupAppraiseTemplateService supAppraiseTemplateService;
    private final ISupTemDimensionService supTemDimensionService;
    private final SupTemDimensionConvert supTemDimensionConvert;
    private final SupTemQuotaConvert supTemQuotaConvert;
    private final ISupTemQuotaService supTemQuotaService;
    private final SupAppraiseTemplateConvert supAppraiseTemplateConvert;
    private final ISupAppraiseResultDetailService supAppraiseResultDetailService;
    private final IMaterialBatchQualifiedService materialBatchQualifiedService;
    private final SupplierEmailClient supplierEmailClient;

    @Override
    public PageView findByPage(SupAppraiseTemplateQuery query) {
        final Page<SupAppraiseTemplate> dbPage = PageUtil.toPage(query);

        List<SupAppraiseTemplatePO> supAppraiseTemplatePOS = supAppraiseTemplateService.findPageByQuery(dbPage, query);

        return PageUtil.getPV(supAppraiseTemplateConvert.po2PageListDTO(supAppraiseTemplatePOS), dbPage.getTotal());
    }

    //查询数据
    @Override
    public SupAppraiseTemplateBaseDTO getById(Integer id) {
        if (id != null) {
            SupAppraiseTemplatePO supAppraiseTemplatePO = supAppraiseTemplateService.getDataById(id);
            return supAppraiseTemplateConvert.po2DTO(supAppraiseTemplatePO);
        } else {
            return new SupAppraiseTemplateBaseDTO();
        }
    }

    /**
     * 启用或停用考核模板数据
     *
     * @param ids    数据Ids
     * @param status 1:启用 2:停用
     * @param user   当前操作人
     * @return 结果
     */
    @Override
    public boolean invalidOrEffectiveTarget(String ids, Integer status, CurrentUserDTO user) {
        boolean isOk = false;
        if (StringUtils.isNotEmpty(ids)) {
            List<SupAppraiseTemplate> list = Lists.newArrayList();
            for (String id : StringUtils.split(ids, ",")) {
                SupAppraiseTemplate sat = new SupAppraiseTemplate();
                sat.setId(Long.valueOf(id));
                sat.setStatus(status);
                sat.setUpdateTime(LocalDateTime.now());
                sat.setUpdateUserId(LoginUtil.getUserId());
                sat.setUpdateUserName(LoginUtil.getName());

                list.add(sat);
            }
            if (CollectionUtil.isNotEmpty(list)) {
                isOk = supAppraiseTemplateService.updateBatchById(list);
                if (!isOk) {
                    throw new DaoException("操作数据失败!");
                }
            }

            return true;
        }
        return false;
    }

    /**
     * 保存考核模板数据
     *
     * @param templateSaveDTO 考核模板数据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(SupAppraiseTemplateSaveDTO templateSaveDTO)
    {
        SupAppraiseTemplate template = supAppraiseTemplateConvert.dto2Entity(templateSaveDTO);
        if (Objects.isNull(template.getId())) {
            final LambdaQueryWrapper<SupAppraiseTemplate> resourcesLambdaQueryWrapper =
                    new LambdaQueryWrapper<SupAppraiseTemplate>().eq(
                            SupAppraiseTemplate::getTemplateCode, template.getTemplateCode()).last(" limit 1");
            if (ObjectUtil.isNotNull(supAppraiseTemplateService.getOne(resourcesLambdaQueryWrapper))) {
                throw new DaoException("模板编码 " + template.getTemplateCode() + " 已经存在");
            }
            template.setCreateTime(LocalDateTime.now());
            template.setCreateUserId(LoginUtil.getUserId());
            template.setCreateUserName(LoginUtil.getName());
            template.setId(null);
        } else {
            template.setUpdateTime(LocalDateTime.now());
            template.setUpdateUserId(LoginUtil.getUserId());
            template.setUpdateUserName(LoginUtil.getName());
        }
        if (!supAppraiseTemplateService.saveOrUpdate(template)) {
            throw new DaoException("保存考核模板数据失败");
        }
        final Long id = template.getId();
        // 考核模板与考核维度关系
        if (CollectionUtils.isNotEmpty(templateSaveDTO.getDimensions())) {
            List<SupTemDimension> supTemDimensions = supTemDimensionConvert.dtos2Entities(
                    templateSaveDTO.getDimensions());
            //排序
            int i = 1;
            for (SupTemDimension td : supTemDimensions) {
                td.setId(null);
                td.setTemplateId(id);
                td.setNumber(i);
                i++;
            }
            supTemDimensionService.remove(
                    new LambdaQueryWrapper<SupTemDimension>().eq(SupTemDimension::getTemplateId, template.getId()));
            if (CollectionUtils.isNotEmpty(supTemDimensions)) {
                supTemDimensionService.saveBatch(supTemDimensions);
            }
        }

        // 考核模板与考核维度和考核指标关系
        if (CollectionUtils.isNotEmpty(templateSaveDTO.getQuotas())) {
            List<SupTemQuota> list = supTemQuotaConvert.dtos2Entities(templateSaveDTO.getQuotas());
            int i = 1;
            for (SupTemQuota tdq : list) {
                tdq.setId(null);
                tdq.setTemplateId(id);
                tdq.setEvelSort(i);
                i++;
            }
            supTemQuotaService.remove(
                    new LambdaQueryWrapper<SupTemQuota>().eq(SupTemQuota::getTemplateId, template.getId()));
            supTemQuotaService.saveBatch(list);
        }
        return true;
    }

    @Override
    public List<SupAppraiseTemplateBaseDTO> listAll(String types) {
        final List<String> split = StrUtil.split(types, StrUtil.COMMA);
        final List<SupAppraiseTemplate> supAppraiseTemplates = supAppraiseTemplateService.list(
                new LambdaQueryWrapper<SupAppraiseTemplate>().in(CollUtil.isNotEmpty(split),
                                SupAppraiseTemplate::getEvaluationCycle, split)
                        .eq(SupAppraiseTemplate::getStatus, EnableStatus.ENABLE.getStatus()));

        return supAppraiseTemplateConvert.entities2Dtos(supAppraiseTemplates);
    }

    @Override
    public List<SupTemQuotaDTO> getField(Long templateId) {
        final List<SupTemQuota> list = supTemQuotaService.list(
                new LambdaQueryWrapper<SupTemQuota>().eq(SupTemQuota::getTemplateId, templateId)
                        .orderBy(true, true, SupTemQuota::getEvelSort));
        return supTemQuotaConvert.entities2Dtos(list);
    }

    @Override
    public List<PlanFieldDTO> getFieldByPlan(Long planId) {
        final List<SupAppraiseResultDetail> list = supAppraiseResultDetailService.list(
                new LambdaQueryWrapper<SupAppraiseResultDetail>().eq(SupAppraiseResultDetail::getPlanId, planId)
                        .orderBy(true, true, SupAppraiseResultDetail::getEvelSort)
                        .groupBy(SupAppraiseResultDetail::getQuotaCode));
        Map<String, PlanFieldDTO> cache = new LinkedHashMap<>();
        for (SupAppraiseResultDetail supAppraiseResultDetail : list) {
            final String dimensionCode = supAppraiseResultDetail.getDimensionCode();
            final String dimensionName = supAppraiseResultDetail.getDimensionName();
            final String quotaCode = supAppraiseResultDetail.getQuotaCode();
            final String quotaDesc = supAppraiseResultDetail.getQuotaDesc();
            PlanFieldDTO planFieldDTO = cache.get(dimensionCode);
            if (Objects.nonNull(planFieldDTO)) {
                final List<PlanFieldDTO> item = planFieldDTO.getItem();
                PlanFieldDTO fieldDTO = new PlanFieldDTO();
                fieldDTO.setCode(quotaCode);
                fieldDTO.setName(quotaDesc);
                fieldDTO.setType(supAppraiseResultDetail.getQuotaType());
                item.add(fieldDTO);
            } else {
                planFieldDTO = new PlanFieldDTO();
                planFieldDTO.setCode(dimensionCode);
                planFieldDTO.setName(dimensionName);
                List<PlanFieldDTO> itm = Lists.newArrayList();
                PlanFieldDTO fieldDTO = new PlanFieldDTO();
                fieldDTO.setCode(quotaCode);
                fieldDTO.setName(quotaDesc);
                fieldDTO.setType(supAppraiseResultDetail.getQuotaType());
                itm.add(fieldDTO);
                planFieldDTO.setItem(itm);
                cache.put(dimensionCode, planFieldDTO);
            }
        }
        return cache.values().stream().collect(Collectors.toList());
    }

    @Override
    public List<Map<String, String>> getMesData(String date) {
        int batchSize = 4;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtils.yyyyMMDash);
        final DateTime localDate = DateUtil.parse(date, formatter);
        // 解析日期字符串为LocalDate
        final Pair<LocalDateTime, LocalDateTime> startAndEndDate = DateUtils.getStartAndEndDate(
                localDate.year(), localDate.monthBaseOne());
        final List<MaterialBatchQualifiedPO> mesData = materialBatchQualifiedService.getMesData(
                startAndEndDate.getKey(), startAndEndDate.getValue(), batchSize);
        String key1 = "ZW_PZ_01";
        String key2 = "ZW_PZ_13";
        String key3 = "supplierCode";
        String key4 = "supplierName";
        String key5 = "date";
        String key6 = "ZW_JS_01";
        String key7 = "ZW_FW_01";
        List<Map<String, String>> list = Lists.newArrayList();
        for (MaterialBatchQualifiedPO mesDatum : mesData) {

            Map<String, String> map = Maps.newHashMap();
            map.put(key1, mesDatum.getTotal());
            map.put(key2, mesDatum.getRejection());
            map.put(key3, mesDatum.getSupplierCode());
            map.put(key4, mesDatum.getSupplierName());
            map.put(key5, mesDatum.getDate());
            map.put(key6, "8");
            map.put(key7, "26");
            list.add(map);
        }
        return list;
    }

}
