package com.yihu.ehr.basic.quota.controller;

import com.yihu.ehr.basic.quota.service.TjDimensionMainService;
import com.yihu.ehr.basic.quota.service.TjDimensionSlaveService;
import com.yihu.ehr.basic.quota.service.TjQuotaDimensionMainService;
import com.yihu.ehr.basic.quota.service.TjQuotaDimensionSlaveService;
import com.yihu.ehr.constants.ApiVersion;
import com.yihu.ehr.constants.ServiceApi;
import com.yihu.ehr.controller.EnvelopRestEndPoint;
import com.yihu.ehr.entity.quota.TjDimensionMain;
import com.yihu.ehr.entity.quota.TjDimensionSlave;
import com.yihu.ehr.entity.quota.TjQuotaDimensionMain;
import com.yihu.ehr.entity.quota.TjQuotaDimensionSlave;
import com.yihu.ehr.model.tj.DictModel;
import com.yihu.ehr.model.tj.SaveModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by janseny on 2017/8/11.
 */
@RestController
@RequestMapping(ApiVersion.Version1_0)
@Api(value = "TjQuotaSynthesizeQueryEndPoint", description = "指标统计综合表", tags = {"统计指标管理-指标统计综合表"})
public class TjQuotaSynthesizeQueryEndPoint extends EnvelopRestEndPoint {

    private static final Logger logger = LoggerFactory.getLogger(TjQuotaSynthesizeQueryEndPoint.class);

    @Autowired
    private TjQuotaDimensionMainService tjQuotaDimensionMainService;
    @Autowired
    private TjQuotaDimensionSlaveService tjQuotaDimensionSlaveService;
    @Autowired
    private TjDimensionMainService tjDimensionMainService;
    @Autowired
    private TjDimensionSlaveService tjDimensionSlaveService;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @RequestMapping(value = ServiceApi.TJ.GetTjQuotaSynthesiseDimension, method = RequestMethod.GET)
    @ApiOperation(value = "查询多个指标交集维度---针对于查询ES库数据维度 主纬度是具体字段，细维度为slaveKey*")
    public  List<Map<String,String>>  getTjQuotaSynthesiseDimension(
            @ApiParam(name = "quotaCodes", value = "指标code，多个指标用英文,分开")
            @RequestParam(value = "quotaCodes") String quotaCodes) {

        List<TjQuotaDimensionMain> tjQuotaDimensionMains = null;
        List<TjQuotaDimensionSlave> tjQuotaDimensionSlaves = null;
        //保存指标的 ID 和 所有维度的集合
        Map<String,Map<String,String>> dimensionMap = new LinkedHashMap();
        String [] quotaCode = quotaCodes.split(",");
        for(int i=0 ; i < quotaCode.length ;i++){
            Map<String,String> map = new LinkedHashMap<>();
            tjQuotaDimensionMains = tjQuotaDimensionMainService.getTjQuotaDimensionMainByCode(quotaCode[i]);
//            int main = 1;
            for(TjQuotaDimensionMain tjQuotaDimensionMain : tjQuotaDimensionMains){
                TjDimensionMain tjDimensionMain = tjDimensionMainService.getTjDimensionMainByCode(tjQuotaDimensionMain.getMainCode());
               if(tjDimensionMain !=null){
                   map.put(tjDimensionMain.getCode(),tjDimensionMain.getName() + "-" + tjDimensionMain.getCode());
               }
//                main ++;
            }
            tjQuotaDimensionSlaves = tjQuotaDimensionSlaveService.getTjQuotaDimensionSlaveByCode(quotaCode[i]);

            int slave = 1;
            for(TjQuotaDimensionSlave tjQuotaDimensionSlave : tjQuotaDimensionSlaves){
                TjDimensionSlave  tjDimensionSlave =  tjDimensionSlaveService.getTjDimensionSlaveByCode(tjQuotaDimensionSlave.getSlaveCode());
                if(tjDimensionSlave != null){
                    map.put(tjDimensionSlave.getCode(), tjDimensionSlave.getName()+"-slaveKey" + slave);//第几个维度
                }
                slave ++;
            }
            dimensionMap.put(quotaCode[i],map);
        }

        //取出第一个指标的所有维度
        Map<String,String> tempMap = new LinkedHashMap();
        for(String quotaCodeKey:dimensionMap.keySet() ){
            Map<String,String> codeMap = dimensionMap.get(quotaCodeKey);
            for(String dimenCode: codeMap.keySet()){
                tempMap.put(dimenCode, codeMap.get(dimenCode));
            }
            break;
        }

        //用于保存共同交集的指标 key 保存交集的维度code
        //value 保存 此维度在每个指标统计的结果集中对应的字段名称
        Map<String,Map<String,String>> synthesiseMap = new LinkedHashMap<>();

        Map<String,String> saveModelMap = new LinkedHashMap();
        //其他指标与第一个指标维度对比，如果在第一个指标中都存在 交集维度
        for(String tempDimenCode:tempMap.keySet() ){
            int num = 0;
            String quotaCodeStr = "";
            for(String keyCode:dimensionMap.keySet() ){
                quotaCodeStr = keyCode;
                Map<String,String> codeMap = dimensionMap.get(keyCode);
                for(String code: codeMap.keySet()){
                    if( code.equals(tempDimenCode) &&  tempMap.get(tempDimenCode).equals(codeMap.get(code))){
                        saveModelMap.put(quotaCodeStr + "-"+ tempDimenCode ,  tempMap.get(tempDimenCode) );
                        //指标code + 维度编码 ->  科室-slaveKey2
                        num ++;
                    }
                }
            }
            if(num == dimensionMap.size()){
                Map<String,String> modelCloumnMap = new LinkedHashMap();
                modelCloumnMap.put("name",tempMap.get(tempDimenCode).split("-")[0]);
                for(String keyCode:dimensionMap.keySet() ){
                    if(saveModelMap.containsKey(keyCode+"-"+ tempDimenCode)) {
                        String str = keyCode+"-"+ tempDimenCode;
                        if(saveModelMap.get(str).contains(tempDimenCode)){
                            modelCloumnMap.put(keyCode,tempDimenCode);
                        }
                        if(saveModelMap.get(str).contains("slaveKey")){
                            modelCloumnMap.put(keyCode,saveModelMap.get(str).split("-")[1]);
                        }
                    }
                }
                synthesiseMap.put(tempDimenCode,modelCloumnMap);
            }
        }

        List<Map<String,String>> resultList = new ArrayList<>();
        for(String key : synthesiseMap.keySet()){
            resultList.add(synthesiseMap.get(key));
        }
        return  resultList;
    }


