package com.nmgs.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nmgs.entity.*;
import com.nmgs.mapper.*;
import com.nmgs.service.IServiceAreaService;
import com.nmgs.util.LogUtil;
import com.nmgs.util.PropertiesUtil;
import com.nmgs.util.PubTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.nmgs.util.PubTools.ClobToString;


@Service
@Slf4j
public class ServiceAreaServiceImpl implements IServiceAreaService {
    @Autowired
    public Mapper mapperI;
    private static String  DBType= PropertiesUtil.getValue("DBType");
    public ServiceAreaPicServiceImpl serviceAreaPicServiceImpl;
    @Autowired
    public void setServiceAreaPicServiceImpl(ServiceAreaPicServiceImpl serviceAreaPicServiceImpl) {
        this.serviceAreaPicServiceImpl = serviceAreaPicServiceImpl;
    }

    public ServiceAreaSpecialServiceImpl serviceAreaSpecialServiceImpl;
    @Autowired
    public void setServiceAreaSpecialServiceImpl(ServiceAreaSpecialServiceImpl serviceAreaSpecialServiceImpl) {
        this.serviceAreaSpecialServiceImpl = serviceAreaSpecialServiceImpl;
    }

    public SerivceAreaOperationMealServiceImpl serivceAreaOperationMealServiceImpl;
    @Autowired
    public void setSerivceAreaOperationMealServiceImpl(SerivceAreaOperationMealServiceImpl serivceAreaOperationMealServiceImpl) {
        this.serivceAreaOperationMealServiceImpl = serivceAreaOperationMealServiceImpl;
    }

    private static String sqlStart="SELECT\n" +
           "\tarea.ID,\n" +
           "\tarea.AREANAME,\n" +
            "\t(area.AREANAME||'('||sapt.TEXT||')') AS AREANAMEPOSITION,\n" +
           "\tarea.SERVICETYPE,\n" +
           "\tarea.LAT,\n" +
           "\tarea.LNG,\n" +
           "\tarea.SERVICEKIND,\n" +
           "  (select LISTAGG ( kind.TEXT, ', ' ) WITHIN GROUP ( ORDER BY kind.VALUE )  from service_area_kind_text kind where INSTR( area.SERVICEKIND, kind.VALUE ) > 0 GROUP BY area.SERVICEKIND) AS SERVICEKINDNAME,\n" +
           "\tarea.SERVICEFEETYPE,\n" +
           "  (select LISTAGG ( kind2.TEXT, ', ' ) WITHIN GROUP ( ORDER BY kind2.VALUE )  from service_area_kind_text kind2 where INSTR( area.SERVICEFEETYPE, kind2.VALUE ) > 0 AND kind2.VALUE >=50 GROUP BY area.SERVICEFEETYPE) AS SERVICEFEETYPENAME,\n" +
            "@PICPARAM AS PICDATA,"+
            "(SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL," +
            "area.CODE AS CODE,"+
            "area.ROADNO AS ROADNO,"+
            "sart.TEXT AS ROADNONAME,"+
            "area.OPEN AS OPEN,"+
            " case when area.OPEN=0 then '关闭' else '开放' END  AS OPENNAME,"+
           "\tTYPE.TEXT AS SERVICETYPENAME \n" +
           "\t FROM\n" +
           "\tservice_area_table area\n" +
            "\tLEFT JOIN SERVICE_AREA_POSITION_TEXT sapt ON sapt.VALUE = area.POSITION\n" +
            "\tLEFT JOIN SERVICE_AREA_ROAD_TEXT sart  ON sart.VALUE = area.ROADNO\n" +
           "\tLEFT JOIN service_area_TYPE_text TYPE ON TYPE.VALUE = area.SERVICETYPE WHERE 1=1  " ;
    private static String sqlEnd=" ";
static{
    if("4".equals(DBType)){
        sqlStart="SELECT\n" +
                "\tarea.ID,\n" +
                "\tarea.AREANAME,\n" +
                "\tconcat(area.AREANAME,'(',sapt.TEXT,')') AS AREANAMEPOSITION,\n" +
                "\tarea.SERVICETYPE,\n" +
                "\tarea.SERVICEKIND,\n" +
                "\tarea.LAT,\n" +
                "\tarea.LNG,\n" +
                " (select GROUP_CONCAT(DISTINCT kind.TEXT ORDER BY kind.VALUE Separator ',')  from service_area_kind_text kind where INSTR( area.SERVICEKIND, kind.VALUE ) > 0 GROUP BY area.SERVICEKIND)    AS SERVICEKINDNAME,\n" +
                "\tarea.SERVICEFEETYPE,\n" +
                "(select GROUP_CONCAT(DISTINCT kind2.TEXT ORDER BY kind2.VALUE Separator ',')  from service_area_kind_text kind2 where INSTR( area.SERVICEFEETYPE, kind2.VALUE ) > 0 AND kind2.VALUE >=50 GROUP BY area.SERVICEFEETYPE)     AS SERVICEFEETYPENAME,\n" +
                "@PICPARAM AS PICDATA,"+
                "(SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL," +
                "area.CODE AS CODE,"+
                "area.ROADNO AS ROADNO,"+
                "sart.TEXT AS ROADNONAME,"+
                "area.OPEN AS OPEN,"+
                " case when area.OPEN=0 then '关闭' else '开放' END  AS OPENNAME,"+
                "\tTYPE.TEXT AS SERVICETYPENAME \n" +
                "\t FROM\n" +
                "\tservice_area_table area\n" +
                "\tLEFT JOIN SERVICE_AREA_POSITION_TEXT sapt  ON sapt.VALUE = area.POSITION\n" +
                "\tLEFT JOIN SERVICE_AREA_ROAD_TEXT sart  ON sart.VALUE = area.ROADNO\n" +
                "\tLEFT JOIN service_area_TYPE_text TYPE ON TYPE.VALUE = area.SERVICETYPE WHERE 1=1  " ;

        sqlEnd=" ";
    }
}

