package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.QualityApply;
import cn.wise.sc.cement.business.entity.SysGroup;
import cn.wise.sc.cement.business.entity.SysUser;
import cn.wise.sc.cement.business.mapper.QualityApplyMapper;
import cn.wise.sc.cement.business.service.IQualityApplyService;
import cn.wise.sc.cement.business.service.ISysGroupService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import cn.wise.sc.cement.business.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-10-12
 */
@Service
public class QualityApplyServiceImpl extends ServiceImpl<QualityApplyMapper, QualityApply>
        implements IQualityApplyService {

    final
    RedisUtil redisUtil;
    final
    ISysUserService iSysUserService;
    final
    ISysGroupService iSysGroupService;

    public QualityApplyServiceImpl(RedisUtil redisUtil,
                                   ISysUserService iSysUserService,
                                   ISysGroupService iSysGroupService) {
        this.redisUtil = redisUtil;
        this.iSysUserService = iSysUserService;
        this.iSysGroupService = iSysGroupService;
    }

    @Override
    public Set<Integer> selectQualityApplyStatusByProIds(List<Integer> projectIds) {
        if (projectIds.size() == 0) {
            return new HashSet<>();
        }
        QueryWrapper<QualityApply> qw = new QueryWrapper<>();
        qw.in("project_id", projectIds);
        List<QualityApply> list = this.list(qw);
        if (list.size() == 0) {
            return new HashSet<>();
        }
        return list.stream().map(QualityApply::getProjectId).collect(Collectors.toSet());
    }

    @Override
    public void exportQuality(Date startParse, Date endParse, HttpServletResponse response) {

        QueryWrapper<QualityApply> qw = new QueryWrapper<>();
        if (startParse != null) {
            qw.ge("create_time", startParse);
        }
        if (endParse != null) {
            qw.le("create_time", endParse);
        }
        List<QualityApply> list = this.list(qw);
        //找到所有项目id归类
        Set<Integer> projectIds = list.stream().map(QualityApply::getProjectId).collect(Collectors.toSet());
        List<Object[]> datas = new ArrayList<>();
        //关联部门名字
        Set<Integer> userIds = list.stream()
                .filter(arg -> !"误差".equals(arg.getUserName()) &&
                        !"标准样".equals(arg.getUserName()))
                .map(QualityApply::getUserId)
                .collect(Collectors.toSet());
        //获取所以用户
        final String userCache = "SYS_USER:CACHE";
        final String groupCache = "SYS_GROUP:CACHE";

        if (!redisUtil.existsKey(userCache)) {
            List<SysUser> sysUsers = iSysUserService.list();
            redisUtil.setString(userCache, JSON.toJSONString(sysUsers), 600);
        }
        if (!redisUtil.existsKey(groupCache)) {
            List<SysGroup> sysGroups = iSysGroupService.list();
            redisUtil.setString(groupCache, JSON.toJSONString(sysGroups), 600);
        }
        //会有临界值问题
        List<SysUser> sysUsers = JSON.parseArray(redisUtil.getString(userCache) + "", SysUser.class);
        List<SysGroup> sysGroups = JSON.parseArray(redisUtil.getString(groupCache) + "", SysGroup.class);
        Map<Integer, String> userGroupMap = new HashMap<>(userIds.size());
        sysUsers.stream()
                .filter(arg -> userIds.contains(arg.getId()))
                .forEach(arg -> sysGroups.forEach(opt -> {
                    if (opt.getId().intValue() == arg.getGroupId()) {
                        userGroupMap.put(arg.getId(), opt.getName());
                    }
                }));
        if (userGroupMap.size() == 0) {
            return;
        }

        for (Integer projectId : projectIds) {
            //找到每个项目的检测组  以检测组归类
            Set<Integer> teamIds = list.stream()
                    .filter(arg -> arg.getProjectId().intValue() == projectId)
                    .map(QualityApply::getTeamGroupId)
                    .collect(Collectors.toSet());

            for (Integer teamId : teamIds) {
                List<QualityApply> samples = list.stream().filter(arg -> arg.getTeamGroupId().intValue() == teamId
                        && arg.getProjectId().intValue() == projectId)
                        .collect(Collectors.toList());
                //以样品归类
//                Set<Integer> sampleIds = samples.stream().map(QualityApply::getTeamGroupId)
//                        .collect(Collectors.toSet());

                //写每个样品的表头
                list.stream()
                        .filter(arg -> arg.getTeamGroupId().intValue() == teamId)
                        .findFirst().ifPresent(arg -> {
                    List<String> teams = JSON.parseArray(arg.getTeams(), String.class);
                    Object[] objs = new Object[teams.size() + 8];
                    objs[0] = "项目名称";
                    objs[1] = "项目编号";
                    objs[2] = "样品名称";
                    objs[3] = "样品状态";
                    objs[4] = "来样编号";
                    objs[5] = "本所编号";
                    objs[6] = "部门";
                    objs[7] = "分析";
                    for (int i = 0; i < teams.size(); i++) {
                        String teamName = teams.get(i);
                        if (teamName.contains("\"")) {
                            teamName = teamName.replace("\"", "");
                        }
                        objs[8 + i] = teamName;
                    }
                    datas.add(objs);
                });
                //为每个样品写值
                samples.forEach(arg -> {
                    List<String> inputValus = JSON.parseArray(arg.getInputResult(), String.class);
                    Object[] objs = new Object[inputValus.size() + 8];
                    if (!"误差".equals(arg.getUserName())) {
                        objs[0] = arg.getProjectName();
                        objs[1] = arg.getProjectId();
                        objs[2] = arg.getSampleName();
                        objs[3] = arg.getSampleForm();
                        objs[4] = arg.getSampleCode();
                        objs[5] = arg.getCementCode();
                        objs[6] = userGroupMap.get(arg.getUserId());
                    }
                    //添加名字
                    objs[7] = arg.getUserName();
                    for (int i = 0; i < inputValus.size(); i++) {
                        String value = inputValus.get(i);
                        if (value == null){
                            value = "0";
                        }
                        if ( value.contains("\"")) {
                            value = value.replace("\"", "");
                        }
                        objs[8 + i] = value;
                    }

                    datas.add(objs);
                });

            }
        }
        ExcelUtil.excelExport("qualityApply", null, datas, response);
    }

}
