package com.lightinit.hsdataportal.impl;

import com.lightinit.hsdataportal.dictionary.*;
import com.lightinit.hsdataportal.entity.*;
import com.lightinit.hsdataportal.mapper.DataRequirementDataMapper;
import com.lightinit.hsdataportal.mapper.RequirementDataMapper;
import com.lightinit.hsdataportal.mapper.RequirementFollowMapper;
import com.lightinit.hsdataportal.mapper.RequirementMapper;
import com.lightinit.hsdataportal.model.*;
import com.lightinit.hsdataportal.service.IDataRequirementService;
import com.lightinit.hsdataportal.spring.DynamicDataContextHolder;
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/11 22:12
 * @Description:
 **/
@Service
public class DataRequirementServiceImpl implements IDataRequirementService {

    @Autowired
    private RequirementMapper requirementMapper;
    @Autowired
    private RequirementDataMapper requirementDataMapper;
    @Autowired
    private DataRequirementDataMapper dataRequirementDataMapper;
    @Autowired
    private RequirementFollowMapper requirementFollowMapper;

    @Transactional
    public ResultState<Long> addDataRequirement(DataRequirementAddModel dataRequirementAddModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            Requirement requirement = new Requirement();
            requirement.setRqrmntName(dataRequirementAddModel.getRqrmntName());
            requirement.setRqrmntType(DicRqrmntType.DATA);
            requirement.setRqrmntSummary(dataRequirementAddModel.getRqrmntSummary());
            requirement.setPlatformType(dataRequirementAddModel.getPlatformType());
            requirement.setRqrmntSource(DicRqrmntSourceType.OPEN);
            requirement.setRqrmntType(DicResourceType.DATA);
            requirement.setPublishBy(dataRequirementAddModel.getUserId());
            requirement.setCreatedAt(new Date());
            if(DicPlatformType.SHARE.equals(dataRequirementAddModel.getPlatformType())){
                if(dataRequirementAddModel.getSubOrTem()==1){
                    requirement.setRqrmntState(DicDataRequirementState.PENDING);
                }else{
                    requirement.setRqrmntState(DicShareDataRequirementState.WAITING);
                }
            }else{
                requirement.setRqrmntState(DicDataRequirementState.PENDING);
            }
            requirementMapper.insert(requirement);

            RequirementData requirementData = new RequirementData();
            requirementData.setId(requirement.getId());
            requirementData.setSectorId(dataRequirementAddModel.getSectorId());
            requirementData.setRqrmntSectorId(dataRequirementAddModel.getRqrmntSectorId());
            requirementData.setDataUses(dataRequirementAddModel.getDataUses());
            requirementData.setCreatedAt(new Date());
            requirementDataMapper.insertRequirementDataId(requirementData);

            DataRequirementData dataRequirementData =null;
            List<DataRequirementDataModel> dataRequirementDataList = dataRequirementAddModel.getDataRequirementDataList();
            if(dataRequirementDataList !=null && dataRequirementDataList.size()>0){
                for (DataRequirementDataModel data : dataRequirementDataList) {
                    if(data.getDataName()==null || data.getDataName().trim()==""){
                        continue;
                    }
                    dataRequirementData=new DataRequirementData();
                    dataRequirementData.setRqrmntId(requirement.getId());
                    dataRequirementData.setDataName(data.getDataName());
                    dataRequirementData.setDataItem(data.getDataItem());
                    dataRequirementData.setCreatedAt(new Date());
                    dataRequirementDataMapper.insert(dataRequirementData);
                }
                //TODO:这里应该将需求申请插入到“用户中心查看反馈状态”，未完成
            }
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("申请失败");
        return resultState;
    }


    @Override
    public List<Map<Long,String>> getSectorParentNames() {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        return requirementMapper.getSectorParentNames();
    }

    @Override
    public List<DataRequirementListModel> getDataRequirementList(DataRequirementSearchModel dataRequirementSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        dataRequirementSearchModel.setRqrmntState1(DicDataRequirementState.FEEDBACKED);
        dataRequirementSearchModel.setRqrmntState2(DicDataRequirementState.FEEDBACKING);
        dataRequirementSearchModel.setRqrmntType(DicResourceType.DATA);
        return requirementMapper.getDataRequirementList(dataRequirementSearchModel);
    }