    @Override
    public List getServiceAreaList(String areaName,String areaScope,String showPic,int start,int end) {
        List ret=null;
        List retlist=new ArrayList();
        String sqlTemp=sqlStart;
        try{
            if("2".equals(DBType)){//oralce数据库
                if(!PubTools.isNull(areaName)){
                    sqlTemp += " and area.AREANAME like '%"+areaName+"%'";
                }
                if(!PubTools.isNull(areaScope)){
                    if("SPECIAL".equals(areaScope)){//特殊服务区
                        sqlTemp += " and area.SERVICETYPE =2";
                    }else if("FCA".equals(areaScope)){//餐饮预约服务区
                        sqlTemp += " and area.ID in(select distinct saot1.SERVICEAREAID from SERVICE_AREA_OPERATORS_TABLE saot1,SERVICE_AREA_OPERATION_MEAL_TABLE saomt1 WHERE saomt1.JOBNUMBER = saot1.JOBNUMBER )";
                    }else if("FOA".equals(areaScope)){//加油预约服务区
                        sqlTemp += " and instr(area.SERVICEFEETYPE,'52') >0";
                    }else{
                    }
                }

                sqlTemp += sqlEnd+" order by area.AREANAME";
                String sqlStartTemp = "SELECT ROWNUM AS NUM,ID,AREANAME,AREANAMEPOSITION,SERVICETYPE,SERVICEKIND,SERVICEKINDNAME,SERVICETYPENAME,PICDATA,CODE,ROADNO,ROADNONAME,OPEN,OPENNAME,SERVICEFEETYPE,PICURL,SERVICEFEETYPENAME,LAT,LNG FROM(" + sqlTemp + ") WHERE 1=1 ";
                if(start>0){
                    sqlStartTemp +=" AND ROWNUM <="+end;
                }
                if(start==0 && end==0){
                        if(PubTools.isNull(showPic) || "N".equals(showPic)){
                            sqlTemp= sqlTemp.replace("@PICPARAM","''");
                        }else{
                            sqlTemp=sqlTemp.replace("@PICPARAM","(SELECT PICDATA FROM (SELECT sapt.PICDATA,ROWNUM AS rank FROM SERVICE_AREA_PIC_TABLE sapt WHERE 1=1 AND SERVICEID=area.ID\n" +
                                    ")temp where rank<2)");
                        }

                    ret= this.mapperI.selectforlist(sqlTemp);
                }else{
                    String startSql = "SELECT ID,AREANAME,AREANAMEPOSITION,SERVICETYPE,SERVICEKIND,SERVICEKINDNAME,SERVICETYPENAME,PICDATA,CODE,ROADNO,ROADNONAME,PICURL,OPEN,OPENNAME,SERVICEFEETYPE,SERVICEFEETYPENAME,LAT,LNG" +
                            " FROM("+sqlStartTemp+")tt where tt.NUM >= "+start;

                        if(PubTools.isNull(showPic) || "N".equals(showPic)){
                            startSql= startSql.replace("@PICPARAM","''");
                        }else{
                            startSql= startSql.replace("@PICPARAM","(SELECT PICDATA FROM (SELECT sapt.PICDATA,ROWNUM AS rank FROM SERVICE_AREA_PIC_TABLE sapt WHERE 1=1 AND SERVICEID=area.ID\n" +
                                    ")temp where rank<2)");
                        }

                    ret= this.mapperI.selectforlist(startSql);
                }
            }else if("4".equals(DBType)){//mysql数据库
                if(!PubTools.isNull(areaName)){
                    sqlTemp += " and area.AREANAME like '%"+areaName+"%'";
                }
                if(!PubTools.isNull(areaScope)){
                    if("SPECIAL".equals(areaScope)){
                        sqlTemp += " and area.SERVICETYPE =2";
                    }
                }
                if(PubTools.isNull(showPic) || "N".equals(showPic)){
                    sqlTemp=sqlTemp.replace("@PICPARAM","''");
                }else{
                    sqlTemp= sqlTemp.replace("@PICPARAM","(SELECT sapt.PICDATA FROM SERVICE_AREA_PIC_TABLE sapt,(Select @i:=0) B WHERE 1=1 AND sapt.SERVICEID=area.ID AND (@i+1) <2)");
                }
                sqlTemp += sqlEnd+" order by area.AREANAME";
                if(start>0){
                    sqlTemp +=" Limit "+(start-1)+","+(end-start+1);
                }
                if(start==0 && end==0){
                    ret= this.mapperI.selectforlist(sqlTemp);
                }else{
                    String startSql = "SELECT ID,AREANAME,AREANAMEPOSITION,SERVICETYPE,SERVICEKIND,SERVICEKINDNAME,SERVICETYPENAME,PICDATA,CODE,ROADNO,ROADNONAME,OPEN,OPENNAME,SERVICEFEETYPE,SERVICEFEETYPENAME,PICURL,LAT,LNG FROM(" + sqlTemp + ")tt";
                    if(PubTools.isNull(showPic) || "N".equals(showPic)){
                        startSql= startSql.replace("@PICPARAM","''");
                    }else{
                        startSql= startSql.replace("@PICPARAM","(SELECT sapt.PICDATA FROM SERVICE_AREA_PIC_TABLE sapt,(Select @i:=0) B WHERE 1=1 AND sapt.SERVICEID=area.ID AND (@i+1) <2)");
                    }
                    ret= this.mapperI.selectforlist(startSql);
                }
            }else{}
            if(ret.size()>0 && start>0 &&  "Y".equals(showPic)){
                for(Object obj:ret){
                    Map<String, Object> obj1 = (Map<String, Object>) obj;
                    if(!PubTools.isEmpty(obj1.get("PICDATA")) ){
                        Object o=obj1.get("PICDATA");
                        String s = PubTools.ClobToString(o);
                        if(!PubTools.isNull(s)){
                            obj1.remove("PICDATA");
                            obj1.put("PICDATA",s);
                        }
                    }else{
                        obj1.put("PICDATA","");
                    }
                    retlist.add(obj1);
                }
            }else{
                retlist=ret;
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询服务区列表失败：===>"+e.getMessage(),"ServiceAreaServiceImpl");
            return retlist=new ArrayList();
        }
        return retlist;
    }

    @Override
    public List getServiceAreaDetail(String serviceId) {
        List list=null;
        List retList=new ArrayList();
        String sqlTemp=sqlStart;
        try{
            if(!PubTools.isNull(serviceId)){
                sqlTemp += " AND (area.ID = "+serviceId+" OR area.CODE ='"+serviceId+"')";
            }
            sqlTemp += sqlEnd+" order by area.AREANAME";
            sqlTemp=sqlTemp.replace("@PICPARAM","''");
            list= this.mapperI.selectforlist(sqlTemp);
            List serviceAreaPicList = this.serviceAreaPicServiceImpl.getServiceAreaPicList(serviceId);
            List serviceAreaSpecialList = this.serviceAreaSpecialServiceImpl.getServiceAreaSpecialList(serviceId);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("SERVICEINFO",list);
            map.put("SERVICEPIC",(serviceAreaPicList != null && serviceAreaPicList.size()>0)?serviceAreaPicList:new ArrayList());
            map.put("SERVICESPECIAL",(serviceAreaSpecialList != null && serviceAreaSpecialList.size()>0)?serviceAreaSpecialList:new ArrayList());
            retList.add(map);
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询服务区详细信息失败：===>"+e.getMessage(),"ServiceAreaServiceImpl");
            return retList=null;
        }
        return retList;
    }

    @Override
    public List getAreaMealList(String operatorId, String areaId,String ids) {
        List list=null;

        String operatorSql=" SELECT\n" +
                "            oper.ID,\n" +
                "            oper.JOBNUMBER,\n" +
                //"            oper.JOBNUMBERINFO,\n" +
               // "            oper.ROLEID,\n" +
                "            oper.SERVICEAREAID,\n" +
                "            oper.USERNAME,\n" +
                "            oper.STROEPIC,\n" +
                "            oper.PHONE,\n" +
                "            oper.POSITION,\n" +
                "            (SELECT IPS.BAK1 FROM INTEGRAL_PUBLIC_SET ips WHERE IPS.PARAMCODE='PICURL') AS PICURL,\n" +
                "            oper.OPENTIME,\n" +
                "            oper.OPEN,\n" +
                "            case when oper.OPEN=0 then '暂停服务' else '营业中' end AS OPENNAME,\n" +
                //"            oper.PASSWORD,\n" +
               // "            r.VALUE as roleName,\n" +
                "            area.AREANAME as SERVICEAREANAME" +
                "        FROM\n" +
                "        service_area_operators_table  oper\n" +
                "        LEFT JOIN service_area_table area on area.ID = oper.SERVICEAREAID\n" +
                "        LEFT JOIN service_area_operators_role_text r on r.ID = oper.ROLEID WHERE 1=1 AND EXISTS(" +
                "SELECT 1 FROM SERVICE_AREA_OPERATION_MEAL_TABLE saomt1 WHERE saomt1.JOBNUMBER = oper.JOBNUMBER)";
        List retList=new ArrayList();
        try{
            if(!PubTools.isNull(operatorId)){
                operatorSql += " and oper.ID = "+operatorId+"";
            }
            if(!PubTools.isNull(areaId)){
                operatorSql += " and oper.SERVICEAREAID = "+areaId+"";
            }
            list= this.mapperI.selectforlist(operatorSql);
            if(list != null && list.size()>0){
                for(Object obj:list){
                    Map<String, Object> obj1 = (Map<String, Object>) obj;
                    Object o=obj1.get("STROEPIC");
                    String s = PubTools.ClobToString( o);
                    if(!PubTools.isNull(s)){
                        obj1.remove("STROEPIC");
                        obj1.put("STROEPIC",s);
                    }else{
                        obj1.remove("STROEPIC");
                        obj1.put("STROEPIC","");
                    }
                    //查询商超的套餐ID
                    List jobnumber = this.serivceAreaOperationMealServiceImpl.getAreaMealList(obj1.get("JOBNUMBER").toString());
                    obj1.put("MEALSINFO",jobnumber);
                    retList.add(obj1);
                }
            }else{
                retList=list;
            }
        }catch (Exception e){
            LogUtil.WriteLog_Error("查询服务区套餐列表失败：===>"+e.getMessage(),"ServiceAreaServiceImpl");
            return retList=null;
        }
        return retList;
    }

}
