package com.lightinit.hsdataplatform.impl.admin;

import com.google.gson.Gson;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.entity.Dictionary;
import com.lightinit.hsdataplatform.mapper.*;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IDataCatelogService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

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

/**
 * @Author: sunxiang
 * @Date: 2018/5/30 16:16
 * @Description:
 **/
@Service
public class DataCatelogServiceImpl implements IDataCatelogService {

    @Autowired
    private DataCatelogMapper dataCatelogMapper;
    @Autowired
    private DataCatelogItemMapper dataCatelogItemMapper;
    @Autowired
    private DictionaryGroupMapper dictionaryGroupMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private SectorMapper sectorMapper;
    @Transactional
    @Override
    public ResultState<Long> addDataCatalog(DataCatelogAddModel dataCatelogAddModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
           /* DataCatelogWithBLOBs dataCatelogWithBLOBs = dataCatelogAddModel.getDataCatelogWithBLOBs();*/
           /* DataCatelogModel dataCatelogWithBLOBs = dataCatelogAddModel.getDataCatelogWithBLOBs();*/
            List<DataCatelogItem> dataCatelogItemList = dataCatelogAddModel.getDataCatelogItemList();
               if(StringUtils.isNotEmpty(dataCatelogAddModel.getDataName())){
                    dataCatelogAddModel.setCreatedAt(new Date());
                    ///////////////////////////////////////////////////////将model的属性赋予mapper类
                    DataCatelogWithBLOBs dataCatelogWithBLOBs1 = new DataCatelogWithBLOBs();
                    BeanUtils.copyProperties(dataCatelogAddModel,dataCatelogWithBLOBs1);
                    //////////////////////////////////////////////////////////
                    dataCatelogMapper.insert(dataCatelogWithBLOBs1);
                    if(dataCatelogItemList !=null && dataCatelogItemList.size()>0){
                        for (DataCatelogItem dataCatelogItem : dataCatelogItemList) {
                            if(StringUtils.isNotEmpty(dataCatelogItem.getItemName())){
                                dataCatelogItem.setDataCatelogId(dataCatelogWithBLOBs1.getId());
                                dataCatelogItem.setCreatedAt(new Date());
                                dataCatelogItem.setCreatedBy(dataCatelogAddModel.getCreatedBy());
                                dataCatelogItemMapper.insert(dataCatelogItem);
                            }
                        }
                    }
                }
            resultState.setData(dataCatelogAddModel.getId());
            return  resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("数据插入失败");
        return resultState;
    }

   /* @Override
    public List<DataCatelogListModel> queryList(DataCatelogSearchModel inputModel) { 待删除
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataCatelogExample example = new DataCatelogExample();
        DataCatelogExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(inputModel.getDataName())){
            criteria.andDataNameLike("%"+inputModel.getDataName()+"%");
        }
        if(StringUtils.isNotEmpty(inputModel.getDataSourceType())){
            criteria.andDataSourceLike("%"+inputModel.getDataSourceType()+"%");
        }
        if(inputModel.getSupplier()!=null){
            criteria.andSupplierEqualTo(inputModel.getSupplier());
        }
        example.setPage(inputModel.getPage());
        List<DataCatelogWithBLOBs> dataCatelogWithBLOBs = dataCatelogMapper.selectByExampleWithBLOBs(example);
        ArrayList<DataCatelogListModel> list = new ArrayList<>();
        DataCatelogListModel dataCatelogListModel = null;
        for (DataCatelogWithBLOBs dataCatelogWithBLOB : dataCatelogWithBLOBs) {
            dataCatelogListModel=new DataCatelogListModel();
            BeanUtils.copyProperties(dataCatelogWithBLOB,dataCatelogListModel);
            list.add(dataCatelogListModel);
        }
        return  list;
    }*/
   @Override
   public List<DataCatelogListModel> getDataCatelogList(DataCatelogSearchModel inputModel){
       if(inputModel.getCatelogName()!=null && inputModel.getCatelogName().length()<2){
           inputModel.setCatelogName(null);
       }
       return dataCatelogMapper.getDataCatelogList(inputModel);
   }

