package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.common.OrderNumberUtils;
import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.mapper.*;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IDataService;
import com.lightinit.hsdataportal.spring.DynamicDataContextHolder;
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.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: sunxiang
 * @Date: 2018/6/9 16:58
 * @Description:
 **/
@Service
public class DataServiceImpl implements IDataService {

    @Autowired
    private PublishInfoMapper publishInfoMapper;
    @Autowired
    private ResourceAuthMapper resourceAuthMapper;
    @Autowired
    private ResourceFollowMapper resourceFollowMapper;
    @Autowired
    private OfflineConferenceMapper offlineConferenceMapper;
    @Autowired
    private PublishSettingMapper publishSettingMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    ResourceViewTimesMapper resourceViewTimesMapper;

    @Override
    public DataDetailModel getDataDetail(Long id, Long userId, int flag) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataDetailModel dataDetailModel=null;
        DataSearchModel dataSearchModel = new DataSearchModel();
        dataSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataSearchModel.setPublisthSettingId(id);
        if(flag==1){
            dataSearchModel.setPlatformType(DicPlatformType.OPEN);
            dataSearchModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        }else{
            //共享平台
            dataSearchModel.setPlatformType(DicPlatformType.SHARE);
            dataSearchModel.setShareType(DicResourceShareType.NOT_SHARE);
        }
        dataDetailModel=publishInfoMapper.getDataDetail(dataSearchModel);
        if(dataDetailModel !=null){
            //dataDetailModel.setOpenType(null);
            //Long dataFollowTotalCount = publishInfoMapper.getDataFollowTotalCount(id);
            //dataDetailModel.setFollowTotalCount(dataFollowTotalCount);
            //更新浏览次数
            try {
                if(resourceViewTimesMapper.selectByPrimaryKey(dataDetailModel.getResourceId())==null){
                    resourceViewTimesMapper.insertViews(dataDetailModel.getResourceId(),1);
                }else{
                    resourceViewTimesMapper.updateViewTimes(dataDetailModel.getResourceId());
                }
            } catch (Exception e) {
                e.getMessage();
                e.printStackTrace();
            }
        }
        if(dataDetailModel !=null && userId !=null){
            ResourceFollowExample resourceFollowExample = new ResourceFollowExample();
            resourceFollowExample.createCriteria().andFollowerIdEqualTo(userId).andPublishSettingIdEqualTo(dataDetailModel.getPublishSettingId()).andPlatformTypeEqualTo(dataSearchModel.getPlatformType()) ;
            List<ResourceFollow> resourceFollows = resourceFollowMapper.selectByExample(resourceFollowExample);
            if(resourceFollows !=null && resourceFollows.size()>0 ){
                dataDetailModel.setResourceFollowId(resourceFollows.get(0).getId());
            }
        }
        return dataDetailModel;
    }
    @Override
    public List<DataListModel> getDataIndex(DataSearchModel inputModel, int flag) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        //1：开放平台    2：共享平台
        List<DataListModel> list=null;
        inputModel.setResourceType(DicResourceType.DATA);
        inputModel.setPublishState(DicPublishApiState.PUBLISH);
        if(flag==1){
            inputModel.setShareType(null);
            inputModel.setPlatformType(DicPlatformType.OPEN);
            inputModel.setOpenType(DicResourceOpenType.NOT_OPEN);
            list=publishInfoMapper.getDataOpenIndex(inputModel);//方法名待改
        }else if(flag==2){
            inputModel.setOpenType(null);
            inputModel.setPlatformType(DicPlatformType.SHARE);
            inputModel.setMoreCondition(inputModel.getShareType());
            inputModel.setShareType(DicResourceShareType.NOT_SHARE);
            list=publishInfoMapper.getDataOpenIndex(inputModel);
        }
        return list;
    }

    @Override
    public Long getIndexCount(DataSearchModel inputModel, int flag) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        //1：开放平台    2：共享平台
        inputModel.setResourceType(DicResourceType.DATA);
        inputModel.setPublishState(DicPublishApiState.PUBLISH);
        Long count=null;
        if(flag==1){
            inputModel.setOpenType(DicResourceOpenType.NOT_OPEN);
            count=publishInfoMapper.getIndexCount(inputModel);
        }else if(flag==2){
            inputModel.setShareType(DicResourceShareType.NOT_SHARE);
            count=publishInfoMapper.getIndexCount(inputModel);
        }
        return count;
    }
    //开放平台
    @Override
    public DataApplyPriceModel getDataOpenType(Long id) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataOpenSearchModel dataOpenSearchModel = new DataOpenSearchModel();
        dataOpenSearchModel.setId(id);
        dataOpenSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataOpenSearchModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        DataApplyPriceModel dataApplyPriceModel =publishInfoMapper.getDataOpenType(dataOpenSearchModel);
        return dataApplyPriceModel;
    }

    //共享平台
    public DataApplyPriceModel getDateShareType(Long id){
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataOpenSearchModel dataOpenSearchModel = new DataOpenSearchModel();
        dataOpenSearchModel.setId(id);
        dataOpenSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataOpenSearchModel.setShareType(DicResourceShareType.NOT_SHARE);
        DataApplyPriceModel dataApplyPriceModel =publishInfoMapper.getDataOpenType(dataOpenSearchModel);
        return dataApplyPriceModel;
    }

    @Override
    @Transactional
    public ResultState insertDataApply(MyDataShareListModel inputModel, String type, int paramer) {//type:无条件开放（免费/收费）;
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);                //paramer:无条件/有条件
        ResultState resultState = new ResultState<>();
        ResourceAuth resourceAuth=null;
        try {
            if(paramer==1){//   无条件开放（免费/收费）/无条件共享
                //插入order表
                Order order = new Order() ;
                order.setUserId(inputModel.getUserORAdminId()) ;
                order.setOrderTime(new Date()) ;
                String orderNumer=OrderNumberUtils.generate();//此次交易生成的订单号。确定生成的是数字
                resultState.setData(orderNumer);
                order.setOrderNumber(orderNumer);
                order.setOrderAmount(inputModel.getPackagePrice());
                order.setRemark(inputModel.getDescription());
                order.setCreatedAt(new Date());
                if(inputModel.getPlatformType().equals(DicPlatformType.OPEN)){//选择平台类型
                    order.setPlatformType(DicPlatformType.OPEN);
                    if(DicPublishSettingChargeMethod.FREE.equals(type)){
                        order.setOrderState(DicOrderState.PAY_SUCCESS);//已付款
                        resultState.setMsg(DicOrderState.PAY_SUCCESS);
                    } else{
                        order.setOrderState(DicOrderState.PAY_WAIT);//待支付
                        resultState.setMsg(DicOrderState.PAY_WAIT);
                    }
                }else{
                    order.setPlatformType(DicPlatformType.SHARE);
                    order.setOrderState(DicOrderState.PAY_SUCCESS);//已付款
                }
                orderMapper.insert(order);
                //插入Resource_auth表
                //if(null ==inputModel.getResourceAuthId()){//如果是‘授权后的申请，不需要再插入申请表中’ 此功能目前不做//}
                resourceAuth = new ResourceAuth();
                resourceAuth.setPlatformType(inputModel.getPlatformType());
                resourceAuth.setPublishInfoId(inputModel.getPublishInfoId());
                resourceAuth.setPublishSettingId(inputModel.getPublishSettingId());
                resourceAuth.setApplier(inputModel.getUserORAdminId());
                resourceAuth.setApplyTime(new Date());
                resourceAuth.setAuthState(DicResourceAuthAuditResult.AUTHORIZATION_SUCCESS);//授权成功
                resourceAuth.setAuditResult(DicResourceAuditResult.APPROVED);
                resourceAuthMapper.insert(resourceAuth);

                //插入order_goods表
                OrderGoods orderGoods = new OrderGoods() ;
                BeanUtils.copyProperties(inputModel,orderGoods);
               /* if(null !=inputModel.getResourceAuthId()){
                    orderGoods.setResourceAuthId(inputModel.getResourceAuthId());
                }else{
                    orderGoods.setResourceAuthId(resourceAuth.getId());
                } 此功能目前不做/*/
                orderGoods.setResourceAuthId(resourceAuth.getId());
                orderGoods.setResourceType(DicResourceType.DATA) ;
                orderGoods.setOrderId(order.getId());
                //orderGoods.setPublishSettingId(inputModel.getPublishSettingId());
                orderGoods.setCreatedAt(new Date());
                orderGoodsMapper.insert(orderGoods);
            }else{      //有条件开放/有条件共享
                resourceAuth = new ResourceAuth();
                resourceAuth.setApplier(inputModel.getUserORAdminId());
                resourceAuth.setPlatformType(inputModel.getPlatformType());
                resourceAuth.setPublishInfoId(inputModel.getPublishInfoId());
                resourceAuth.setPublishSettingId(inputModel.getPublishSettingId());
                resourceAuth.setApplyReason(inputModel.getApplyReason());
                resourceAuth.setApplyTime(new Date());
                resourceAuth.setAuthState(DicResourceAuthAuditResult.WAIT_AUTHORIZATION);//待授权
                resourceAuthMapper.insert(resourceAuth);
            }
            return resultState;
        } catch (BeansException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("申请失败");
        return resultState;
    }

    @Transactional
    @Override
    public ResultState<Long> follow(String openOrShare, Long id, Long userId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            ResourceFollow resourceFollow = new ResourceFollow();
            resourceFollow.setPlatformType(openOrShare);
            resourceFollow.setFollowerId(userId);
            resourceFollow.setPublishSettingId(id);
            resourceFollow.setCreatedAt(new Date());
            resourceFollowMapper.insert(resourceFollow);
            resultState.setData(resourceFollow.getId());//将关注后的id传入前台
            resultState.setMsg("关注成功！");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("关注失败");
        return resultState;
    }

    @Transactional
    @Override
    public ResultState delfollow(long id, Long loginUserId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            ResourceFollowExample resourceFollowExample = new ResourceFollowExample();
            resourceFollowExample.createCriteria().andFollowerIdEqualTo(loginUserId).andIdEqualTo(id);
            resourceFollowMapper.deleteByExample(resourceFollowExample);
            resultState.setMsg("取消关注成功！");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("取消关注失败");
        return resultState;
    }

    @Override
    public ResultState offlineConference(DataOfflineConferenceModel inputModel, Long userId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState resultState = new ResultState<>();
        try {
            OfflineConferenceWithBLOBs offlineConferenceWithBLOBs = new OfflineConferenceWithBLOBs();
            /*offlineConferenceWithBLOBs.setRequirement(inputModel.getRequirement());
            offlineConferenceWithBLOBs.setUsage(inputModel.getUsage());
            offlineConferenceWithBLOBs.setContact(inputModel.getContact());
            offlineConferenceWithBLOBs.setPhone(inputModel.getPhone());
            offlineConferenceWithBLOBs.setPublishSettingId(inputModel.getPublishSettingId());*/
            BeanUtils.copyProperties(inputModel,offlineConferenceWithBLOBs);
            offlineConferenceWithBLOBs.setOrderNumber(OrderNumberUtils.generate());
            offlineConferenceWithBLOBs.setSubmitTime(new Date());
            offlineConferenceWithBLOBs.setCreatedAt(new Date());
            offlineConferenceWithBLOBs.setUserId(userId);
            offlineConferenceMapper.insert(offlineConferenceWithBLOBs);
            resultState.setMsg("洽谈申请成功");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("洽谈申请失败");
        return resultState;
    }

    @Override
    public List<DataStructListModel> getDataStructreList(String platform) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataOpenSearchModel dataOpenSearchModel = new DataOpenSearchModel();
        if(DicPlatformType.OPEN.equals(platform)){
            dataOpenSearchModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        }else{
            dataOpenSearchModel.setShareType(DicResourceShareType.NOT_SHARE);
        }
        dataOpenSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataOpenSearchModel.setResourceType(DicResourceType.DATA);
        return publishInfoMapper.getDataStructreList(dataOpenSearchModel);
    }

    @Override
    public Long getSectorTotal(String platform) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataOpenSearchModel dataOpenSearchModel = new DataOpenSearchModel();
        if(DicPlatformType.OPEN.equals(platform)){
            dataOpenSearchModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        }else{
            dataOpenSearchModel.setShareType(DicResourceShareType.NOT_SHARE);
        }
        dataOpenSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataOpenSearchModel.setResourceType(DicResourceType.DATA);
        return publishInfoMapper.getSectorTotal(dataOpenSearchModel);
    }


    @Override
    public Long getSectorDataTotal(String platform) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataOpenSearchModel dataOpenSearchModel = new DataOpenSearchModel();
        if(DicPlatformType.OPEN.equals(platform)){
            dataOpenSearchModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        }else{
            dataOpenSearchModel.setShareType(DicResourceShareType.NOT_SHARE);
        }
        dataOpenSearchModel.setPublishState(DicDataPublishState.PUBLISHED);
        dataOpenSearchModel.setResourceType(DicResourceType.DATA);
        return publishInfoMapper.getSectorDataTotal(dataOpenSearchModel);
    }

    @Override
    public List<DataViewListModel> getDataViewList(String platform) {
        DataViewListModel dataViewListModel = new DataViewListModel();
        if(DicPlatformType.OPEN.equals(platform)){
            dataViewListModel.setOpenType(DicResourceOpenType.NOT_OPEN);
        }else{
            dataViewListModel.setShareType(DicResourceShareType.NOT_SHARE);
        }
        dataViewListModel.setCatelogType(DicResourceCatelogType.THEME);
        dataViewListModel.setType((byte)1);
        return publishInfoMapper.getDataViewList(dataViewListModel);
    }

}
