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.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 小客户满意度业务实现类
 *
 * @Description:所有关于小业主满意度指标的相关业务
 * @Author:Wyman
 * @Date:2018/11/2
 */
@Service
public class SmallCustSatisfyServiceImpl<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);

        Map<String, Object> elementMap = new LinkedHashMap<>();
        PerformanceElement element = new PerformanceElement();
        element.setElementId(elementId);
        //获得小业主下级 的ID 和 指标的名
        List<PerformanceElement> list = performanceElementMapper.selectFirstElement(element);
        for (PerformanceElement aList : list) {
            if (aList.getName().equals("综合满意率")) {
                elementMap.put("综合满意率", aList.getElementId());
            }
            if (aList.getName().equals("管家服务满意率")) {
                elementMap.put("管家服务满意率", aList.getElementId());
            }
        }

        //使用mybatis PageHelper类进行分页
        PageHelper.startPage(pageCurr,pageSize);
        List<PerformanceArea> organList = this.performanceAreaService.getAllAreasByType(typeNo);//查出来的分页记录数

        if(organList.size() != 0) {

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

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

            for(PerformanceArea pa : organList){
                SmallownersSatisfaction so = new SmallownersSatisfaction();

                String hierachy_id = pa.getHierachyId();

                so.setHierarchyId(hierachy_id);
                //二、三级组织等
                so.setSecond_organization(pa.getHierachyName());
                so.setThird_organization(pa.getHierachyName());
                //设置显示格式
                so.setUnit(1);//单位（0-分，1-百分比，2-元，3-万元，4-平方米/人）

                recordId = performanceRecordService.getRecordId(Long.parseLong(elementMap.get("综合满意率").toString()),year,quarter,hierachy_id);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    so.setCompre_threshold(target.getThresholdTarget());
                    so.setCompre_atLeast(target.getAtLeastTarget());
                    so.setCompre_scream(target.getScreamTarget());
                    so.setCompre_howl(target.getHowlTarget());
                }

                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    so.setCompre_score(String.valueOf(score.getScore()));
                    so.setCompre_investigation(String.valueOf(score.getComplete()));
                }

                recordId = performanceRecordService.getRecordId(Long.parseLong(elementMap.get("管家服务满意率").toString()),year,quarter,hierachy_id);
                target = performanceRecordService.getTarget(recordId);
                if(target !=null){
                    so.setButler_investigation(null);
                    so.setButler_threshold(target.getThresholdTarget());
                    so.setButler_atLeast(target.getAtLeastTarget());
                    so.setButler_scream(target.getScreamTarget());
                    so.setButler_howl(target.getHowlTarget());
                }

                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    so.setButler_score(String.valueOf(score.getScore()));
                    so.setButler_investigation(String.valueOf(score.getComplete()));
                }

                //小业主满意率
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachy_id);
                //是否考核
                if (record != null) {
                    so.setIs_check(record.getIsExamine() == 1 ? 1 : 0);
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        so.setIndividualScore(String.valueOf(score.getScore()));
                    }
                } else {
                    so.setIs_check(1);
                }
                so.setQuarter(String.valueOf(quarter));
                so.setYear(String.valueOf(year));
                returnList.add(so);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        //返回的对象
        RecordPerformanceDto recordDto = new RecordPerformanceDto();

        String jsonString = JSONObject.toJSONString(values);

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

        for(SmallownersSatisfaction s : list){
            String hierachyId = s.getHierarchyId();

            //综合管家
            String Compre_investigation = s.getCompre_investigation() == null ? "-1" : s.getCompre_investigation();
            String Compre_threshold = s.getCompre_threshold() == null ? "-1" : s.getCompre_threshold();
            String Compre_atLeast = s.getCompre_atLeast() == null ? "-1" : s.getCompre_atLeast();
            String Compre_scream = s.getCompre_scream() == null ? "-1" : s.getCompre_scream();
            String Compre_howl = s.getCompre_howl() == null ? "-1" : s.getCompre_howl();

            double weight = 1;
            String Compre_score = "-1";

            if (!StringUtil.isBlankOrEmpty(Compre_investigation)) {
                try {
                    Compre_score = Calculate.InsertionMethod(Double.parseDouble(Compre_investigation), Double.parseDouble(Compre_threshold), Double.parseDouble(Compre_atLeast), Double.parseDouble(Compre_scream), Double.parseDouble(Compre_howl), weight);
                } catch (NumberFormatException e) {
                    logger.info(e.getMessage());
                }
            }
            if (s.getIs_check() == 0){
                Compre_score = "-1";
            }
            s.setCompre_score(Compre_score);
            //综合满意率入库得分表

            recordDto.setHierachyId(hierachyId);
            recordDto.setElementId(1002001);
            recordDto.setYear(year);
            recordDto.setQuarter(quarter);
            recordDto.setScore(Float.parseFloat(Compre_score));
            recordDto.setComplete(Float.parseFloat(Compre_investigation));
            recordDto.setThreshold(String.valueOf(Compre_threshold));
            recordDto.setAt_Least(String.valueOf(Compre_atLeast));
            recordDto.setScream(String.valueOf(Compre_scream));
            recordDto.setHowl(String.valueOf(Compre_howl));
            performanceRecordService.performanceRecord(recordDto);

            //管家服务满意率
            String Butler_investigation = s.getButler_investigation() == null ? "-1" : s.getButler_investigation();
            String Butler_threshold = s.getButler_threshold() == null ? "-1" : s.getButler_threshold();
            String Butler_atLeast = s.getButler_atLeast() == null ? "-1" : s.getButler_atLeast();
            String Butler_scream = s.getButler_scream() == null ? "-1" : s.getButler_scream();
            String Butler_howl = s.getButler_howl() == null ? "-1" : s.getButler_howl();
            double weight1 = 1;
            String Butler_score = "-1";

            if (!StringUtil.isBlankOrEmpty(Butler_investigation)) {
                try {
                    Butler_score = Calculate.InsertionMethod(Double.parseDouble(Butler_investigation), Double.parseDouble(Butler_threshold), Double.parseDouble(Butler_atLeast), Double.parseDouble(Butler_scream), Double.parseDouble(Butler_howl), weight1);
                } catch (NumberFormatException e) {
                    logger.info(e.getMessage());
                }
            }
            if (s.getIs_check() == 0){
                Butler_score = "-1";
            }
            s.setButler_score(Butler_score);
            //管家入库得分表
            Butler_investigation = StringUtil.isBlankOrEmpty(Butler_investigation) ? "-1" : Butler_investigation;

            recordDto.setElementId(1002002);
            recordDto.setScore(Float.parseFloat(Butler_score));
            recordDto.setComplete(Float.parseFloat(Butler_investigation));
            recordDto.setThreshold(String.valueOf(Butler_threshold));
            recordDto.setAt_Least(String.valueOf(Butler_atLeast));
            recordDto.setScream(String.valueOf(Butler_scream));
            recordDto.setHowl(String.valueOf(Butler_howl));
            performanceRecordService.performanceRecord(recordDto);

            //小业主满意率的指标单项得分
            float IndividualScore;

            if (!Compre_score.equals("-1") && Butler_score.equals("-1")) {
                IndividualScore = Float.parseFloat(Compre_score);
            } else {
                IndividualScore = (float) (Float.parseFloat(Compre_score) * 0.8 + Float.parseFloat(Butler_score) * 0.2);
            }

            if (s.getIs_check() == 0){
                IndividualScore = -1;
            }
            s.setIndividualScore(String.valueOf(IndividualScore));

            recordDto.setElementId(elementId);
            recordDto.setScore(IndividualScore);
            recordDto.setComplete(-1);
            recordDto.setRate("季度、年度");
            recordDto.setWeight(0.25);
            recordDto.setIsExamine((short)s.getIs_check());
            recordDto.setThreshold(null);
            recordDto.setAt_Least(null);
            recordDto.setScream(null);
            recordDto.setHowl(null);
            performanceRecordService.performanceRecord(recordDto);

        }
        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.SmallownersSatisfactionUpload(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);
    }
}
