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.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.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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;

/**
 * 大客户满意度业务实现类
 *
 * @Description:所有关于大业主满意度指标的相关业务
 * @Author:Wyman
 * @Date:2018/10/22
 */
@Service
public class BigCustSatisfyServiceImpl<T> extends AbstractIndicatorService<T> {

    @Override
    public PerformanceShowDataDto 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<BigCustomerSatisfaction> returnList = new ArrayList<>();

            //定义值用来存放目标值，避免新增的区域无目标值
            String hrspp_threshold=null;
            String hrspp_atLeast=null;
            String hrspp_scream=null;
            String hrspp_howl=null;

            PerformanceTarget target;
            PerformanceScore score;
            PerformanceRecord record;

            for(int i = 0; i < organList.size(); i++){

                BigCustomerSatisfaction b = new BigCustomerSatisfaction();

                String hierachy_id = organList.get(i).getHierachyId();
                long record_id;

                b.setHierarchyId(organList.get(i).getHierachyId());
                b.setSecond_organization(organList.get(i).getHierachyName());
                b.setThird_organization(organList.get(i).getHierachyName());
                b.setQuarter(String.valueOf(quarter));
                b.setYear(String.valueOf(year));

                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachy_id);
                if(record != null){

                    record_id = record.getRecordId();
                    score = performanceRecordService.getScore(record_id);
                    if(score != null){
                        b.setAnnual(String.valueOf(score.getComplete()));
                        b.setIndividualScore(String.valueOf(score.getScore()));
                    }

                    target = performanceRecordService.getTarget(record_id);
                    if(target != null){
                        b.setHrspp_threshold(target.getThresholdTarget());
                        b.setHrspp_atLeast(target.getAtLeastTarget());
                        b.setHrspp_scream(target.getScreamTarget());
                        b.setHrspp_howl(target.getHowlTarget());
                        //是否考核,1表示考核，0表示不考核
                        b.setIs_check(record.getIsExamine() == 1 ? 1 : 0);
                        if(hrspp_threshold==null){
                            hrspp_threshold=target.getThresholdTarget();
                            hrspp_atLeast=target.getAtLeastTarget();
                            hrspp_scream=target.getScreamTarget();
                            hrspp_howl=target.getHowlTarget();
                        }
                    }
                }else{
                    b.setHrspp_threshold(hrspp_threshold);
                    b.setHrspp_atLeast(hrspp_atLeast);
                    b.setHrspp_scream(hrspp_scream);
                    b.setHrspp_howl(hrspp_howl);
                }