    @Override
    public Long getDataRequirementCount(DataRequirementSearchModel dataRequirementSearchModel) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        dataRequirementSearchModel.setRqrmntState1(DicDataRequirementState.FEEDBACKED);
        dataRequirementSearchModel.setRqrmntState2(DicDataRequirementState.FEEDBACKING);
        dataRequirementSearchModel.setRqrmntType(DicResourceType.DATA);
        return requirementMapper.getDataRequirementCount(dataRequirementSearchModel);
    }

    @Override
    public DataRequirementDetailModel getDataRequirementDetail(Long id, Long userId, String openOrShareType) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataRequirementDetailModel dataRequirementDetailModel=null;
        DataRequirementSearchModel dataRequirementSearchModel = new DataRequirementSearchModel();
        dataRequirementSearchModel.setRqrmntState1(DicDataRequirementState.FEEDBACKED);
        dataRequirementSearchModel.setRqrmntState2(DicDataRequirementState.FEEDBACKING);
        dataRequirementSearchModel.setRqrmntId(id);
        if(DicPlatformType.OPEN.equals(openOrShareType)){
            dataRequirementSearchModel.setPlatformType(DicPlatformType.OPEN);
            dataRequirementSearchModel.setOpenType(DicPlatformType.OPEN);
        }else{
            //共享平台
            dataRequirementSearchModel.setPlatformType(DicPlatformType.SHARE);
            dataRequirementSearchModel.setShareType(DicPlatformType.SHARE);
        }
        dataRequirementDetailModel=requirementMapper.getDataRequirementDetail(dataRequirementSearchModel);
        if(dataRequirementDetailModel !=null){
            //更新浏览查看次数
            requirementMapper.updateViewTimes(id);

            DataRequirementDataExample dataRequirementDataExample = new DataRequirementDataExample();
            dataRequirementDataExample.createCriteria().andRqrmntIdEqualTo(id);
            List<DataRequirementData> dataRequirementDataList = dataRequirementDataMapper.selectByExample(dataRequirementDataExample);
            dataRequirementDetailModel.setDataRequirementDataList(dataRequirementDataList);
        }
        if(dataRequirementDetailModel !=null && userId !=null){
            RequirementFollowExample requirementFollowExample= new RequirementFollowExample();
            requirementFollowExample.createCriteria().andFollowerIdEqualTo(userId).andRqrmntIdEqualTo(id).andPlatformTypeEqualTo(dataRequirementSearchModel.getPlatformType()) ;
            List<RequirementFollow> requirementFollows = requirementFollowMapper.selectByExample(requirementFollowExample);
            if(requirementFollows !=null && requirementFollows.size()>0){
                dataRequirementDetailModel.setRqrmntFollowId(requirementFollows.get(0).getId());
            }
        }
        return dataRequirementDetailModel;
    }

    @Transactional
    @Override
    public ResultState<Long> follow(String openOrShare, Long id, Long userId) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            RequirementFollow requirementFollow= new RequirementFollow();
            requirementFollow.setPlatformType(openOrShare);
            requirementFollow.setFollowerId(userId);
            requirementFollow.setRqrmntId(id);
            requirementFollowMapper.insert(requirementFollow);
            resultState.setData(requirementFollow.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) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        ResultState<Long> resultState = new ResultState<>();
        try {
            requirementFollowMapper.deleteByPrimaryKey(id);
            resultState.setMsg("取消关注成功！");
            return resultState;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        }
        resultState.setStateCode(ResultStateCode.INVALID_DATA);
        resultState.setMsg("取消关注失败");
        return resultState;
    }

    @Override
    public List<DataRequirementListModel> getMore(DataRequirementSearchModel dataRequirementSearchModel,int pageNo) {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        dataRequirementSearchModel.setRqrmntState1(DicDataRequirementState.FEEDBACKED);
        dataRequirementSearchModel.setRqrmntState2(DicDataRequirementState.FEEDBACKING);
        dataRequirementSearchModel.setRqrmntType(DicResourceType.DATA);
        dataRequirementSearchModel.setFlag(0);//默认按时间查询
        BaseExample.Page page = new BaseExample.Page();
        page.setPageSize(5); //默认再显示五条数据
        page.setPageNo(pageNo);
        dataRequirementSearchModel.setPage(page);
        List<DataRequirementListModel> list=requirementMapper.getDataRequirementList(dataRequirementSearchModel);
        return list;
    }


}
