package com.lightinit.hsdataplatform.impl.admin;

import com.lightinit.hsdataplatform.common.ObjectMappingUtils;
import com.lightinit.hsdataplatform.dictionary.*;
import com.lightinit.hsdataplatform.entity.*;
import com.lightinit.hsdataplatform.mapper.DataRequirementDataMapper;
import com.lightinit.hsdataplatform.mapper.PublishInfoMapper;
import com.lightinit.hsdataplatform.mapper.RequirementDataMapper;
import com.lightinit.hsdataplatform.mapper.RequirementMapper;
import com.lightinit.hsdataplatform.model.ResultState;
import com.lightinit.hsdataplatform.model.ResultStateCode;
import com.lightinit.hsdataplatform.model.admin.*;
import com.lightinit.hsdataplatform.service.admin.IDataSupplyService;
import com.lightinit.hsdataplatform.spring.DynamicDataContextHolder;
import org.apache.axiom.om.ds.InputStreamDataSource;
import org.springframework.beans.BeanUtils;
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.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2018/5/25 0025.
 */
@Service
public class DataSupplyServiceImpl implements IDataSupplyService {
    @Autowired
    private RequirementDataMapper requirementDataMapper;
    @Autowired
    private RequirementMapper requirementMapper;
    @Autowired
    private PublishInfoMapper publishInfoMapper;
    @Autowired
    private DataRequirementDataMapper dataRequirementDataMapper;