    @Override
    public long getDataCatelogListCount(DataCatelogSearchModel inputModel) {
        if(inputModel.getCatelogName()!=null && inputModel.getCatelogName().length()<2){
            inputModel.setCatelogName(null);
        }
        return dataCatelogMapper.getDataCatelogListCount(inputModel);
    }



    /*
    *@Description
    *@Param id：是数据目录id，删除会连字表所有与该id管理删除掉
    *@Date 2018/5/31
    *@return
    **/
    @Transactional
    @Override
    public ResultState<Long> delete(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            DataCatelogItemExample example = new DataCatelogItemExample();
            DataCatelogItemExample.Criteria criteria = example.createCriteria();
            criteria.andDataCatelogIdEqualTo(id);
            List<DataCatelogItem> dataCatelogItems = dataCatelogItemMapper.selectByExample(example);
            if(dataCatelogItems !=null && dataCatelogItems.size()>0){
                for (DataCatelogItem dataCatelogItem : dataCatelogItems) {
                    dataCatelogItemMapper.deleteByPrimaryKey(dataCatelogItem.getId());
                }
            }
            dataCatelogMapper.deleteByPrimaryKey(id);
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("数据插入失败");
        return resultState;
    }

    @Override
    public DataCatelogAddModel queryOne(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataCatelogAddModel dataCatelogAddModel = new DataCatelogAddModel();
        //通过BeanUtils工具类，复制属性
        DataCatelogWithBLOBs dataCatelogWithBLOBs = dataCatelogMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(dataCatelogWithBLOBs,dataCatelogAddModel);
        DataCatelogItemExample example = new DataCatelogItemExample();
        DataCatelogItemExample.Criteria criteria = example.createCriteria();
        criteria.andDataCatelogIdEqualTo(id);
        List<DataCatelogItem> dataCatelogItems = dataCatelogItemMapper.selectByExample(example);
        List<DataCatelogItem> list= new ArrayList<>();
        DataCatelogItem dataCatelogItem=null;
        for (DataCatelogItem  item: dataCatelogItems) {
            dataCatelogItem=new DataCatelogItem();
            BeanUtils.copyProperties(item,dataCatelogItem);
            list.add(dataCatelogItem);
        }
        dataCatelogAddModel.setDataCatelogItemList(list);
        return dataCatelogAddModel;
    }

