package cn.com.countrygarden.bi.main.service.performance.impl.indicators;

import cn.com.countrygarden.bi.main.model.performance.NegativeEffective;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.dto.PerformanceShowDataDto;
import cn.com.countrygarden.bi.main.service.performance.indicators.AbstractIndicatorService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 媒体曝光或群诉业务实现类
 *
 * @Author:Wyman
 * @Date:2018/11/3
 */
@Service
public class NegativeEffectServiceImpl<T> extends AbstractIndicatorService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object showData(long elementId, int year, int quarter, int pageCurr, int pageSize, String typeNo) {

        //展示的dto实体
        PerformanceShowDataDto result = this.setVacancyInfo(elementId,year,quarter,typeNo);

        //使用mybatis PageHelper类进行分页
        PageHelper.startPage(pageCurr,pageSize);

        List<PerformanceArea> organList = this.performanceAreaService.getAllAreasByType(typeNo);//查出来的分页记录数
        if(organList.size() != 0){

            //组装返回的数据
            List<NegativeEffective> returnList = new ArrayList<>();

            PerformanceScore score;
            long recordId;

            long elementId1 = 1015001;//二级id 未按标准流程妥善处理
            long elementId2 = 1015002;//二级id 地方媒体报道事件
            long elementId3 = 1015003;//二级id 中央媒体报道事件
            long elementId4 = 1015004;//二级id 广泛媒体报道事件


            for(PerformanceArea p : organList){

                String hierachyId = p.getHierachyId();

                NegativeEffective negativeEffective = new NegativeEffective();
                negativeEffective.setHierarchyId(p.getHierachyId());
                negativeEffective.setSecond_organization(p.getHierachyName());
                negativeEffective.setThird_organization(p.getHierachyName());
                negativeEffective.setQuarter(String.valueOf(quarter));
                negativeEffective.setElementId(elementId);
                negativeEffective.setYear(year);

                //查找分数并插入分数，即加减分
                recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    negativeEffective.setPlus_OR_Less(String.valueOf(score.getScore()));

                //查找 ‘未按标准流程妥善处理’ 指标项 并插入到数据库
                recordId = performanceRecordService.getRecordId(elementId1,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    negativeEffective.setOutStandard(String.valueOf(score.getComplete()));

                //查找 ‘地方媒体报道事件’ 指标项并返回到前端
                recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    negativeEffective.setLocation(String.valueOf(score.getComplete()));

                //查找 ‘中央媒体报道事件’ 指标项并返回到前端
                recordId = performanceRecordService.getRecordId(elementId3,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    negativeEffective.setCenter(String.valueOf(score.getComplete()));

                //查找 ‘广泛媒体报道事件’ 指标项并返回到前端
                recordId = performanceRecordService.getRecordId(elementId4,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    negativeEffective.setSpread(String.valueOf(score.getComplete()));

                returnList.add(negativeEffective);
            }
            result.setDataList(returnList);
        }
        return result;
    }

    @Override
    public Object saveData(long elementId, int year, int quarter, List values) {

        //返回的对象
        PerformanceScore score;
        long recordId;

        long elementId1 = 1015001;//二级id  未按标准流程妥善处理
        long elementId2 = 1015002;//二级id  地方媒体报道事件
        long elementId3 = 1015003;//二级id  中央媒体报道事件
        long elementId4 = 1015004;//二级id  广泛媒体报道事件

        String jsonString = JSONObject.toJSONString(values);

        List<NegativeEffective> list = JSON.parseObject(jsonString,new TypeReference<List<NegativeEffective>>(){});

        for(NegativeEffective n : list) {

            String hierachyId = n.getHierarchyId();

            int plus_or_less = -1, outStandard = -1, location = -1, center = -1, spread = -1;
            plus_or_less = 0;
            if (n.getOutStandard() != null) {
                try {
                    outStandard = Integer.valueOf(n.getOutStandard());
                } catch (NumberFormatException e) {
                    logger.error("=====NegativeeffectiveController.countValue=====outStandard:" + n.getOutStandard());
                }
            }
            if (n.getLocation() != null) {
                try {
                    location = Integer.valueOf(n.getLocation());
                } catch (NumberFormatException e) {
                    logger.error("=====NegativeeffectiveController.countValue=====location:" + n.getLocation());
                }
            }
            if (n.getCenter() != null) {
                try {
                    center = Integer.valueOf(n.getCenter());
                } catch (NumberFormatException e) {
                    logger.error("=====NegativeeffectiveController.countValue=====center:" + n.getCenter());
                }
            }
            if (n.getSpread() != null) {
                try {
                    spread = Integer.valueOf(n.getSpread());
                } catch (NumberFormatException e) {
                    logger.error("=====NegativeeffectiveController.countValue=====spread:" + n.getSpread());
                }
            }
            if (outStandard != -1) {
                plus_or_less = outStandard * -3;
            }
            if (location != -1) {
                plus_or_less = plus_or_less + location * -1;
            }
            if (center != -1) {
                plus_or_less = plus_or_less + center * -2;
            }
            if (spread != -1) {
                plus_or_less = plus_or_less + spread * -10;
            }
            n.setPlus_OR_Less(String.valueOf(plus_or_less));

            //查看分数是否为空 有则更新 否则插入
            recordId = performanceRecordService.getRecordId(elementId, year, quarter, hierachyId);
            score = performanceRecordService.getScore(recordId);
            if (score != null) {
                performanceRecordService.updateScoreSelective(recordId, Float.valueOf(n.getPlus_OR_Less()), score.getComplete(), score.getYearlyScore());
            } else {
                performanceRecordService.insertScoreSelective(recordId, Float.valueOf(n.getPlus_OR_Less()), -1, -1);
            }

            //查看 ‘未按标准流程妥善处理’ 是否存在 有则更新 没有则插入
            if (outStandard != -1) {
                recordId = performanceRecordService.getRecordId(elementId1, year, quarter, hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    performanceRecordService.updateScoreSelective(recordId, score.getScore(), (float) outStandard, score.getYearlyScore());
                } else {
                    performanceRecordService.insertScoreSelective(recordId, -1, (float) outStandard, -1);
                }
            }

            //查看 ‘地方媒体报道事件’ 是否存在 有则更新 没有则插入
            if (location != -1) {
                recordId = performanceRecordService.getRecordId(elementId2, year, quarter, hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    performanceRecordService.updateScoreSelective(recordId, score.getScore(), (float) location, score.getYearlyScore());
                } else {
                    performanceRecordService.insertScoreSelective(recordId, -1, (float) location, -1);
                }
            }

            //查看 ‘中央媒体报道事件’ 是否存在 有则更新 没有则插入
            if (center != -1) {
                recordId = performanceRecordService.getRecordId(elementId3, year, quarter, hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    performanceRecordService.updateScoreSelective(recordId, score.getScore(), (float) center, score.getYearlyScore());
                } else {
                    performanceRecordService.insertScoreSelective(recordId, -1, (float) center, -1);
                }
            }

            //查看 ‘广泛媒体报道事件’ 是否存在 有则更新 没有则插入
            if (spread != -1) {
                recordId = performanceRecordService.getRecordId(elementId4, year, quarter, hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    performanceRecordService.updateScoreSelective(recordId, score.getScore(), (float) spread, score.getYearlyScore());
                } else {
                    performanceRecordService.insertScoreSelective(recordId, -1, (float) spread, -1);
                }
            }
        }

            performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

            PerformanceShowDataDto dataDto = new PerformanceShowDataDto();
            dataDto.setDataList(values);
            //空缺值&空缺地区名称
            List<String> vacanHierachyList = performanceRecordService.getVacancyAreas(elementId,year,quarter,"1");
            dataDto.setNameList(vacanHierachyList);
            int vacancy = vacanHierachyList.size();
            dataDto.setVacancy(vacancy);
            return dataDto;
    }

    @Override
    public void uploadData(long elementId, int year, int quarter, MultipartFile mf, String OperatorId) {
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)mf;
        String fileName = commonsMultipartFile.getOriginalFilename();
        if(!fileName.contains("媒体曝光或群诉")){
            throw new IllegalArgumentException("文件名不正确!");
        }

        //保存数据
        ea.negativeEffectiveUplaod(mf, year, String.valueOf(quarter), OperatorId);
        //保存平均分和总分
        this.performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

    }

    @Override
    public Object selectAuthority(long elementId, Map requestMap, HttpServletRequest request) {
        return this.performancePower.getUserPower(String.valueOf(elementId),requestMap,request);
    }


}
