package com.lightinit.hsdataplatformresdir.impl.admin;

import com.lightinit.hsdataplatformresdir.dictionary.DicDataPublishState;
import com.lightinit.hsdataplatformresdir.entity.*;
import com.lightinit.hsdataplatformresdir.mapper.PublishInfoMapper;
import com.lightinit.hsdataplatformresdir.mapper.PublishSettingMapper;
import com.lightinit.hsdataplatformresdir.mapper.ResourceMapper;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import com.lightinit.hsdataplatformresdir.model.admin.DataPublishDetailModel;
import com.lightinit.hsdataplatformresdir.model.admin.DataPublishListModel;
import com.lightinit.hsdataplatformresdir.model.admin.DataPublishSearchModel;
import com.lightinit.hsdataplatformresdir.model.admin.ResourceDataRegisterDataModel;
import com.lightinit.hsdataplatformresdir.service.admin.IDataPublishMgrService;
import com.lightinit.hsdataplatformresdir.service.admin.IResourceDataRegisterService;
import com.lightinit.hsdataplatformresdir.spring.DynamicDataContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: sunxiang
 * @Date: 2018/6/3 16:13
 * @Description:
 **/
@Service
public class DataPublishMgrServiceImpl implements IDataPublishMgrService {

    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private PublishInfoMapper publishInfoMapper;
    @Autowired
    private PublishSettingMapper publishSettingMapper;
    @Autowired
    private IResourceDataRegisterService resourceDataRegisterService;

    //判断是否是admin,是：将id置为null;
    private DataPublishSearchModel getRolecodeByUserId(DataPublishSearchModel inputModel){
        List<String> RolecodeList=publishInfoMapper.getRolecodeByUserId(inputModel.getUserId());
        for (String s : RolecodeList) {
            if(s.equals("admin")){
                inputModel.setUserId(null);
                break;
            }
        }
        return inputModel;
    }
    @Override
    public List<DataPublishListModel> queryList(DataPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel= getRolecodeByUserId(inputModel);
        return publishInfoMapper.queryList(inputModel);
    }

    @Override
    public long queryListCount(DataPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel= getRolecodeByUserId(inputModel);
        return publishInfoMapper.queryListCount(inputModel);
    }

    @Override
    public List<DataPublishListModel> queryPublishResourceDataList(DataPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel= getRolecodeByUserId(inputModel);
        return resourceMapper.queryPublishResourceDataList(inputModel);
    }

    @Override
    public long queryCount(DataPublishSearchModel inputModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        inputModel= getRolecodeByUserId(inputModel);
        return resourceMapper.queryCount(inputModel);
    }

    @Transactional
    @Override
    public ResultState<Long> publishResourceDetailAdd(DataPublishDetailModel dataPublishDetailModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            PublishInfoWithBLOBs publishInfoWithBLOBs = new PublishInfoWithBLOBs();
            Long sourceId=dataPublishDetailModel.getId();
            dataPublishDetailModel.setId(null);
            BeanUtils.copyProperties(dataPublishDetailModel,publishInfoWithBLOBs);
            publishInfoWithBLOBs.setResourceId(sourceId);
            publishInfoWithBLOBs.setCreatedAt(new Date());
            if(dataPublishDetailModel.getParam()==1){
                publishInfoWithBLOBs.setPublishState(DicDataPublishState.PENDING);
            }else{
                publishInfoWithBLOBs.setPublishState(DicDataPublishState.DRAFT);
            }
            publishInfoMapper.insert(publishInfoWithBLOBs);
            //插入数据到publish_setting表
            List<PublishSetting> publishSettingList = dataPublishDetailModel.getPublishSettingList();
            if(publishSettingList !=null && publishSettingList.size()>0){
                PublishSetting publishSettingEntry =null;
                for (PublishSetting publishSetting : publishSettingList) {
                    if(StringUtils.isEmpty(publishSetting.getPackageName())){   //套餐名称必填项，这里通过名称判断角标为空的剔除
                        continue;
                    }
                    publishSettingEntry=new PublishSetting();
                    BeanUtils.copyProperties(publishSetting,publishSettingEntry);
                    publishSetting.setPublishInfoId(publishInfoWithBLOBs.getId());
                    publishSetting.setCreatedAt(new Date());
                    publishSettingMapper.insert(publishSetting);
                }
            }
            return resultState;
        } catch (BeansException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("数据插入失败");
        return resultState;
    }

    /*
    *@Description 删除相应的publish_info和publish_setting表
    *@Param 
    *@Date 2018/6/5
    *@return 
    **/
    @Transactional
    @Override
    public ResultState<Long> delete(long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            PublishSettingExample publishSettingExample1 = new PublishSettingExample();
            PublishSettingExample.Criteria criteria = publishSettingExample1.createCriteria();
            criteria.andPublishInfoIdEqualTo(id);
            List<PublishSetting> publishSettings = publishSettingMapper.selectByExample(publishSettingExample1);
            if(publishSettings !=null && publishSettings.size()>0){
                for (PublishSetting  publishSetting: publishSettings) {
                    publishSettingMapper.deleteByPrimaryKey(publishSetting.getId());
                }
            }
            publishInfoMapper.deleteByPrimaryKey(id);
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("数据删除失败");
        return resultState;
    }