    @Transactional
    @Override
    public ResultState<Long> updateDataCatalog(DataCatelogAddModel dataCatelogAddModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            List<Long> dataCatelogItemIds = dataCatelogItemMapper.getDataCatelogItemIds(dataCatelogAddModel.getId());
            //删除所有id
            if(dataCatelogItemIds !=null && dataCatelogItemIds.size()>0){
                for (Long dataCatelogItemId : dataCatelogItemIds) {
                    dataCatelogItemMapper.deleteByPrimaryKey(dataCatelogItemId);
                }
            }
            //添加
            List<DataCatelogItem> dataCatelogItemList = dataCatelogAddModel.getDataCatelogItemList();
            if(dataCatelogItemList !=null && dataCatelogItemList.size()>0){
                for (DataCatelogItem dataCatelogItem : dataCatelogItemList) {
                    //后台判断dataCatelogItem的值不为null（前端没有判断list[]可能为0，3，2为null）
                    if (StringUtils.isBlank(dataCatelogItem.getItemName())) {
                        continue;
                    }
                    dataCatelogItem.setDataCatelogId(dataCatelogAddModel.getId());
                    dataCatelogItemMapper.insert(dataCatelogItem);
                }
            }
            //更新
            DataCatelogWithBLOBs dataCatelogWithBLOBs1 = new DataCatelogWithBLOBs();
            BeanUtils.copyProperties(dataCatelogAddModel,dataCatelogWithBLOBs1);
            DataCatelogWithBLOBs dataCatelogWithBLOBs = dataCatelogMapper.selectByPrimaryKey(dataCatelogWithBLOBs1.getId());
            dataCatelogWithBLOBs1.setCreatedAt(dataCatelogWithBLOBs.getCreatedAt());
            dataCatelogMapper.updateByPrimaryKeyWithBLOBs(dataCatelogWithBLOBs1);

            /*DataCatelogWithBLOBs dataCatelogWithBLOBs = dataCatelogAddModel.getDataCatelogWithBLOBs();*/
           /* DataCatelogModel dataCatelogWithBLOBs = dataCatelogAddModel.getDataCatelogWithBLOBs();*/
           /* if(dataCatelogItemList !=null && dataCatelogItemList.size()>0){
                for (DataCatelogItem dataCatelogItem : dataCatelogItemList) {
                    //后台判断dataCatelogItem的值不为null（前端没有判断list[]可能为0，3，2为null）
                    if(StringUtils.isBlank(dataCatelogItem.getItemName())){
                        continue;
                    }
                    //通过判断id是否为null，来判断是否是新加数据：新：id为null--->添加到dataCatelogItem表中
                    if(dataCatelogItem.getId()==null){
                        dataCatelogItem.setDataCatelogId(dataCatelogAddModel.getId());
                        dataCatelogItemMapper.insert(dataCatelogItem);
                        continue;
                    }
                    //判断前端传来的数据是否删除了dataCatelogItem条目：与数据库中dataCatelogItem表中对比。不包含--->删除数据库中的值
                    if(dataCatelogItemIds.contains(dataCatelogItem.getId())){
                        dataCatelogItemMapper.updateByPrimaryKeySelective(dataCatelogItem);
                        dataCatelogItemIds.remove(dataCatelogItem.getId());
                    }
                }
                for (Long dataCatelogItemId : dataCatelogItemIds) {
                    dataCatelogItemMapper.deleteByPrimaryKey(dataCatelogItemId);
                }
            }
            ////////////////////////////////////////////////////
            DataCatelogWithBLOBs dataCatelogWithBLOBs1 = new DataCatelogWithBLOBs();
            BeanUtils.copyProperties(dataCatelogAddModel,dataCatelogWithBLOBs1);
            ////////////////////////////////////////////////////
            dataCatelogMapper.updateByPrimaryKeySelective(dataCatelogWithBLOBs1);*/
            return resultState;
        } catch (BeansException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("修改失败");
        return resultState;
    }

