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 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:Wtman
 * @Date:2018/11/3
 */
@Service
public class OwnerSatisfyServiceImpl<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){

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

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

            for(PerformanceArea p : organList){

                OwnersSatisfaction o = new OwnersSatisfaction();

                o.setSecond_organization(p.getHierachyName());//二级区域
                o.setThird_organization(p.getHierachyName());//三级区域
                o.setHierarchyId(p.getHierachyId());//城市公司id
                o.setYear(String.valueOf(year));//年份
                o.setQuarter(String.valueOf(quarter));//季度

                String hierarchy_id = p.getHierachyId();

                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierarchy_id);
                if(record != null){
                    o.setIs_check(record.getIsExamine() == 1 ? 1 : 0);
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        o.setInvestigation(String.valueOf(score.getComplete()));
                        o.setIndividualScore(String.valueOf(score.getScore()));
                    }
                    target = performanceRecordService.getTarget(recordId);
                    if(target != null){
                        o.setThreshold(target.getThresholdTarget());
                        o.setAtLeast(target.getAtLeastTarget());
                        o.setScream(target.getScreamTarget());
                        o.setHowl(target.getHowlTarget());
                    }
                }
                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<OwnersSatisfaction> list = JSON.parseObject(jsonString,new TypeReference<List<OwnersSatisfaction>>(){});

        double weight = 0;
        for(OwnersSatisfaction value : list){

            String hierachyId = value.getHierarchyId();
            String type = performanceAreaService.getSubTypeByHierachyId(hierachyId);
            switch (type){
                case "单一业主项目":
                    weight = 0.3;
                    break;
                case "多业主第一年":
                    weight = 0.5;
                    break;
                case "多业主第二年":
                    weight = 0.4;
                    break;
            }

            String complete = value.getInvestigation();//完成值就是调查情况值
            if (complete == null || "".equals(complete)) {
                complete = "-1";
            }

            String threshold = value.getThreshold();
            if (threshold == null || "".equals(threshold))
                threshold = "-1";

            String atLeast = value.getAtLeast();
            if (atLeast == null || "".equals(atLeast))
                atLeast = "-1";

            //1.门槛值有&&保底值有 2.门槛值无且保底值有的情况 门槛值才是保底值的80%
            if ((!"-1".equals(threshold) && !"-1".equals(atLeast)) || ("-1".equals(threshold) && !"-1".equals(atLeast))) {
                double d = Float.parseFloat(atLeast) * 0.8;
                threshold = String.valueOf(d < 0 ? -1 : d);
            }

            String scream = value.getScream();
            if (scream == null || "".equals(scream))
                scream = "-1";

            String howl = value.getHowl();
            if (howl == null || "".equals(howl))
                howl = "-1";

            double default_weight = 1;
            String IndividualScore = "-1";
            if (!complete.equals("-1")) {
                IndividualScore = Calculate.InsertionMethod(Double.parseDouble(complete), Double.parseDouble(threshold), Double.parseDouble(atLeast), Double.parseDouble(scream), Double.parseDouble(howl), default_weight);
            }
            value.setIndividualScore(IndividualScore);

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

            try{
                RecordPerformanceDto performanceDto = new RecordPerformanceDto();
                performanceDto.setElementId(elementId);
                performanceDto.setYear(year);
                performanceDto.setQuarter(quarter);
                performanceDto.setHierachyId(hierachyId);
                performanceDto.setScore(Float.parseFloat(IndividualScore));
                performanceDto.setComplete(Float.parseFloat(complete));
                performanceDto.setThreshold(threshold);
                performanceDto.setAt_Least(atLeast);
                performanceDto.setScream(scream);
                performanceDto.setHowl(howl);
                performanceDto.setWeight(weight);
                performanceDto.setIsExamine((short) value.getIs_check());
                performanceRecordService.performanceRecord(performanceDto);
            } catch (Exception e){

            }

        }
        performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

        PerformanceShowDataDto dataDto = new PerformanceShowDataDto();
        dataDto.setDataList(values);
        //空缺值&空缺地区名称
        List<String> vacanHierachyList = performanceRecordService.getVacancyAreas(elementId,year,quarter,"2");
        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.OwnersSatisfactionUpload(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);
    }
}