    /*
    *@Description 在发布页面查询某一条的详细情况
    *@Param id：是publish_info表的id
    *@Date 2018/6/5
    *@return 
    **/
    @Override
    public DataPublishDetailModel queryPublishInfoOne(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataPublishDetailModel dataPublishDetailModel = new DataPublishDetailModel();
        PublishInfoWithBLOBs publishInfoWithBLOBs = publishInfoMapper.selectByPrimaryKey(id);
        ResourceDataRegisterDataModel resourceDataRegisterDataModel = resourceDataRegisterService.queryOne(publishInfoWithBLOBs.getResourceId());
        BeanUtils.copyProperties(resourceDataRegisterDataModel,dataPublishDetailModel);
        BeanUtils.copyProperties(publishInfoWithBLOBs,dataPublishDetailModel);//复制publish_info表属性
        PublishSettingExample publishSettingExample = new PublishSettingExample();
        PublishSettingExample.Criteria criteria = publishSettingExample.createCriteria();
        criteria.andPublishInfoIdEqualTo(id).andDeletedAtIsNull();
        List<PublishSetting> publishSettings = publishSettingMapper.selectByExampleWithBLOBs(publishSettingExample);
        dataPublishDetailModel.setPublishSettingList(publishSettings);
        return dataPublishDetailModel;
    }

    @Transactional
    @Override
    public ResultState updatePublishDataDetial(DataPublishDetailModel dataPublishDetailModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState<>();
        try {
            Long publishInfoId = dataPublishDetailModel.getId();
            PublishSettingExample publishSettingExample = new PublishSettingExample();
            publishSettingExample.createCriteria().andPublishInfoIdEqualTo(publishInfoId);
            List<Long> publishSettingsInDataBaseList = publishSettingMapper.selectPublishSettingByPublishInfoId(publishInfoId);
            List<PublishSetting> list = dataPublishDetailModel.getPublishSettingList();
            PublishSetting publishSettingEntry=null;
            ArrayList<Long> idList = new ArrayList<>();
            if(list !=null && list.size()>0) {
                for (PublishSetting publishSetting : list) {
                    if(StringUtils.isEmpty(publishSetting.getPackageName())){    //套餐名称必填项，这里通过名称判断角标为空的剔除
                        continue;
                    }
                    if(publishSetting.getId() ==null|| publishSetting.getId()==0){  //前端默认添加数据id为0
                        publishSettingEntry=new PublishSetting();
                        BeanUtils.copyProperties(publishSetting,publishSettingEntry);
                        publishSetting.setPublishInfoId(publishInfoId);
                        publishSettingMapper.insert(publishSetting);
                    }else{
                        publishSettingEntry=new PublishSetting();
                        BeanUtils.copyProperties(publishSetting,publishSettingEntry);
                        publishSetting.setPublishInfoId(publishInfoId);
                        publishSettingMapper.updateByPrimaryKeySelective(publishSettingEntry);
                        idList.add(publishSetting.getId());
                    }
                }
            }
            //用前端传入的集合id与数据库中的集合id比较，前端不包含的id即为删除的id--->更新删除时间和删除人
            if(publishSettingsInDataBaseList!=null && publishSettingsInDataBaseList.size()>0){
                for (Long aLong : publishSettingsInDataBaseList) {
                    if(! idList.contains(aLong)){
                        publishSettingEntry=new PublishSetting();
                        publishSettingEntry.setId(aLong);
                        publishSettingEntry.setDeletedAt(new Date());
                        publishSettingEntry.setDeletedBy(dataPublishDetailModel.getDeleteById());
                        publishSettingMapper.updateByPrimaryKeySelective(publishSettingEntry);
                    }
                }
            }
            PublishInfoWithBLOBs publishInfoWithBLOBs = new PublishInfoWithBLOBs();
            publishInfoWithBLOBs.setId(publishInfoId);
            publishInfoWithBLOBs.setOpenCondition(dataPublishDetailModel.getOpenCondition());
            publishInfoWithBLOBs.setShareCondition(dataPublishDetailModel.getShareCondition());
            publishInfoWithBLOBs.setResourceImg(dataPublishDetailModel.getResourceImg());
            publishInfoWithBLOBs.setAuditResult(null);
            publishInfoWithBLOBs.setAuditedAt(null);
            publishInfoWithBLOBs.setCreatedAt(new Date());
            if(dataPublishDetailModel.getParam()==1){
                publishInfoWithBLOBs.setPublishState(DicDataPublishState.PENDING);
            }else{
                publishInfoWithBLOBs.setPublishState(DicDataPublishState.DRAFT);
            }
            publishInfoMapper.updateByPrimaryKeySelectiveExcludResourceId(publishInfoWithBLOBs);
            resultState.setMsg("编辑成功");
            return  resultState;
        } catch (BeansException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("编辑失败");
        return resultState;

    }

    @Transactional
    @Override
    public ResultState offPublishData(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            PublishInfoWithBLOBs publishInfoWithBLOBs = new PublishInfoWithBLOBs();
            publishInfoWithBLOBs.setId(id);
            publishInfoWithBLOBs.setPublishState(DicDataPublishState.OFFLINE);
            publishInfoMapper.updateByPrimaryKeySelective(publishInfoWithBLOBs);
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("下架失败");
        return resultState;
    }
}