    @RequestMapping(value = ServiceApi.TJ.GetTjQuotaSynthesiseDimensionKeyVal, method = RequestMethod.GET)
    @ApiOperation(value = "查询多个指标交集维度的字典项")
    public  Map<String, Map<String, Object>>  getTjQuotaSynthesiseDimensionKeyVal(
            @ApiParam(name = "quotaCode", value = "指标code多个指标其中一个")
            @RequestParam(value = "quotaCode") String quotaCode,
            @ApiParam(name = "dimensions", value = "维度编码，多个维度用英文,分开")
            @RequestParam(value = "dimensions") String dimensions) throws Exception {

        List<TjQuotaDimensionMain> tjQuotaDimensionMains = null;
        List<TjQuotaDimensionSlave> tjQuotaDimensionSlaves = null;
        String [] dimensionArr = dimensions.split(",");

        Map<String, Map<String, Object>> resultMap = new HashMap<String, Map<String, Object>>();
        tjQuotaDimensionMains = tjQuotaDimensionMainService.getTjQuotaDimensionMainByCode(quotaCode);
        if (tjQuotaDimensionMains != null){
            for (TjQuotaDimensionMain tjQuotaDimensionMain : tjQuotaDimensionMains){
                for (int i=0 ;i < dimensionArr.length ; i++){
                    if (dimensionArr[i].equals(tjQuotaDimensionMain.getMainCode())){
                        Map<String, Object> map = new HashedMap();
                        List<String> list = new ArrayList<String>();
                        TjDimensionMain tjDimensionMain = tjDimensionMainService.getTjDimensionMainByCode(tjQuotaDimensionMain.getMainCode());
                        //查询字典数据
                        List<SaveModel> dictData = jdbcTemplate.query(tjQuotaDimensionMain.getDictSql(), new BeanPropertyRowMapper(SaveModel.class));
                        if (dictData != null ){
                            for (SaveModel saveModel : dictData){
                                try {
                                    String name = getFieldValueByName(tjQuotaDimensionMain.getMainCode() + "Name", saveModel).toString();
//                                String val = getFieldValueByName(tjQuotaDimensionMain.getMainCode(),saveModel).toString();
                                    list.add(name);
                                } catch (Exception e) {
                                    logger.error(e.getMessage());
                                }
                            }
                            map.put("key", tjQuotaDimensionMain.getMainCode() + "Name");
                            map.put("name", tjDimensionMain.getName());
                            map.put("value", list);
                            resultMap.put(tjQuotaDimensionMain.getMainCode(), map);
                        }
                    }
                }
            }
        }

        tjQuotaDimensionSlaves = tjQuotaDimensionSlaveService.getTjQuotaDimensionSlaveByCode(quotaCode);
        if (tjQuotaDimensionSlaves != null && tjQuotaDimensionSlaves.size() > 0){
            for(int i=0 ;i < dimensionArr.length ; i++){
                String slave = "slaveKey1,slaveKey2,slaveKey3";
                if( slave.contains(dimensionArr[i]) ){
                    Map<String, Object> map = new HashedMap();
                    List<String> list = new ArrayList<String>();
                    int num = Integer.valueOf(dimensionArr[i].substring(dimensionArr[i].length() - 1, dimensionArr[i].length()));
                    TjDimensionSlave tjDimensionSlave = tjDimensionSlaveService.getTjDimensionSlaveByCode(tjQuotaDimensionSlaves.get(num - 1).getSlaveCode());

                    //查询字典数据
                    List<DictModel> dictDataList = jdbcTemplate.query(tjQuotaDimensionSlaves.get(num-1).getDictSql(), new BeanPropertyRowMapper(DictModel.class));
                    if(dictDataList != null ){
                        for(DictModel dictModel :dictDataList){
                            String name = getFieldValueByName("name",dictModel).toString();
                            //String val = getFieldValueByName("code",dictModel).toString();
                            list.add(name);
                        }
                        map.put("key",dimensionArr[i]+"Name");
                        map.put("name",tjDimensionSlave.getName());
                        map.put("value",list);
                        resultMap.put(dimensionArr[i], map);
                    }
                }
            }
        }
        return resultMap;
    }


    /**
     * 根据属性名获取属性值
     * */
    private Object getFieldValueByName(String fieldName, Object o) throws Exception {
        String firstLetter = fieldName.substring(0, 1).toUpperCase();
        String getter = "get" + firstLetter + fieldName.substring(1);
        Method method = o.getClass().getMethod(getter, new Class[] {});
        Object value = method.invoke(o, new Object[] {});
        return value;
    }


}
