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

import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceRecord;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.YuanAverageValue;
import cn.com.countrygarden.bi.main.model.performance.dto.PerformanceShowDataDto;
import cn.com.countrygarden.bi.main.model.performance.dto.RecordPerformanceDto;
import cn.com.countrygarden.bi.main.service.performance.indicators.AbstractIndicatorService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
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 YuanaverageServiceImpl<T> extends AbstractIndicatorService<T> {
    @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){

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

            PerformanceScore score;
            PerformanceRecord record;
            long recordId;

            for(PerformanceArea p : organList){

                String hierachyId = p.getHierachyId();
                YuanAverageValue yuanAverageValue = new YuanAverageValue();
                yuanAverageValue.setHierarchyId(p.getHierachyId());//组织id
                yuanAverageValue.setSecond_organization(p.getHierachyName());//二级组织
                yuanAverageValue.setThird_organization(p.getHierachyName());//三级组织
                yuanAverageValue.setYear(year);//设置年份
                yuanAverageValue.setQuarter(String.valueOf(quarter));//设置季度

                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachyId);
                if(record != null){
                    yuanAverageValue.setIs_check(record.getIsExamine() == 1 ? 1 : 0);

                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        yuanAverageValue.setYuan_RealValue(String.valueOf(score.getComplete()));// 元均产值：实际值
                        yuanAverageValue.setIndividualScore(String.valueOf(score.getScore()));// 指标单项得分
                    }
                }
                returnList.add(yuanAverageValue);
            }
            result.setDataList(returnList);
        }
        return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        for(YuanAverageValue yuanAverageValue : list){

            double Complete = 0;

            String hierachyId = yuanAverageValue.getHierarchyId();
            String Completes = yuanAverageValue.getYuan_RealValue();
            String score = yuanAverageValue.getIndividualScore();

            //实际值
            if (!StringUtil.isBlankOrEmpty(Completes)) {
                Complete = Double.parseDouble(Completes);
            } else {
                continue;
            }

            score = StringUtil.isBlankOrEmpty(score) ? "-1" : score;

            yuanAverageValue.setIndividualScore(score);// 计算结果设值

            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierachyId);
            performanceDto.setElementId(elementId);
            performanceDto.setComplete((float) Complete);
            performanceDto.setScore(Float.parseFloat(score));
            performanceDto.setWeight(0.05);
            performanceDto.setIsExamine((short)yuanAverageValue.getIs_check());
            performanceRecordService.performanceRecord(performanceDto);

        }
        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.yuanAverageValueUpload(mf, year, quarter, OperatorId);
        //保存平均分和总分
        this.performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);
    }

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