package com.bohuikeji.frame.module.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.entity.sys.SysChart;
import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.mapper.SysChartMapper;
import com.bohuikeji.frame.module.admin.service.IFieldAuthService;
import com.bohuikeji.frame.module.admin.service.ISysChartService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统菜单 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysChartServiceImpl extends ServiceImplBase<SysChartMapper, SysChart> implements ISysChartService {
    final IFieldAuthService fieldAuthService;
    @Override
    public List<SysChart> fullChartList(List<SysChart> charts,SysUser user) {
        charts.forEach(chart -> {
            if("card".equals(chart.getChartType())){
                chart.setValue(chart.sql().selectObj(fieldAuthService.formartSql(chart.getChartSql(),user)).toString());return;
            }
            else {
                List<LocalDate> xList = getXByDays(chart.getChartDays());
                JSONObject json = JSONObject.parseObject(chart.getChartJson());
                JSONArray datasets = json.getJSONArray("datasets");
                for (int i = 0; i < datasets.size(); i++) {
                    JSONObject node = datasets.getJSONObject(i);
                    String sql = node.getString("sql");
                    if (StringUtils.isBlank(sql)){
                        sql=chart.getChartSql();
                    }
                    //获取sql执行结果
                    List<Map<String, Object>> results = chart.sql().selectList(fieldAuthService.formartSql(sql, user));
                    //log.error("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$:{}",results);
                    //利用X坐标进行填充，Y坐标值，无值补0
                    node.put("data", getValue(xList,results,"days" ,"count"));
                    node.remove("sql");
                    datasets.set(i, node);
                }
                json.put("labels", xList);
                json.put("datasets", datasets);
                //log.error("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$2:{}",json);
                chart.setChartJson(json.toJSONString());
            }
        });
        return charts;
    }

    /**
     * 解析并填充数据结构
     * @param xs X坐标集合
     * @param results 数据库结果集
     * @param xkey x坐标的key
     * @param yKey y坐标的key
     * @return
     */
    private List<Object> getValue(List<LocalDate> xs,List<Map<String,Object>>results,String xkey,String yKey){
        List<Object> values=new ArrayList<>(xs.size());
        for(LocalDate x:xs){
            for(Map<String,Object> res:results){
                if(x.equals(LocalDate.parse(res.get(xkey).toString(),StringUtils.dataFormat))){
                    values.add(res.get(yKey));break;
                }
            }
        }
        return values;
        /*List<Object> list=new ArrayList<>();
        results.forEach(row->{
            list.add(row.get(key));
        });
        return list;*/
    }



    /**
     * 获取X坐标（日期坐标）
     * @param days 前多少天
     * @return
     */
    private List<LocalDate> getXByDays(int days){
        List<LocalDate> list=new ArrayList<>(days);
        //定义了数据周期则初始化周期日期
        LocalDate minDate=LocalDate.now().minusDays(days-1);
        for (int i = 0; i < days; i++) {
            list.add(minDate.plusDays(i));
        }
        return list;
    }
}