    @Override
    public List<InfomationResourceIdAndNameModel> queryInformationResourceTypeByDicMap(LinkedHashMap<String, String> dicMap) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ArrayList<String> list = new ArrayList<>();
        Set<String> keySet = dicMap.keySet();
        for(String key:keySet){
            list.add(key);
        }
        return dictionaryGroupMapper.queryInformationResourceTypeByDicMap(list);
    }

    @Override
    public List<InfomationResourceIdAndNameModel> queryInfoStyle(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DictionaryExample dictionaryExample = new DictionaryExample();
        dictionaryExample.createCriteria().andGroupIdEqualTo(id);
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(dictionaryExample);
        ArrayList<InfomationResourceIdAndNameModel> infomationResourceIdAndNameModels = new ArrayList<>();
        InfomationResourceIdAndNameModel infomationResourceIdAndNameModel = null;
        for (Dictionary dictionary : dictionaries) {
            infomationResourceIdAndNameModel = new InfomationResourceIdAndNameModel();
            infomationResourceIdAndNameModel.setId(dictionary.getId());
            infomationResourceIdAndNameModel.setGroupName(dictionary.getDicName());
            infomationResourceIdAndNameModels.add(infomationResourceIdAndNameModel);
        }
        return infomationResourceIdAndNameModels;
    }

    ////////////////////////////新增视图效果
    @Override
    public ResultState getAllDataToView() {
        ResultState resultState = new ResultState();
        List<SectorDataStaticsModel> list = dataCatelogMapper.getAllDataToView();
        String data="{\"name\":\"数据图谱\",\"children\":";
        Gson gson = new Gson();
        String str = gson.toJson(list);
        data+=str+"}";
        resultState.setData(data);
        return resultState;
    }

    @Override
    public ResultState getDataById(Long id) {
        ResultState resultState = new ResultState();
       /* List<SectorDataStaticsModel> list = dataCatelogMapper.getDataById(id);
        String data="{\"name\":\""+list.get(0).getSectorName()+"\",\"children\":";
        Gson gson = new Gson();
        String str = gson.toJson(list);
        data+=str+"}";
        resultState.setData(data);
        return resultState;*/
        Gson gson = new Gson();
        List<SectorDataStaticsModel> list = dataCatelogMapper.getDataById(id);
        String data="{\"name\":\""+list.get(0).getSectorName()+"\",\"value\":\"v\",\"children\":[";
        for (int i=0;i<list.size();i++) {
            List<SectorChirdrenModel> children=dataCatelogMapper.getChildrenByDataName(list.get(i).getName());
            list.get(i).setChildren(children);
            String str = gson.toJson(list.get(i));
            data+=str;
            if(i!=list.size()-1){
                data+=",";
            }
        }
        data+="]}";
        resultState.setData(data);
        return resultState;
    }


    @Resource(name="txManager")
    private DataSourceTransactionManager transactionManager;
    @Override
    public ResultState parseExcel(XSSFSheet sheetAt){
        //手动开启事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物传递性
        ResultState resultState = new ResultState();
        TransactionStatus status=null;
        int count=0;//计算是否导入成功
        for (int i = 0; i < sheetAt.getPhysicalNumberOfRows(); i++) {
            try {
                if(i<3){
                    continue;
                }
                Row row =sheetAt.getRow(i);
                if(StringUtils.isEmpty(row.getCell(0).getStringCellValue())){
                    continue;
                }
                status = transactionManager.getTransaction(def);
                row.getCell(0).setCellType(CellType.STRING);
                String stringCellValue0 = row.getCell(0).getStringCellValue(); // 第一列数据
                row.getCell(2).setCellType(CellType.STRING);
                String stringCellValue2 = row.getCell(2).getStringCellValue();
                row.getCell(3).setCellType(CellType.STRING);
                String stringCellValue3 = row.getCell(3).getStringCellValue();
                row.getCell(5).setCellType(CellType.STRING);
                String stringCellValue5 = row.getCell(5).getStringCellValue();
                row.getCell(6).setCellType(CellType.STRING);
                String stringCellValue6 = row.getCell(6).getStringCellValue();
                row.getCell(7).setCellType(CellType.STRING);
                String stringCellValue7 = row.getCell(7).getStringCellValue();
                row.getCell(8).setCellType(CellType.STRING);
                String stringCellValue8 = row.getCell(8).getStringCellValue();
                row.getCell(15).setCellType(CellType.STRING);
                String stringCellValue10 = row.getCell(15).getStringCellValue();
                row.getCell(16).setCellType(CellType.STRING);
                String stringCellValue11 = row.getCell(16).getStringCellValue();
                row.getCell(17).setCellType(CellType.STRING);
                String stringCellValue12 = row.getCell(17).getStringCellValue();
                row.getCell(18).setCellType(CellType.STRING);
                String stringCellValue13 = row.getCell(18).getStringCellValue();
                row.getCell(19).setCellType(CellType.STRING);
                String stringCellValue14 = row.getCell(19).getStringCellValue();
                row.getCell(20).setCellType(CellType.STRING);
                String stringCellValue15 = row.getCell(20).getStringCellValue();
                row.getCell(21).setCellType(CellType.STRING);
                String stringCellValue16 = row.getCell(21).getStringCellValue();
                row.getCell(22).setCellType(CellType.STRING);
                String stringCellValue17 = row.getCell(22).getStringCellValue();
                row.getCell(23).setCellType(CellType.STRING);
                String stringCellValue18 = row.getCell(23).getStringCellValue();
                row.getCell(24).setCellType(CellType.STRING);
                String stringCellValue19 = row.getCell(24).getStringCellValue();
                row.getCell(25).setCellType(CellType.STRING);
                String stringCellValue20 = row.getCell(25).getStringCellValue();

                DataCatelogItem dataCatelogItem = new DataCatelogItem();
                dataCatelogItem.setItemName(StringUtils.isEmpty(stringCellValue10)?null:stringCellValue10);//信息项名称
                dataCatelogItem.setItemType(StringUtils.isEmpty(stringCellValue11)?null:stringCellValue11);//数据项类型
                dataCatelogItem.setItemLength(StringUtils.isEmpty(stringCellValue12)?null:stringCellValue12);//数据长度
                dataCatelogItem.setShareType(StringUtils.isEmpty(stringCellValue13)?null:stringCellValue13);//共享类型
                dataCatelogItem.setShareCondition(StringUtils.isEmpty(stringCellValue14)?null:stringCellValue14);//共享条件
                dataCatelogItem.setShareMethodType(StringUtils.isEmpty(stringCellValue15)?null:stringCellValue15);//共享方式分类
                dataCatelogItem.setShareMethodCategory(StringUtils.isEmpty(stringCellValue16)?null:stringCellValue16);//共享方式类型
                dataCatelogItem.setIsOpen("是".equals(stringCellValue17)?(byte)1:0);//是否向社会开放
                dataCatelogItem.setOpenCondition(StringUtils.isEmpty(stringCellValue18)?null:stringCellValue18);//开放条件

                //查找是否已经有“信息资源名称”
                DataCatelogExample dataCatelogExample = new DataCatelogExample();
                dataCatelogExample.createCriteria().andDataNameEqualTo(stringCellValue0);
                List<DataCatelog> dataCatelogList = dataCatelogMapper.selectByExample(dataCatelogExample);
                Long dataCatelogId=null;
                if(dataCatelogList!=null && dataCatelogList.size()>0){
                    dataCatelogId=dataCatelogList.get(0).getId();
                }else{
                    DataCatelogWithBLOBs dataCatelog = new DataCatelogWithBLOBs();
                    dataCatelog.setDataName(stringCellValue0);//信息资源名称
                    //查询提供方id
                    SectorExample sectorExample = new SectorExample();
                    sectorExample.createCriteria().andSectorNameLike("%"+stringCellValue2+"%");
                    List<Sector> sectors = sectorMapper.selectByExample(sectorExample);
                    Long sectorId=null;
                    if(sectors!=null && sectors.size()>0){
                        sectorId=sectors.get(0).getId();
                    }
                    dataCatelog.setSupplier(sectorId);//信息资源提供方

                    //查询方内部部门id
                    SectorExample sectorExample1 = new SectorExample();
                    sectorExample1.createCriteria().andSectorNameLike("%"+stringCellValue3+"%");
                    List<Sector> sectors1 = sectorMapper.selectByExample(sectorExample1);
                    Long sector1Id=null;
                    if(sectors1!=null && sectors1.size()>0){
                        sector1Id=sectors1.get(0).getId();
                    }
                    dataCatelog.setSupplierDept(sector1Id);//提供方内部部门
                    dataCatelog.setDataSummary(StringUtils.isEmpty(stringCellValue5)?null:stringCellValue5);//信息资源摘要
                    //dataCatelog.setDataSourceType(StringUtils.isEmpty(stringCellValue6)?null:stringCellValue6);//信息资源格式分类
                    //dataCatelog.setDataSource(StringUtils.isEmpty(stringCellValue7)?null:stringCellValue7);//信息资源格式类型
                    dataCatelog.setDataSourceOther(StringUtils.isEmpty(stringCellValue8)?null:stringCellValue8);//其他类型资源格式描述
                    dataCatelog.setUpdateCycle(StringUtils.isEmpty(stringCellValue19)?null:stringCellValue19);//更新周期
                    dataCatelog.setPublishTime(new Date());//发布时间
                    dataCatelog.setCreatedAt(new Date());
                    //插入
                    dataCatelogMapper.insert(dataCatelog);
                    dataCatelogId=dataCatelog.getId();
                }
                dataCatelogItem.setDataCatelogId(dataCatelogId);
                dataCatelogItem.setCreatedAt(new Date());
                dataCatelogItemMapper.insert(dataCatelogItem);
                //提交事务
                transactionManager.commit(status);
                count++;
            } catch (NumberFormatException e) {
               /* e.printStackTrace();*/
               if(status!=null){
                   transactionManager.rollback(status);
               }
            }
        }
        if(count<1){
            resultState.setStateCode(500);
        }
        return resultState;
    }
}