    //判断是否是admin,是：将id置为null;
    private DataSupplySearchModel getRolecodeByUserId(DataSupplySearchModel 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<DataSupplyListModel> queryList(DataSupplySearchModel inputModel, BaseExample.Page pager) throws IOException {
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataSupplySearchModel rolecodeByUserId = getRolecodeByUserId(inputModel);
        DataSupplyPagingSearchModel queryModel = ObjectMappingUtils.map(rolecodeByUserId, DataSupplyPagingSearchModel.class);
        queryModel.setPage(pager);
       //判断开放/共享平台
        if(DicPlatformType.OPEN.equals(inputModel.getRequirementSource())){
            queryModel.setShareType(null);
            queryModel.setBackType(null);
            queryModel.setOpenType(DicPlatformType.OPEN);
            return requirementDataMapper.selectModelList(queryModel);
        }else if((DicPlatformType.SHARE.equals(inputModel.getRequirementSource()))){
            queryModel.setOpenType(null);
            queryModel.setBackType(null);
            queryModel.setShareType(DicPlatformType.SHARE);
            return requirementDataMapper.selectModelList(queryModel);
        }else if(DicPlatformType.BACKSTAGE.equals(inputModel.getRequirementSource())){
            queryModel.setShareType(null);
            queryModel.setOpenType(null);
            queryModel.setBackType(DicRqrmntSourceType.BACKSTAGE);
            return requirementDataMapper.selectModelList(queryModel);
        }else{
            queryModel.setOpenType(DicPlatformType.OPEN);
            queryModel.setShareType(DicPlatformType.SHARE);
            queryModel.setBackType(DicRqrmntSourceType.BACKSTAGE);
            return requirementDataMapper.selectModelList(queryModel);
        }
    }

    @Override
    public long queryCount(DataSupplySearchModel inputModel) throws IOException{
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        DataSupplyPagingSearchModel queryModel = ObjectMappingUtils.map(inputModel, DataSupplyPagingSearchModel.class);
        //判断开放/共享平台
        if(DicPlatformType.OPEN.equals(inputModel.getRequirementSource())){
            queryModel.setOpenType(DicPlatformType.OPEN);
            queryModel.setShareType(null);
            return requirementDataMapper.selectModelListCount(queryModel);
        }else if((DicPlatformType.SHARE.equals(inputModel.getRequirementSource()))){
            queryModel.setOpenType(null);
            queryModel.setShareType(DicPlatformType.SHARE);
            return requirementDataMapper.selectModelListCount(queryModel);
        }else{
            queryModel.setOpenType(DicPlatformType.OPEN);
            queryModel.setShareType(DicPlatformType.SHARE);
            return requirementDataMapper.selectModelListCount(queryModel);
        }
    }


    @Transactional
    public ResultState<Long> SetAuditOpinion(Requirement inputModel) {
        ResultState<Long> resultState = new ResultState<Long>();
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        RequirementExample example = new RequirementExample();
        RequirementExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(inputModel.getId());
        Requirement requirement = requirementMapper.selectByPrimaryKey(inputModel.getId());
        if (DicRequirementAuditResult.APPROVED.equals(inputModel.getAuditResult())){
            requirement.setRqrmntState(DicRequirementState.PENDING_FEEDBACK);
            requirement.setPublishAt(new Date());
            requirement.setAuditedAt(new Date());
            requirement.setAuditResult(DicResourceAuditResult.APPROVED);
        }else {
            requirement.setRqrmntState(DicRequirementState.REJECTED);
            requirement.setAuditedAt(new Date());
            requirement.setAuditResult(DicResourceAuditResult.REJECTED);
        }
        requirement.setAuditedBy(inputModel.getAuditedBy());
        requirement.setAuditOpinion(inputModel.getAuditOpinion());
        if (requirementMapper.updateByExampleSelective(requirement, example) > 0) {
            resultState.setMsg("操作成功！");
            resultState.setStateCode(1);
        } else {
            resultState.setMsg("操作失败！");
            resultState.setStateCode(0);
        }
        return resultState;
    }

    @Transactional
    public ResultState<Long> SetFeedbackDesc(RequirementData inputModel) {
        ResultState<Long> resultState = new ResultState<Long>();
        DynamicDataContextHolder.setCustomerType(DynamicDataContextHolder.DEFAULT);
        RequirementData entity = new RequirementData();
        BeanUtils.copyProperties(inputModel, entity);
        RequirementDataExample example = new RequirementDataExample();
        RequirementDataExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(inputModel.getId());
        RequirementData requirementData = requirementDataMapper.selectByPrimaryKey(inputModel.getId());
        if (requirementData != null) {
            if (requirementDataMapper.updateByExampleSelective(entity, example) > 0) {
                resultState.setMsg("操作成功！");
                resultState.setStateCode(1);
            } else {
                resultState.setMsg("操作失败！");
                resultState.setStateCode(0);
            }
        } else {
            entity.setCreatedAt(new Date());
            if (requirementDataMapper.insert(entity) > 0) {
                resultState.setMsg("操作成功！");
                resultState.setStateCode(1);
            } else {
                resultState.setMsg("操作失败！");
                resultState.setStateCode(0);
            }
        }
        Requirement requirement = requirementMapper.selectByPrimaryKey(inputModel.getId());
        requirement.setRqrmntState(DicRequirementState.PROCESSED_FEEDBACK);
        RequirementExample example2 = new RequirementExample();
        RequirementExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andIdEqualTo(inputModel.getId());
        if (requirementMapper.updateByExampleSelective(requirement, example2) > 0) {
            resultState.setMsg("操作成功！");
            resultState.setStateCode(1);
        } else {
            resultState.setMsg("操作失败！");
            resultState.setStateCode(0);
        }
        return resultState;

    }

    @Override
    public ResultState addDataRequirement(DataRequirementAddModel dataRequirementAddModel) {
        ResultState<Long> resultState = new ResultState<>();
        try {
            Requirement requirement = new Requirement();
            //requirement.setPlatformType(dataRequirementAddModel.getPlatformType());
            requirement.setPlatformType(DicPlatformType.BACKSTAGE);
            requirement.setRqrmntType(DicRqrmntType.DATA);;
            requirement.setRqrmntState(DicRequirmentAuditState.AUDITING);
            requirement.setRqrmntSource(DicPlatformType.BACKSTAGE);
            requirement.setRqrmntName(dataRequirementAddModel.getRqrmntName());
            requirement.setRqrmntSummary(dataRequirementAddModel.getRqrmntSummary());
            requirement.setRqrmntType(DicResourceType.DATA);
            requirement.setPublishBy(dataRequirementAddModel.getUserId());
            requirement.setCreatedAt(new Date());
            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() {
        return requirementMapper.getSectorParentNames();
    }
}
