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

import com.usoftchina.bi.core.base.BaseContextHolder;
import com.usoftchina.bi.core.base.RoleConstant;
import com.usoftchina.bi.core.utils.GetTokenDataUtil;
import com.usoftchina.bi.server.dao.chart.ChartsConfigMapper;
import com.usoftchina.bi.server.dao.dataSource.DataConnectorMapper;
import com.usoftchina.bi.server.dao.strategy.StrategysBdMapper;
import com.usoftchina.bi.server.dao.strategy.StrategysChartMapper;
import com.usoftchina.bi.server.dao.user.RecordMapper;
import com.usoftchina.bi.server.model.vo.configVo.RecordInfo;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@Component
public class ChartsUtilService {
    @Autowired
    DataConnectorMapper dataConnectorMapper;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    StrategysBdMapper strategysBdMapper;
    @Autowired
    StrategysChartMapper strategysChartMapper;
    @Autowired
    RecordMapper recordMapper;

    public String getSqlStr(String token, int id, int dashId) {
        Map<String, String> resultMap = GetTokenDataUtil.getTokenData(token);
        int userId = Integer.parseInt(resultMap.get("id"));
        String role = resultMap.get("role");
        int createID;
        int baseId;
        try {
            createID = chartsConfigMapper.getCreateId(id);
            baseId = dataConnectorMapper.getBaseId(id);
        }catch (BindingException exception){
            throw new BindingException();
        }
        String tableName = chartsConfigMapper.getTableName(id);
        if (dashId == 0) {
            if (userId == createID || RoleConstant.SUPER_ADMIN.getRole().equals(role)) {
                //如果数据源创建人ID跟用户ID一样，获得数据源全部权限
                if (tableName == null || "".equals(tableName)) {
                    return "";
                } else {
                    return columnNameUtil(userId, baseId, tableName, true, id, -1);
                }
            } else {
                //先拿图表创建者权限，在取分发权限
                String sql = columnNameUtil(createID, baseId, tableName, true, id, -1);
                return columnNameUtil(userId, baseId, sql, false, id, -1);
            }
        }else {
            return columnNameUtil(createID, baseId, tableName, true, id, -1);
        }
    }

    public String columnNameUtil(int userId, int baseId, String tableName, boolean isOrder, int id, int createBId){
        //用户不是创建人
        List<String> strList = new ArrayList<>();
        String role = BaseContextHolder.getRole();
        if (isOrder){
            int baseCreateId;
            if (id != 0) {
                baseCreateId = chartsConfigMapper.getCreateIdBychart(id);
            }else {
                baseCreateId = createBId;
            }
            if (baseCreateId == userId || RoleConstant.SUPER_ADMIN.getRole().equals(role)){
                return "(" + tableName +")";
            }else {
                strList = strategysBdMapper.getSqlStr(userId, baseId);
            }
        }else {
            if (RoleConstant.SUPER_ADMIN.getRole().equals(role)) {
                return "(" + tableName +")";
            }else {
                strList = strategysChartMapper.getSqlStr(userId, id);
            }
        }

        if (strList.size() == 0){
            return "";
        }
        String sqlStr = "";
        Iterator isList = strList.iterator();
        while (isList.hasNext()){
            String str = (String) isList.next();
            if ("".equals(str) || str == null){
                return  "(select * from " + "(" + tableName +"))";
            }
            StringBuilder sb = new StringBuilder(str);
            sqlStr = sqlStr + String.valueOf(sb .replace(1, 5, "( ")) + ") or";
        }
        StringBuilder sb = new StringBuilder(sqlStr);
        sqlStr = "(select * from " + "(" + tableName +")" + " where " + sb.replace(sb.length()-2,sb.length(), "") + ")";
        return sqlStr;
    }

    /*
    浏览记录
     */
    public void inputRecord(String token, RecordInfo recordInfo){
        int tarId = recordInfo.getTarId();
        String type = recordInfo.getType();
        Map<String, String> resultMap = GetTokenDataUtil.getTokenData(token);
        int userId = Integer.parseInt(resultMap.get("id"));
        int count = recordMapper.getCount(type, userId);


        List<Integer> integerList = recordMapper.getListId(type, userId);
        if (integerList.contains(tarId)){
            recordMapper.updateRecord(type, tarId);
        }else {
            if (count >= 10) {
                recordMapper.deleteRecord(type, userId);
            }
            recordMapper.inputRecord(type, userId, tarId);
        }
    }
}
