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

import cn.com.countrygarden.bi.main.model.performance.CommunityITTransfor;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.PerformanceTarget;
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.Arith;
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 CommunityITServiceImpl<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<CommunityITTransfor> returnList = new ArrayList<>();

            long elementIdSqlr = 1010001;//税前利润达标id
            long elementIdSzxwc = 1010002;//双执行完成项目数id
            long elementIdSswc = 1010003;//iRBA实施完成项目数id
            PerformanceTarget target;
            PerformanceScore score;
            long recordId;

            for(PerformanceArea p : organList){

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

                //------------税前利润达标
                recordId = performanceRecordService.getRecordId(elementIdSqlr,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    //税前利润达标
                    if (score.getComplete() == 1) {
                        communityITTransfor.setIs_Standard("是");
                        //communityITTransfor.setIs_Standard("1");
                    } else {
                        communityITTransfor.setIs_Standard("否");
                        //communityITTransfor.setIs_Standard("0");
                    }
                }
                //------------双执行
                recordId = performanceRecordService.getRecordId(elementIdSzxwc,year,quarter,hierachyId);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    communityITTransfor.setComple_Value(target.getHowlTarget());//双执行完成目标值
                }
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    communityITTransfor.setPriject_Count(score.getComplete());//双执行完成项目数
                    communityITTransfor.setComple_Rate(score.getScore());//双执行完成率
                }
                //------------iRBA
                recordId = performanceRecordService.getRecordId(elementIdSswc,year,quarter,hierachyId);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    try {
                        communityITTransfor.setiRBA_Count(Float.valueOf(target.getHowlTarget()));//双执行完成目标值
                    } catch (NumberFormatException e) {
                        communityITTransfor.setiRBA_Count(null);//双执行完成目标值
                    }
                }

                //----------------社区智能改造
                recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    communityITTransfor.setPlus_OR_Less(score.getScore());//双执行完成率
                }
                returnList.add(communityITTransfor);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        long elementIdSqlr = 1010001;//税前利润达标id
        long elementIdSzxwc = 1010002;//双执行完成项目数id
        long elementIdSswc = 1010003;//iRBA实施完成项目数id


        String jsonString = JSONObject.toJSONString(values);

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

        for(CommunityITTransfor value : list){
            //税前利润达标 是或者否,更新数据库分别为1和0
            String hierachyId = value.getHierarchyId();
            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierachyId);

            if (!StringUtil.isBlankOrEmpty(value.getIs_Standard())) {

                performanceDto.setElementId(elementIdSqlr);
                float complete;
                if ("1".equals(value.getIs_Standard())) {
                    complete = 1;
                } else {
                    complete = 0;
                }
                performanceDto.setComplete(complete);
                performanceDto.setScore(-1);
                performanceRecordService.performanceRecord(performanceDto);

                //---------双执行
                //计算双执行完成率
                double szxwcl = -1;
                if (value.getPriject_Count() != null
                        && value.getComple_Value() != null && (!"".equals(value.getComple_Value()))) {
                    try {
                        double prijectC = value.getPriject_Count().doubleValue();
                        double compleV = Double.parseDouble(value.getComple_Value());
                        //计算保留两位小数
                        szxwcl = Arith.div(prijectC, compleV, 2);
                        if (szxwcl > 1) {//如果大于100%，则等于1
                            szxwcl = 1;
                        }
                        value.setComple_Rate((float) szxwcl);//返回给前端
                    } catch (Exception e) {
                        logger.error("=====CommunityITTrasforController.TotalCalculate=====exception for prijectC:"
                                + value.getPriject_Count() + ",compleV:" + value.getComple_Value());
                    }
                }

                performanceDto.setElementId(elementIdSzxwc);
                float score2 = -1;
                float complete2 = -1;
                //双执行完成项目数
                if (value.getPriject_Count() != null) {
                    complete2 = value.getPriject_Count();
                }
                //双执行完成率
                if (szxwcl != -1) {
                    score2 = (float) szxwcl;
                }
                performanceDto.setComplete(complete2);
                performanceDto.setScore(score2);
                performanceRecordService.performanceRecord(performanceDto);

                //双执行完成目标值
                if (value.getComple_Value() != null && (!"".equals(value.getComple_Value()))) {
                    performanceDto.setElementId(elementIdSzxwc);
                    performanceDto.setHowl(value.getComple_Value());
                    performanceRecordService.performanceRecord(performanceDto);
                }
                //iRBA实施完成项目数
                if (value.getiRBA_Count() != null) {
                    performanceDto.setElementId(elementIdSswc);
                    performanceDto.setHowl(String.valueOf(value.getiRBA_Count()));
                    performanceRecordService.performanceRecord(performanceDto);
                }

                //计算
                //计算规则：
                /*
                区域智能安防改造加分：
                （a）物业区域智能安保系统改造“双执行”完成率＝100%，区域智能安防改造加分＝3；
                （b）物业区域智能安保系统改造“双执行”完成率＜100%，区域智能安防改造加分＝0；
                区域 iRBA 改造加分＝区域下辖涉及 iRBA 改造项目如期完成项目数×0.5，本项加分不超过 1 分。
                 */
                float temp_plus_or_less = -1;//加减分
                //先判断税前利润达标
                if ("1".equals(value.getIs_Standard())||"是".equals(value.getIs_Standard())) {
                    temp_plus_or_less = 0;//重新初始化为0
                    if (szxwcl >= 1) {
                        temp_plus_or_less += 3;//加三分
                    }
//                    if (!values.get(i).getComple_Value().equals("") && values.get(i).getComple_Value() != null && values.get(i).getPriject_Count() != null) {
//                        if (values.get(i).getPriject_Count() / Float.parseFloat(values.get(i).getComple_Value()) >= 1) {
//                            temp_plus_or_less += 3;//加三分
//                        }
//                    }
                    if (value.getiRBA_Count() != null) {
                        if (value.getiRBA_Count() * 0.5 > 1) {
                            temp_plus_or_less += 1;
                        } else {
                            temp_plus_or_less += (value.getiRBA_Count() * 0.5);
                        }
                    }
                }

                performanceDto.setElementId(elementId);
                float score3;
                if (temp_plus_or_less != -1) {
                    //修改要返回前端的值
                    value.setPlus_OR_Less(temp_plus_or_less);
                    score3 = temp_plus_or_less;//设置score
                } else {
                    //修改要返回前端的值
                    value.setPlus_OR_Less(null);
                    score3 = 0;//设置score
                }
                performanceDto.setScore(score3);
                performanceDto.setComplete(-1);
                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.communityITTransforUpload(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);
    }
}
