package com.yihu.hos.rest.services.crawler;

import com.yihu.ehr.dbhelper.mongodb.MongodbHelper;
import com.yihu.hos.rest.common.dao.DatacollectDao;
import com.yihu.hos.rest.common.dao.DatacollectLogDao;
import com.yihu.hos.rest.models.standard.adapter.AdapterDatasetModel;
import com.yihu.hos.rest.models.standard.adapter.resultModel.AdapterMetadataResultDetailModel;
import com.yihu.hos.rest.services.standard.StdService;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.Result;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 推数据服务
 */
@Service
public class DatapushService {

    @Autowired
    private DatacollectDao datacollect;

    @Autowired
    private DatacollectLogDao datacollectLog;

    @Autowired
    private StdService stdService;

    MongodbHelper mongo = new MongodbHelper();

    /**
     * 转译字典
     */
    private String translateDictValue(String oldValue,String type,JSONArray dictAdapterList) throws Exception
    {
        //应用标准字段
        String colName = "adapterEntryCode";
        if(type.equals("0")) //通过name转译
        {
            colName = "adapterEntryValue";
        }

        //遍历字典数据
        for(int i=0; i< dictAdapterList.length();i++)
        {
            JSONObject dictItem = dictAdapterList.getJSONObject(i);
            if(oldValue.equals(dictItem.getString(colName)))
            {
                String newValue = dictItem.getString("stdEntryCode");
                return newValue;
            }
        }

        return oldValue;
    }


    /*****************************************************************************************************/

    /**
     * 数据入库
     */
    @Transactional
    public Result pushData(String datasetCode,String dataString,String orgCode) throws Exception
    {
        //机构标准版本
        String version = datacollect.getVersionByQLC(orgCode);
        //通过标准数据集名称获取适配关系
        AdapterDatasetModel dataset = stdService.getDatasetByCode(version,datasetCode);
        String msg = "";
        if(dataset!=null)
        {
            String datasetId = dataset.getAdapterDatasetId().toString();
            List<AdapterMetadataResultDetailModel> list = stdService.getDatacolByScheme(version,datasetId);
            if(list!=null && list.size()>0)
            {
                JSONArray array = new JSONArray(dataString);
                List<JSONObject> dataList = new ArrayList<>();

                if(array!=null && array.length()>0)
                {
                    for (int i=0;i<array.length();i++)
                    {
                        JSONObject obj = new JSONObject();
                        JSONObject data = (JSONObject)array.get(i);
                        //标准转换
                        for(AdapterMetadataResultDetailModel metadata : list)
                        {
                            String stdColName = metadata.getStdMetadataCode();
                            String adapterColName = metadata.getAdapterMetadataCode();
                            if(data.has(adapterColName))
                            {
                                String val = data.optString(adapterColName);
                                String newValue =val;
                                //判断是否字典
                                if(metadata.getStdDictId()!=null&&metadata.getStdDictId()!=0)
                                {
                                    //获取字典列表
                                    List dictString = stdService.getDictByScheme(version,metadata.getStdDictId().toString());
                                    JSONArray dictAdapterArray = new JSONArray(dictString);
                                    String type = "";
                                    if(metadata.getAdapterDataType()!=null)
                                    {
                                        type = metadata.getAdapterDataType().toString();
                                    }
                                    newValue = translateDictValue(val,type,dictAdapterArray);
                                }

                                obj.put(stdColName,newValue);
                            }
                        }

                        //org_code字段
                        obj.put("RSCOM_ORG_CODE",orgCode);
                        dataList.add(obj);
                    }
                }

                //MongoDB入库
                boolean b = mongo.insert(datasetCode,dataList);

                if(!b)
                {
                    if(mongo.errorMessage!=null && mongo.errorMessage.length()>0)
                    {
                        System.out.print(mongo.errorMessage);
                        msg = "Mongodb保存失败！（表："+datasetCode+",数据："+dataString+"）"+mongo.errorMessage;
                    }
                    else {
                        msg ="Mongodb保存失败！（表："+datasetCode+",数据："+dataString+"）";
                    }
                }



            }
        }
        else{
            msg ="适配标准不完善！";
        }

        //是否成功
        if(msg.length()>0)
        {
            //日志记录
            datacollectLog.addDataPushLog("1","0",msg);
            return ActionResult.error(msg);
        }
        else{
            msg = "数据入库成功！（表："+datasetCode+"）";
            //日志记录
            datacollectLog.addDataPushLog("1","1",msg);
            return ActionResult.success(msg);
        }
    }


}