                //第一个季度
                record_id = performanceRecordService.getRecordId(elementId,year,1,hierachy_id);
                    score = performanceRecordService.getScore(record_id);
                    if(score != null) {
                        b.setS1(String.valueOf(score.getComplete()));
                    } else {
                        b.setS1(null);
                    }
                //第二个季度
                record_id = performanceRecordService.getRecordId(elementId,year,2,hierachy_id);
                    score = performanceRecordService.getScore(record_id);
                    if(score != null) {
                        b.setS2(String.valueOf(score.getComplete()));
                    } else {
                        b.setS2(null);
                    }
                //第三个季度
                record_id = performanceRecordService.getRecordId(elementId,year,3,hierachy_id);
                    score = performanceRecordService.getScore(record_id);
                    if(score != null) {
                        b.setS3(String.valueOf(score.getComplete()));
                    } else {
                        b.setS3(null);
                    }
                //第四个季度
                record_id = performanceRecordService.getRecordId(elementId,year,4,hierachy_id);
                    score = performanceRecordService.getScore(record_id);
                    if(score != null) {
                        b.setS4(String.valueOf(score.getComplete()));
                    } else {
                        b.setS4(null);
                    }
                //将对象加入到集合中
                returnList.add(b);
            }
            result.setDataList(returnList);
        }

        return result;
    }

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

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

        String jsonString = JSONObject.toJSONString(values);

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

        //遍历集合将对象存入数据库中
        for(int i = 0; i < list.size(); i++){
           BigCustomerSatisfaction value =  list.get(i);

            String s1 = value.getS1();
            String s2 = value.getS2();
            String s3 = value.getS3();
            String s4 = value.getS4();
            String[] completes = {s1, s2, s3, s4};
            String HierarchyId = value.getHierarchyId();


            for (int j = 0; j < completes.length; j++) {
                if (StringUtil.isBlankOrEmpty(completes[j])) {
                    completes[j] = "-1";
                }
                if (j <= quarter - 1) {  //使其输入的数据限定于选择的季度  eg:选择第一季度，只有s1数据有效；选择第二季度，只s1、s2数据有效
                    recordId = performanceRecordService.getRecordId(elementId,year,j+1,HierarchyId);
                    score = performanceRecordService.getScore(recordId);
                    completes[j] = String.valueOf(score == null ? "-1" : completes[j]);
                }
            }
            String Annual;

            if (completes[0].equals("-1") && completes[1].equals("-1") && completes[2].equals("-1") && completes[3].equals("-1")) {
                Annual = "-1";
            } else {
                Annual = Calculate.Year(Double.parseDouble(completes[0]), Double.parseDouble(completes[1]), Double.parseDouble(completes[2]), Double.parseDouble(completes[3]));
            }

            String Hrspp_threshold = value.getHrspp_threshold();
            if (Hrspp_threshold == null || "".equals(Hrspp_threshold)) {
                Hrspp_threshold = "-1";
            }
            String Hrspp_atLeast = value.getHrspp_atLeast();
            if (Hrspp_atLeast == null || "".equals(Hrspp_atLeast)) {
                Hrspp_atLeast = "-1";
            }

            String Hrspp_scream = value.getHrspp_scream();
            if (Hrspp_scream == null || "".equals(Hrspp_scream)) {
                Hrspp_scream = "-1";
            }
            String Hrspp_howl = value.getHrspp_howl();
            if (Hrspp_howl == null || "".equals(Hrspp_howl)) {
                Hrspp_howl = "-1";
            }

            String IndividualScore = "-1";

            if (!Annual.equals("-1")) {
                IndividualScore = Calculate.InsertionMethod(Double.parseDouble(Annual), Double.parseDouble(Hrspp_threshold), Double.parseDouble(Hrspp_atLeast), Double.parseDouble(Hrspp_scream), Double.parseDouble(Hrspp_howl), 1);
            }
            value.setAnnual(Annual);
            value.setIndividualScore(IndividualScore);


            if (value.getIs_check() == 0) {
                IndividualScore = "-1";
            }

            recordId = performanceRecordService.getRecordId(elementId,year,quarter,HierarchyId);
            score = performanceRecordService.getScore(recordId);
            //查出考核记录表中对应的recordId
            recordId = performanceRecordService.getRecordId(elementId,year,quarter,HierarchyId);
            if(score != null){//已有，更新
                performanceRecordService.updateScoreSelective(recordId,Float.parseFloat(IndividualScore),Float.parseFloat(completes[quarter - 1]),Float.parseFloat(Annual));
            }else{//没有，则新增
                performanceRecordService.insertScoreSelective(recordId,Float.parseFloat(IndividualScore),Float.parseFloat(completes[quarter - 1]),Float.parseFloat(Annual));
            }



            target = performanceRecordService.getTarget(recordId);
            if (target != null) {//更新
                performanceRecordService.updateTargetSelective(recordId,String.valueOf(Hrspp_threshold),String.valueOf(Hrspp_atLeast),
                        String.valueOf(Hrspp_scream),String.valueOf(Hrspp_howl));
            } else {//新增
                performanceRecordService.insertTargetSelective(recordId,String.valueOf(Hrspp_threshold),String.valueOf(Hrspp_atLeast),
                        String.valueOf(Hrspp_scream),String.valueOf(Hrspp_howl));
            }
            value.setIndividualScore(IndividualScore);
        }

           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
    @Transactional
    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("文件名不正确!");
        }

        try {
            //保存数据
            ea.BigCustomerSatisfactionUpload(elementId,mf, year, quarter, OperatorId);
            //保存平均分和总分
            this.performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);
        } catch (Exception e) {
            throw e;
        }
    }


    @Override
    public Object selectAuthority(long elementId,Map<String, Object> requestMap, HttpServletRequest request) {

        return this.performancePower.getUserPower(String.valueOf(elementId),requestMap,request);

    }
}
