package com.njcn.serviceimpl.configuration;

import com.njcn.mapper.configuration.RPTreeMapper;
import com.njcn.mapper.configuration.RptAssMapper;
import com.njcn.mapper.configuration.RptDataMapper;
import com.njcn.mapper.configuration.RptPloyMapper;
import com.njcn.pojo.commons.PloyInfo;
import com.njcn.pojo.configuration.*;
import com.njcn.sso.pojo.user.User;
import com.njcn.service.configuration.ReportService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.UserUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private UserUtil userUtil;

    @Resource
    private RPTreeMapper rptreeMapper;

    @Resource
    private RptDataMapper rptDataMapper;

    @Resource
    private RptPloyMapper rptPloyMapper;

    @Resource
    private RptAssMapper rptAssMapper;

    @Autowired
    private AppConfig appConfig;

    public List<RPTree> getTreeData(Integer dataType) {
        List<RPTree> list = new ArrayList<>();

        Map<Integer, Integer> value = new HashMap<Integer, Integer>();
        int p = 1000;
        List<RPTree> one = rptreeMapper.getfirstData(dataType);

        if (one == null || one.size()==0) {
            RPTree dt = new RPTree();
            dt.setId(100);
            dt.setNodeType(0);
            dt.setpId(0);
            dt.setPpId(0);
            dt.setName("报告基础项");
            dt.setRdIndex("0");
            list.add(dt);
            return list;
        }

        RPTree dt = new RPTree();
        dt.setId(100);
        dt.setNodeType(0);
        dt.setpId(0);
        dt.setPpId(0);
        dt.setName("报告基础项");
        dt.setRdIndex("0");
        list.add(dt);

        List<Integer> first = new ArrayList<>();

        for (int i = 0; i < one.size(); i++) {
            first.add(one.get(i).getNodeIndex());
            RPTree dto = new RPTree();
            dto.setId(++p);
            dto.setName(one.get(i).getRdDescribe());
            dto.setpId(100);
            dto.setPpId(100);
            dto.setNodeIndex(one.get(i).getNodeIndex());
            dto.setNodeType(1);
            dto.setRdIndex(one.get(i).getRdIndex());
            list.add(dto);
            value.put(one.get(i).getNodeIndex(), p);
        }

        List<RPTree> two = rptreeMapper.getsecondData(first,dataType);
        if (two == null || two.size()==0) {
            return list;
        }

        Map<Integer, Integer> value1 = new HashMap<Integer, Integer>();
        List<Integer> second = new ArrayList<>();
        int p1 = 2000;
        for (int i = 0; i < two.size(); i++) {
            second.add(two.get(i).getNodeIndex());
            RPTree dto = new RPTree();
            dto.setId(++p1);
            dto.setName(two.get(i).getRdDescribe());
            dto.setpId(value.get(two.get(i).getpId()));
            dto.setPpId(two.get(i).getpId());
            dto.setNodeIndex(two.get(i).getNodeIndex());
            dto.setNodeType(2);
            dto.setRdIndex(two.get(i).getRdIndex());
            list.add(dto);
            value1.put(two.get(i).getNodeIndex(), p1);
        }

        List<RPTree> three = rptreeMapper.getsecondData(second,dataType);
        if (three == null || three.size()==0) {
            return list;
        }

        int p2 = 3000;
        for (int i = 0; i < three.size(); i++) {
            RPTree dto = new RPTree();
            dto.setId(++p1);
            dto.setName(three.get(i).getRdDescribe());
            dto.setpId(value1.get(three.get(i).getpId()));
            dto.setPpId(three.get(i).getpId());
            dto.setNodeIndex(three.get(i).getNodeIndex());
            dto.setNodeType(3);
            dto.setRdIndex(three.get(i).getRdIndex());
            list.add(dto);
        }
//
//		Map<Integer, Integer> value1 = new HashMap<Integer, Integer>();
//		int p1 = 2000;
//		for (int i=0;i<subInfo.size();i++) {
//			Tree dto = new Tree();
//			dto.setId(++p1);
//			dto.setName(subInfo.get(i).getName());
//			dto.setpId(value.get(subInfo.get(i).getpId()));
//			dto.setPpId(subInfo.get(i).getpId());
//			dto.setNodeIndex(subInfo.get(i).getNodeIndex());
//			dto.setNodeType(2);
//			list.add(dto);
//			value1.put(subInfo.get(i).getNodeIndex(), p1);
//		}
//		
//		Map<Integer, Integer> value2 = new HashMap<Integer, Integer>();
//		int p2 = 3000;
//		for (int i=0;i<devInfo.size();i++) {
//			Tree dto = new Tree();
//			dto.setId(++p2);
//			dto.setName(devInfo.get(i).getName());
//			dto.setpId(value1.get(devInfo.get(i).getpId()));
//			dto.setPpId(devInfo.get(i).getpId());
//			dto.setNodeIndex(devInfo.get(i).getNodeIndex());
//			dto.setNodeType(3);
//			list.add(dto);
//			value2.put(devInfo.get(i).getNodeIndex(), p2);
//		}

        return list;
    }

    public String saveNode(String name, String describe, Integer first, Integer second,Integer dataType) {
        RptData tmp = new RptData();
        tmp.setRdName(name);
        tmp.setState(1);
        tmp.setDataType(dataType);

        tmp = rptDataMapper.selectOne(tmp);
        if (tmp != null) {
            return "失败a";
        } else {
            RptData rpt = new RptData();
            String index = UUID.randomUUID().toString();
            rpt.setRdIndex(index);
            rpt.setRdName(name);
            rpt.setRdDescribe(describe);

            User user = TokenManager.getToken();
            rpt.setState(Integer.valueOf("1"));
            rpt.setUserIndex(user.getUserIndex());
            rpt.setUpdateTime(new Date());
            rpt.setDataType(dataType);
			String sysType = TokenManager.getSysType();
			rpt.setSysType(sysType);

			if(first==null){
				rpt.setParentnode(0);

				int node=rptDataMapper.getMaxDesc()+1000;
				rpt.setNode(node);
				rpt.setSort(rptDataMapper.getMaxDesc()+1);
			}else if(second == null){
				rpt.setParentnode(first);

				int node=rptDataMapper.getMaxDesc()+1000+first;
				rpt.setNode(node);
				rpt.setSort(rptDataMapper.getMaxDesc()+1);
			}else{
				rpt.setParentnode(second);

				int node=rptDataMapper.getMaxDesc()+1000+second;
				rpt.setNode(node);
				rpt.setSort(rptDataMapper.getMaxDesc()+1);
			}
			
            try {
                int flag = rptDataMapper.insert(rpt);
                return "成功";
            } catch (Exception e) {
                return "添加失败";
            }
        }
    }

    public List<List> getAllData(Integer dataType) {
        List<List> result = new ArrayList<>();

        RptData exm = new RptData();
        exm.setDataType(dataType);
        exm.setState(1);
        List<RptData> one = rptDataMapper.select(exm);

        for (int i = 0; i < one.size(); i++) {
            List<String> tmp = new ArrayList<String>();
            tmp.add(one.get(i).getRdName());
            tmp.add(one.get(i).getRdDescribe());
            int parentnode = one.get(i).getParentnode();
            if (parentnode == 0) {
                tmp.add("无");
            } else {
                RptData rpt = new RptData();
                rpt.setNode(parentnode);
                rpt = rptDataMapper.selectOne(rpt);
                if (rpt != null) {
                    tmp.add(rpt.getRdDescribe());
                }
            }

            tmp.add(
                    "<button type='button' class='btn  themeBGColor' style='margin-right:10px;' href='javascript:void(0);' onclick='updateRpData(\"" + one.get(i).getRdIndex() + "\")' ><i class='glyphicon glyphicon-edit'></i>修改</button>"
                            + "<button type='button' class='btn  btn-danger' style='margin-right:10px;' href='javascript:void(0);' onclick='deleteRpData(\"" + one.get(i).getRdIndex() + "\")' ><i class='glyphicon glyphicon-trash'></i>删除</button>"
            );

            result.add(tmp);
        }
        return result;
    }

    public List<List> getData(Integer index) {
        List<List> result = new ArrayList<>();

        RptData tmp = new RptData();
        tmp.setNode(index);

        List<RptData> one = rptDataMapper.select(tmp);
        
        RptData tmp1 = new RptData();
        tmp1.setParentnode(index);
        List<RptData> two = rptDataMapper.select(tmp1);
        
        for(int n = 0;n<two.size();n++){
        	one.add(two.get(n));
        	
        	RptData tmp2 = new RptData();
        	tmp2.setParentnode(two.get(n).getNode());
            List<RptData> three = rptDataMapper.select(tmp2);
            
            for(int m = 0;m<three.size();m++){
            	one.add(three.get(m));
            }
        }

        for (int i = 0; i < one.size(); i++) {
            List<String> temp = new ArrayList<String>();
            temp.add(one.get(i).getRdName());
            temp.add(one.get(i).getRdDescribe());
            int parentnode = one.get(i).getParentnode();
            if (parentnode == 0) {
                temp.add("无");
            } else {
                RptData rpt = new RptData();
                rpt.setNode(parentnode);
                rpt = rptDataMapper.selectOne(rpt);
                if (rpt != null) {
                    temp.add(rpt.getRdDescribe());
                }
            }

            temp.add(
                    "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);' onclick='updateRpData(\"" + one.get(i).getRdIndex() + "\")' ><i class='glyphicon glyphicon-edit'></i>修改</button>"
                            + "<button type='button' class='btn  btn-danger' style='margin-right:10px;' href='javascript:void(0);' onclick='deleteRpData(\"" + one.get(i).getRdIndex() + "\")' ><i class='glyphicon glyphicon-trash'></i>删除</button>"
            );

            result.add(temp);
        }
        return result;
    }

    public String savePloy(String name, String describe, List<String> index, Integer ployType) {
        String result;

        RptPloy tmp = new RptPloy();
        tmp.setRpName(name);
        tmp.setState(new Integer(1));

        tmp = rptPloyMapper.selectOne(tmp);
        if (tmp != null) {
            return "失败a";
        } else {
            RptPloy rpp = new RptPloy();
            String rpIndex = UUID.randomUUID().toString();
            rpp.setRpIndex(rpIndex);
            rpp.setRpName(name);
            rpp.setRpDescribe(describe);

            User user = TokenManager.getToken();
            rpp.setState(Integer.valueOf("1"));
            rpp.setUserIndex(user.getUserIndex());
            rpp.setUpdateTime(new Date());

            String sysType = TokenManager.getSysType();
            rpp.setSysType(sysType);
            rpp.setPloyType(ployType);

            try {
                int flag = rptPloyMapper.insert(rpp);

                for (int i = 0; i < index.size(); i++) {
                    RptAss rpa = new RptAss();
                    rpa.setRpIndex(rpIndex);
                    rpa.setRdIndex(index.get(i));

                    int flag0 = rptAssMapper.insert(rpa);
                }

                return "成功";
            } catch (Exception e) {
                return "失败";
            }

        }
    }

    public String updateNode(String rdIndex, String name, String describe) {
        RptData rpt = new RptData();

        List<RptData> test = rptDataMapper.testName(name, rdIndex);

        RptData tmp = rptDataMapper.selectByPrimaryKey(rdIndex);

        if (test.size() > 0) {
            return "更新失败a";
        } else {
            tmp.setRdName(name);
            tmp.setRdDescribe(describe);
            tmp.setUpdateTime(new Date());

            try {
                int flag = rptDataMapper.updateByPrimaryKey(tmp);
                return "更新成功";
            } catch (Exception e) {
                return "更新失败";
            }
        }
    }

    public String updatePloy(String rpIndex, String name, String describe, List<String> index, Integer... type) {
        String result;

        List<RptPloy> tmp = new ArrayList<>();

        tmp = rptPloyMapper.testName(rpIndex, name);
        if (tmp.size() > 0) {
            return "失败a";
        } else {
            RptPloy rpp = new RptPloy();
            rpp = rptPloyMapper.selectByPrimaryKey(rpIndex);
            rpp.setRpName(name);
            rpp.setRpDescribe(describe);

            rpp.setUpdateTime(new Date());
            
            try {
                int flag = rptPloyMapper.updateByPrimaryKey(rpp);

                RptAss del = new RptAss();
                del.setRpIndex(rpIndex);
                int flag4 = rptAssMapper.delete(del);

                for (int i = 0; i < index.size(); i++) {
                    RptAss rpa = new RptAss();
                    rpa.setRpIndex(rpIndex);
                    rpa.setRdIndex(index.get(i));

                    int flag0 = rptAssMapper.insert(rpa);
                }

                return "成功";
            } catch (Exception e) {
                return "失败b";
            }
        }
    }

    @Override
	public List<RptPloy> getTemplate(Integer ployType) {
		String sysType=appConfig.getSysType();
		//获取所有模板
		List<RptPloy> ploys ;
		List<RptPloy> rptPloys=new ArrayList<>() ;
		RptPloy ploy = new RptPloy();
		ploy.setSysType(sysType);
		ploy.setState(1);
		ploy.setPloyType(ployType);
		ploys=rptPloyMapper.select(ploy);
		if(CollectionUtils.isEmpty(ploys)){
			return new ArrayList<>();
		}
		//获取该策略对应的选项
		for (RptPloy ploy1: ploys) {
			List<RptData> rptData;
			rptData=rptDataMapper.getDatasByPloy(ploy1.getRpIndex());
			ploy1.setRptDatas(rptData);
			rptPloys.add(ploy1);
		}
		return rptPloys;
	}

    @Override
    public List<RptData> getExcelSetting() {
        List<RptData> list = rptreeMapper.getExcelSetting();

        //添加最大层的根节点 excel报表基础项
        RptData tree = new RptData();
        tree.setId(0);
        tree.setRdIndex("0");
        tree.setRdName("jcpz");
        tree.setParentGUID("0");
        tree.setRdDescribe("excel报表基础项");

        //根据时间生成唯一种子Key作为tree的id使用  为啥用这个做法，比较尴尬
        Calendar calendar = Calendar.getInstance();
        long timeKey = calendar.getTimeInMillis();

        //设置查询结果的id与pId
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getParentGUID().equals("0")) { //如果parentguid为0，则为二级根节点
                    list.get(j).setpId(0);
                    list.get(j).setId(timeKey + j);
                } else if (list.get(j).getParentGUID().equals(list.get(i).getRdIndex())) {
                    list.get(j).setpId(list.get(i).getId());
                    list.get(j).setId(timeKey + j);
                }
            }
        }

        list.add(tree);

        return list;
    }

    @Override
    @Transactional
    public int createData(String shortName, String fullName, String parentGUID) {
        RptData data = new RptData();//封装数据
        String strUserGuid = TokenManager.getToken().getUserIndex();//获取用户信息
        String sysKey = TokenManager.getSysType();//获取系统key
        Date now = new Date();//获取创建时间

        data.setRdDescribe(fullName);
        data.setRdName(shortName);
        data.setNode(0);
        data.setSort(0);
        data.setState(1);
        data.setParentnode(0);
        data.setParentGUID(parentGUID == null ? "0" : parentGUID);//此处的0参考上面方法tree数据加载说明
        data.setCreateTime(now);
        data.setUpdateTime(now);
        data.setUserIndex(strUserGuid);
        data.setRdIndex(UUID.randomUUID().toString());
        data.setSysType(sysKey);
        data.setDataType(Integer.valueOf("2"));

        return rptDataMapper.insert(data);
    }

    @Override
    @Transactional
    public int deleteData(String rdIndex) {
        return rptDataMapper.deleteData(rdIndex, new Date());
    }

    @Override
    @Transactional
    public int updateData(String shortName, String fullName, String rdIndex) {
        return rptDataMapper.updateData(shortName, fullName, rdIndex, new Date());
    }

    @Override
    @Transactional
    public int addExcelPloy(String name, String describe, String rdIndex) {
        JSONArray ja = JSONArray.fromObject(rdIndex);
        List<String> index = (List<String>) JSONArray.toCollection(ja, String.class);
        String strResult = savePloy(name, describe, index, 2);

        return strResult.indexOf("成功") > -1 ? 1 : 0;
    }

    @Override
    public List<String> getTreeState(String rpIndex) {
        return rptDataMapper.getTreeState(rpIndex);
    }

    @Override
    @Transactional
    public int updateExcelPloy(String name, String describe, String rdIndex, String globalRpIndex) {
        JSONArray ja = JSONArray.fromObject(rdIndex);
        List<String> index = (List<String>) JSONArray.toCollection(ja, String.class);
        String strResult = updatePloy(globalRpIndex, name, describe, index, 2);
        return strResult.indexOf("成功") > -1 ? 1 : 0;
    }

    @Override
    @Transactional
    public int deleteExcelPloy(String rpIndex) {
        RptPloy rpp = rptPloyMapper.selectByPrimaryKey(rpIndex);
        rpp.setState(Integer.valueOf("0"));

        RptAss ass = new RptAss();
        ass.setRpIndex(rpIndex);
        rptAssMapper.delete(ass);

        return rptPloyMapper.updateByPrimaryKey(rpp);
    }

    public PloyInfo loadPloy(String rpIndex) {
        PloyInfo result = new PloyInfo();

        RptPloy rpp = new RptPloy();
        List<RptAss> ploy = new ArrayList<>();
        List<String> rdIndex = new ArrayList<>();

        RptAss tmp = new RptAss();
        tmp.setRpIndex(rpIndex);

        rpp = rptPloyMapper.selectByPrimaryKey(rpIndex);
        ploy = rptAssMapper.select(tmp);

        for (int i = 0; i < ploy.size(); i++) {
            rdIndex.add(ploy.get(i).getRdIndex());
        }

        result.setRpName(rpp.getRpName());
        result.setRpDescribe(rpp.getRpDescribe());
        result.setRdIndex(rdIndex);

        return result;
    }
}