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

import cn.com.countrygarden.bi.main.model.performance.*;
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.Calculate;
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.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 OutreachRevenueServiceImpl<T> extends AbstractIndicatorService<T> {

    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<OutreachRevenue> returnList = new ArrayList<>();

            PerformanceTarget target;
            PerformanceScore score;
            PerformanceRecord record;
            long recordId;

            for(PerformanceArea p : organList){

                String hierachyId = p.getHierachyId();
                OutreachRevenue o = new OutreachRevenue();
                o.setHierarchyId(p.getHierachyId());//组织id
                o.setSecond_organization(p.getHierachyName());//二级组织
                o.setThird_organization(p.getHierachyName());//三级组织
                o.setElementId((int) elementId);//设置elementid
                o.setYear(String.valueOf(year));//设置年份
                o.setQuarter(String.valueOf(quarter));//设置季度值

                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachyId);
                if(record != null){
                    //是否考核,1表示考核，0表示不考核
                    if (StringUtil.isEmpty(String.valueOf(record.getIsExamine()))) {
                        o.setIs_check(0);
                    } else if (record.getIsExamine() == 1) {
                        o.setIs_check(1);
                    } else {
                        o.setIs_check(0);
                    }
                    recordId = record.getRecordId();
                    target = performanceRecordService.getTarget(recordId);
                    if(target != null){
                        o.setThresholdTarget(target.getThresholdTarget());//门槛
                        o.setAtLeastTarget(target.getAtLeastTarget());//保底
                        o.setScreamTarget(target.getScreamTarget());//尖叫
                        o.setHowlTarget(target.getHowlTarget());//嚎叫
                    }
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        o.setRealIncome(String.valueOf(score.getComplete()));//把完成值放入实际值，实际值是入库后才获得的
                        o.setIndividualScore(String.valueOf(score.getScore()));//单项指标得分，是计算后入库才获得
                    }
                }
                returnList.add(o);
            }
            result.setDataList(returnList);
        }
        return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        for (OutreachRevenue outreachRevenue : list){
            String hierachyId = outreachRevenue.getHierarchyId();
            //目标值
            double realIncome = 0;         //实际收入
            double thresholdTarget = 0;  //门槛值目标值
            double atLeastTarget = 0;  //保底目标值
            double screamTarget = 0;  //尖叫目标值
            double howlTarget = 0;  //嚎叫目标值
            String IndividualScore;      // 指标单项得分
            //外拓收入实际值(万元)
            if (!StringUtil.isBlankOrEmpty(outreachRevenue.getRealIncome())) {
                try {
                    realIncome = Double.parseDouble(outreachRevenue.getRealIncome());
                } catch (Exception e) {
                    logger.error("======OutreachRevenueController.TotalCalculate======realIncome:" + outreachRevenue.getRealIncome());
                }
            }

            //门槛值
            if (!StringUtil.isBlankOrEmpty(outreachRevenue.getThresholdTarget())) {
                try {
                    thresholdTarget = Double.parseDouble(outreachRevenue.getThresholdTarget());
                } catch (Exception e) {
                    logger.error("======OutreachRevenueController.TotalCalculate======thresholdTarget:" + outreachRevenue.getThresholdTarget());
                }
            }
            //保底值
            if (!StringUtil.isBlankOrEmpty(outreachRevenue.getAtLeastTarget())) {
                try {
                    atLeastTarget = Double.parseDouble(outreachRevenue.getAtLeastTarget());
                } catch (Exception e) {
                    logger.error("======OutreachRevenueController.TotalCalculate======atLeastTarget:" + outreachRevenue.getAtLeastTarget());
                }
            }
            //尖叫值
            if (!StringUtil.isBlankOrEmpty(outreachRevenue.getScreamTarget())) {
                try {
                    screamTarget = Double.parseDouble(outreachRevenue.getScreamTarget());
                } catch (Exception e) {
                    logger.error("======OutreachRevenueController.TotalCalculate======screamTarget:" + outreachRevenue.getScreamTarget());
                }
            }
            //嚎叫值
            if (!StringUtil.isBlankOrEmpty(outreachRevenue.getHowlTarget())) {
                try {
                    howlTarget = Double.parseDouble(outreachRevenue.getHowlTarget());
                } catch (Exception e) {
                    logger.error("======OutreachRevenueController.TotalCalculate======howlTarget:" + outreachRevenue.getHowlTarget());
                }
            }
            //计算指标单项得分
            IndividualScore = Calculate.InsertionMethod(realIncome, atLeastTarget, thresholdTarget, screamTarget, howlTarget, 1);
            outreachRevenue.setIndividualScore(IndividualScore);
            ///////////////////////////////////////////////////////////////////
            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setElementId(elementId);
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierachyId);
            performanceDto.setRate("年度");
            performanceDto.setWeight(0.1);
            performanceDto.setThreshold(String.valueOf(thresholdTarget));
            performanceDto.setAt_Least(String.valueOf(atLeastTarget));
            performanceDto.setScream(String.valueOf(screamTarget));
            performanceDto.setHowl(String.valueOf(howlTarget));
            performanceDto.setComplete((float) realIncome);
            performanceDto.setScore(Float.parseFloat(IndividualScore));
            performanceDto.setIsExamine((short)outreachRevenue.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.outreachRevenueUpload(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);
    }
}
