package com.usoftchina.bi.server.service.chart;

import com.usoftchina.bi.core.base.*;
import com.usoftchina.bi.core.exception.MyException;
import com.usoftchina.bi.core.utils.GetTokenDataUtil;
import com.usoftchina.bi.server.dao.chart.ChartsConfigMapper;
import com.usoftchina.bi.server.dao.user.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.usoftchina.bi.server.model.bo.GroupUpdateId;
import com.usoftchina.bi.server.model.po.ChartConfig;
import com.usoftchina.bi.server.model.po.ChartConfigList;
import com.usoftchina.bi.server.model.po.MessageLog;
import com.usoftchina.bi.server.model.vo.configVo.ChangeOrderInfo;
import com.usoftchina.bi.server.model.vo.configVo.ChartConfigInfo;
import com.usoftchina.bi.server.model.vo.configVo.GroupInfo;
import com.usoftchina.bi.server.service.common.MessageLogService;
import com.usoftchina.bi.server.service.strategy.StrategysService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class ChartsConfigService {

    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ObjectMapper objectmapper;
    @Autowired
    StrategysService strategysService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private MessageLogService messageLogService;

    /*
    保存表设置
     */
    public RepEntity setChartsConfig(ChartConfigInfo chartConfigInfo, String token){
        int userId = BaseContextHolder.getUserId();
        String userName = BaseContextHolder.getUserName();
        ChartConfig chartConfig = new ChartConfig();
        BeanUtils.copyProperties(chartConfigInfo, chartConfig);

        String groupBy = null;
        String accessAuthority = null;
        String updateAuthority = null;

        try {
            groupBy = objectmapper.writeValueAsString(chartConfigInfo.getGroupBy());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            accessAuthority = objectmapper.writeValueAsString(chartConfigInfo.getAccessAuthority());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            updateAuthority = objectmapper.writeValueAsString(chartConfigInfo.getUpdateAuthority());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        chartConfig.setGroupBy(groupBy);
        chartConfig.setAccessAuthority(accessAuthority);
        chartConfig.setUpdateAuthority(updateAuthority);
        chartConfig.setCreateId(userId);
        chartConfig.setCreateBy(userName);

        if (chartConfig.getChartsGroup() == 0){
            chartConfig.setChartsGroup(-1);
        }
        if (chartConfig.getChartOption() == null ) {
            chartConfig.setChartOption("");
        }
        if (chartConfig.getFetchConfig() == null || "".equals(chartConfig.getFetchConfig())){
            chartConfig.setFetchConfig("");
        }
        if (chartConfig.getStyle() == null){
            chartConfig.setStyle("");
        }

        chartsConfigMapper.insertCharts(chartConfig);
        int id = chartConfig.getChartId();

        return new RepEntity(RepCode.success,id);
    }

    /*
    更新表设置
     */
    public RepEntity updateChartsConfig(ChartConfigInfo chartConfigInfo, String token){
        int userId = BaseContextHolder.getUserId();
        String userName = BaseContextHolder.getUserName();
        int createID = chartsConfigMapper.getCreateId(chartConfigInfo.getChartId());
        if (userId != createID && !RoleConstant.ADMIN.getRole().equals(BaseContextHolder.getRole())){
            return new RepEntity(RepCode.NoAuthority);
        }
        ChartConfig chartConfig = new ChartConfig();
        BeanUtils.copyProperties(chartConfigInfo, chartConfig);

        String groupBy = null;
        String accessAuthority = null;
        String updateAuthority = null;

        try {
            groupBy = objectmapper.writeValueAsString(chartConfigInfo.getGroupBy());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        try {
            accessAuthority = objectmapper.writeValueAsString(chartConfigInfo.getAccessAuthority());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        try {
            updateAuthority = objectmapper.writeValueAsString(chartConfigInfo.getUpdateAuthority());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        chartConfig.setGroupBy(groupBy);
        chartConfig.setAccessAuthority(accessAuthority);
        chartConfig.setAccessAuthority(accessAuthority);
        chartConfig.setUpdateAuthority(updateAuthority);
        chartConfig.setCreateId(userId);
        chartConfig.setCreateBy(userName);
        if (chartConfig.getChartsGroup() == 0){
            chartConfig.setChartsGroup(-1);
        }
        if (chartConfig.getChartOption() == null) {
            chartConfig.setChartOption("");
        }
        if (chartConfig.getStyle() == null){
            chartConfig.setStyle("");
        }
        chartsConfigMapper.updateChartConfig(chartConfig);

        return new RepEntity(RepCode.success);
    }

    /*
    移交图表
     */
    public RepEntity changeChartOrder(ChangeOrderInfo changeOrderInfo, String token){
        int userId = BaseContextHolder.getUserId();
        String username = BaseContextHolder.getUserName();
        int createId = chartsConfigMapper.getCreateId(changeOrderInfo.getId());
        if (createId != userId && !RoleConstant.SUPER_ADMIN.getRole().equals(BaseContextHolder.getRole())){
            return new RepEntity(RepCode.NoAuthority);
        }
        chartsConfigMapper.changeChartOrder(username, changeOrderInfo.getUserId(), changeOrderInfo.getId());
        //记录LOg
        String chartName = chartsConfigMapper.getOneChart(changeOrderInfo.getId()).getChartName();
        messageLogService.update("图表", chartName, username, "移交图表");
        return new RepEntity(RepCode.success);
    }

    /*
    更新图表配置的分组
     */
    public RepEntity updateConfigGroup(String token, GroupUpdateId groupUpdateId){
        String username = BaseContextHolder.getUserName();
        int chartId = groupUpdateId.getId();
        int chartGroupId = groupUpdateId.getGroupId();
        chartsConfigMapper.updateConfigGroup(chartId, chartGroupId);
        //记录LOg
        String chartName = chartsConfigMapper.getOneChart(chartId).getChartName();
        messageLogService.update("图表", chartName, username, "更新图表分组");
        return new RepEntity(RepCode.success);
    }

    /*
    删除图表
     */
    public RepEntity delChartsConfig(String token, Long id){
        String username = BaseContextHolder.getUserName();
        int count = chartsConfigMapper.countDashboardsById(id);
        if (count > 0) {
            throw new MyException(RepCode.DASHBOARD_USED_CHARTS);
        }
        String chartName = chartsConfigMapper.getOneChart(id.intValue()).getChartName();
        chartsConfigMapper.deleteCharts(id);
        //记录LOg
        messageLogService.delete("图表", chartName, username, "删除图表分组");
        return new RepEntity(RepCode.success);
    }

    /*
    查询图表列表
     */
    public RepEntity getListCharts(String token, TestPage testPage){
        int id = BaseContextHolder.getUserId();
        String role = BaseContextHolder.getRole();
        List<ChartConfigList> chartsList = new ArrayList<>();
        if (RoleConstant.SUPER_ADMIN.getRole().equals(role)) {
            chartsList = chartsConfigMapper.getListCharts();
        }else {
            chartsList = chartsConfigMapper.getListByUser(id, testPage.enablePaging());
        }
        PageInfo<ChartConfigList> pageInfo = new PageInfo<>(chartsList);
        return new RepEntity(RepCode.success, pageInfo);
    }

    /*
    查询单个图表配置
     */
    public RepEntity getOneCharts(int id){
        ChartConfig chartConfig = chartsConfigMapper.getOneChart(id);
        if (chartConfig == null){
            return new RepEntity(RepCode.Null);
        }
        String name = chartsConfigMapper.getDataNameById(chartConfig.getDataId());
        if (name == null){
            return new RepEntity(RepCode.DataNonExistent);
        }
        return new RepEntity(RepCode.success, chartConfig);
    }

    /*
    创建图表分组
     */
    public RepEntity setDataConnectorGroup(String token, GroupInfo groupInfo){
        String username = BaseContextHolder.getUserName();
        if (groupInfo == null){
            return new RepEntity(RepCode.Null);
        }
        chartsConfigMapper.setChartsGroup(groupInfo);
        int id = groupInfo.getId();
        //记录LOg
        MessageLog messageLog = new MessageLog(username, "创建图表分组", "创建成功", "", "图表", groupInfo.getGroupName());
        messageLogService.customizeLog(messageLog);
        return new RepEntity(RepCode.success, id);
    }

    /*
    更新图表分组
     */
    public RepEntity updataDataConnectorGroup(String token, GroupInfo groupInfo){
        String username = BaseContextHolder.getUserName();
        chartsConfigMapper.updataChartsGroup(groupInfo);
        //记录LOg
        messageLogService.update("图表", groupInfo.getGroupName(), username, "更新图表分组");
        return new RepEntity(RepCode.success);
    }

    public RepEntity saveChartsGroup(String token, List<GroupInfo> groupInfoList) {
        String username = BaseContextHolder.getUserName();
        List<GroupInfo> addGroupInfoList = new ArrayList<>();
        List<GroupInfo> deleteGroupInfoList = new ArrayList<>();
        List<GroupInfo> updateGroupInfoList = new ArrayList<>();
        groupInfoList.forEach(groupInfo -> {
            if ("add".equals(groupInfo.getOperate())) {
                addGroupInfoList.add(groupInfo);
            }else if ("delete".equals(groupInfo.getOperate())) {
                deleteGroupInfoList.add(groupInfo);
            }else if ("update".equals(groupInfo.getOperate())) {
                updateGroupInfoList.add(groupInfo);
            }
        });
        if (addGroupInfoList.size() > 0) {
            messageLogService.save("图表分组", null, username, "批量创建图表分组");
            chartsConfigMapper.batchInsertCharts(addGroupInfoList);
        }
        if (updateGroupInfoList.size() > 0) {
            messageLogService.save("图表分组", null, username, "批量更新图表分组");
            chartsConfigMapper.batchUpdateCharts(updateGroupInfoList);
        }
        if (deleteGroupInfoList.size() > 0) {
            messageLogService.save("图表分组", null, username, "批量删除图表分组");
            chartsConfigMapper.batchUpdateGroupToDefault(deleteGroupInfoList);
            chartsConfigMapper.batchDeleteCharts(deleteGroupInfoList);
        }
        return new RepEntity(RepCode.success);
    }

    /*
    批量更新图表分组
     */
    public RepEntity updataListGroup(String token, List<GroupInfo> groupInfoList){
        String username = BaseContextHolder.getUserName();
        Iterator isList = groupInfoList.iterator();
        GroupInfo groupInfo = new GroupInfo();
        while (isList.hasNext()){
            groupInfo = (GroupInfo) isList.next();
            chartsConfigMapper.updataChartsGroup(groupInfo);
        }
        messageLogService.save("图表分组", null, username, "批量更新图表分组");
        return new RepEntity(RepCode.success);
    }

    /*
    删除图表分组
     */
    public RepEntity delDataConnectorGroup(String token, List<Integer> idList){
        String username = BaseContextHolder.getUserName();
        List<Integer> integerList = idList;
        Iterator isList = integerList.iterator();
        while (isList.hasNext()){
            int id = (int) isList.next();
            List<String> groupName = chartsConfigMapper.getChartFatherId(id);
            if (groupName.size() != 0){
                return new RepEntity(RepCode.hasGroupUsing);
            }
            List<String> chartName = chartsConfigMapper.getChartName(id);
            if (chartName.size() != 0 ){
                return new RepEntity(RepCode.hasChartUsing);
            }
        }
        chartsConfigMapper.delChartsGroup(idList);
        messageLogService.save("图表分组", null, username, "批量删除图表分组");
        return new RepEntity(RepCode.success);
    }

    /*
    查询图表分组列表
     */
    public RepEntity getConnectorGroup(){
        return new RepEntity(RepCode.success, chartsConfigMapper.getChartsGroup());
    }

}
