package com.fjs.scenic.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fjs.scenic.cyt.utils.Base64Util;
import com.fjs.scenic.service.user.StatisticalPermissionsService;
import com.fjs.scenic.service.user.UserStatisticalService;
import com.fjs.scenic.utils.Cons;
import com.fjs.scenic.utils.HttpReq;
import com.fjs.scenic.utils.ReturnResult;
import com.google.gson.JsonObject;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 领导决策
 */
@RestController
@RequestMapping("/api/decision")
public class DecisionAnalysisController {

    private Logger log = LoggerFactory.getLogger(DressController.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StatisticalPermissionsService statisticalPermissionsService;
    @Autowired
    private UserStatisticalService userStatisticalService;

    /**
     * 请求地址http://fx.fjsfjq.com/service/distributor.do
     */
    //private static final String url = "http://192.168.100.221:8081/services/cytDataService/doWxQueryRequest.action";
    private static final String url = "http://w.fjsstlyq.com:8082/services/cytDataService/doWxQueryRequest.action";

    @ApiOperation(value = "获取决策权限集合", notes = "获取决策权限集合")
    @PostMapping(value = "/getPermission")
    public ReturnResult getPermission(HttpServletRequest request) throws Exception {
        Integer userId = getUserId(request);
        return ReturnResult.ok(statisticalPermissionsService.selectByUserID(userId));
    }

    @ApiOperation(value = "验证秘钥", notes = "验证秘钥")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "secretKey", dataType = "string", value = "秘钥", required = true, paramType = "query"),
    })
    @PostMapping(value = "/verifySecretKey")
    public ReturnResult verifySecretKey(HttpServletRequest request, String secretKey) throws Exception {
        Integer userId = getUserId(request);
        return ReturnResult.ok(userStatisticalService.verifySecretKey(userId, secretKey));
    }

    @ApiOperation(value = "更新秘钥", notes = "更新秘钥")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldKey", dataType = "string", value = "原秘钥", required = true, paramType = "query"),
            @ApiImplicitParam(name = "newKey", dataType = "string", value = "新秘钥", required = true, paramType = "query"),
    })
    @PostMapping(value = "/updateSecretKey")
    public ReturnResult updateSecretKey(HttpServletRequest request, String oldKey, String newKey) throws Exception {
        Integer userId = getUserId(request);
        if (!userStatisticalService.verifySecretKey(userId, oldKey)) {
            return ReturnResult.error("原密码验证失败");
        } else if (!userStatisticalService.updateSecretKeyByUserId(userId, newKey)) {
            return ReturnResult.error("密码修改失败");
        } else {
            return ReturnResult.OK("密码修改成功");
        }
    }

    @ApiOperation(value = "销售总金额接口", notes = "销售总金额接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-09-25", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-09-25", dataType = "string", value = "结束时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "qtype", defaultValue = "H", dataType = "string", value = "返回类型：Y,M,D,H", required = true, paramType = "query")
    })
    @PostMapping("/saleTotalAmount")
    public ReturnResult saleTotalAmount(HttpServletRequest request, String starttime, String endtime, String qtype) throws Exception {
        Integer userId = getUserId(request);
        String permissionsStr = getPermissionsStr(userId);
        if (permissionsStr.equals("")) {//没权限返回空
            return ReturnResult.ok();
        }
        String data = "{starttime:'" + starttime + "',endtime:'" + endtime + "',userid:" + userId + ",pressId:1,qtype:'" + qtype + "'}";
        JSONObject responseJSONObject = HttpReq.sendPost(url, "saleTotalAmount", data);
        String code = (String) responseJSONObject.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = getDataStr(responseJSONObject);
            dataStr = getNewDataStr("saleTotalAmount", dataStr);
            List<JSONObject> jsonObject = JSONArray.parseArray(dataStr).toJavaList(JSONObject.class);
            //根据权限 值处理
            return ReturnResult.ok(assembleBySaleTotalAmount(jsonObject.get(0), permissionsStr));
        } else {
            //返回错误信息
            return ReturnResult.build(Integer.parseInt(code), (String) responseJSONObject.get("describe"));
        }
    }

    /**
     * 根据方法名称 替换字段
     *
     * @param methodName 接口名称
     * @param dataStr    要替换的string
     * @return
     */
    private String getNewDataStr(String methodName, String dataStr) {
        switch (methodName) {
            case "saleTotalAmount":
                dataStr = dataStr.replace("XMMPS", "XMTICKET");
                dataStr = dataStr.replace("DMMPS", "DMTICKET");
                dataStr = dataStr.replace("XMMPNUM", "XMMPXSS");
                dataStr = dataStr.replace("DMMPNUM", "DMMPXSS");
                break;
            case "sale24Trend":
                dataStr = dataStr.replace("XMMPNUM", "XMTICKET");
                dataStr = dataStr.replace("DMMPNUM", "DMTICKET");
                break;
            case "scenicLiveIn":
                dataStr = dataStr.replace("XMPS", "XMTICKET");
                dataStr = dataStr.replace("DMPS", "DMTICKET");
                break;
            case "saleChannel":
                dataStr = dataStr.replace("XMMPNUM", "XMTICKET");
                dataStr = dataStr.replace("DMMPNUM", "DMTICKET");
                break;
            default:
                break;
        }
        return dataStr;
    }

    @ApiOperation(value = "销售24小时走势图", notes = "销售24小时走势图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-09-25", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-09-25", dataType = "string", value = "结束时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "qtype", defaultValue = "H", dataType = "string", value = "返回类型：Y,M,D,H", required = true, paramType = "query")
    })
    @PostMapping("/sale24Trend")
    public ReturnResult sale24Trend(HttpServletRequest request, String starttime, String endtime, String qtype) throws Exception {
        return commonPost(request, starttime, endtime, 1, qtype, "sale24Trend");
    }

    @ApiOperation(value = "销售渠道金额", notes = "售渠道金额")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-10-14", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-10-14", dataType = "string", value = "结束时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "qtype", defaultValue = "H", dataType = "string", value = "返回类型：Y,M,D,H", required = true, paramType = "query")
    })
    @PostMapping("/saleChannel")
    public ReturnResult saleChannel(HttpServletRequest request, String starttime, String endtime, String qtype) throws Exception {
        return commonPost(request, starttime, endtime, 1, qtype, "saleChannel");
    }

    @ApiOperation(value = "景区实况 概况", notes = "景区实况 概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-09-25", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-09-25", dataType = "string", value = "结束时间", required = true, paramType = "query")
    })
    @PostMapping("/scenicLive")
    public ReturnResult scenicLive(HttpServletRequest request, String starttime, String endtime) throws Exception {
        return commonPost(request, starttime, endtime, 1, "H", "scenicLive");
    }

    @ApiOperation(value = "景区实况 入园情况", notes = "景区实况 入园情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-09-25", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-09-25", dataType = "string", value = "结束时间", required = true, paramType = "query")
    })
    @PostMapping("/scenicLiveIn")
    public ReturnResult scenicLiveIn(HttpServletRequest request, String starttime, String endtime) throws Exception {
        Integer userId = getUserId(request);
        String permissionsStr = getPermissionsStr(userId);
        if (permissionsStr.equals("")) {//没权限返回空
            return ReturnResult.ok();
        }
        String data = "{starttime:'" + starttime + "',endtime:'" + endtime + "',userid:" + userId + ",pressId:1,qtype:'H'}";
        JSONObject responseJSONObject = HttpReq.sendPost(url, "scenicLiveIn", data);
        String code = (String) responseJSONObject.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = getDataStr(responseJSONObject);
            dataStr = getNewDataStr("scenicLiveIn", dataStr);
//            List<JSONObject> jsonObject = JSONArray.parseArray(dataStr).toJavaList(JSONObject.class);
            JSONObject jsonObject = JSONObject.parseObject(dataStr);
            jsonObject.put("prenum", assembleByPermissions((List<JSONObject>) jsonObject.get("prenum"), permissionsStr));
            jsonObject.put("innum", assembleByPermissions((List<JSONObject>) jsonObject.get("innum"), permissionsStr));
            //根据权限 值处理
            return ReturnResult.ok(jsonObject);
        } else {
            //返回错误信息
            return ReturnResult.build(Integer.parseInt(code), (String) responseJSONObject.get("describe"));
        }


//        return commonPost(request, starttime, endtime, 1, "H", "scenicLiveIn");
    }

    @ApiOperation(value = "景区实况 观光车、索道上下行检票情况", notes = "景区实况 观光车、索道上下行检票情况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-07-01", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-07-01", dataType = "string", value = "结束时间", required = true, paramType = "query")
    })
    @PostMapping("/scenicSaleCheck")
    public ReturnResult scenicSaleCheck(HttpServletRequest request, String starttime, String endtime) throws Exception {
        return commonPost(request, starttime, endtime, 1, "H", "scenicSaleCheck");
    }

    @ApiOperation(value = "景区实况 渠道预定人数", notes = "景区实况 渠道预定人数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "starttime", defaultValue = "2019-09-25", dataType = "string", value = "开始时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "endtime", defaultValue = "2019-09-25", dataType = "string", value = "结束时间", required = true, paramType = "query")
    })
    @PostMapping("/scenicChannel")
    public ReturnResult scenicChannel(HttpServletRequest request, String starttime, String endtime) throws Exception {
        Integer userId = getUserId(request);
        return commonPost(request, starttime, endtime, 1, "H", "scenicChannel");
    }

    /**
     * 通用请求
     *
     * @param request
     * @param starttime  开始时间
     * @param endtime    结束时间
     * @param pressId    权限标识
     * @param methodName 方法名称
     * @return
     * @throws Exception
     */
    public ReturnResult commonPost(HttpServletRequest request, String starttime, String endtime, int pressId, String qtype, String methodName) throws Exception {
        Integer userId = getUserId(request);
        String permissionsStr = getPermissionsStr(userId);
        if (permissionsStr.equals("")) {//没权限返回空
            return ReturnResult.ok();
        }

        String data = "{starttime:'" + starttime + "',endtime:'" + endtime + "',userid:" + userId + ",pressId:" + pressId + ",qtype:'" + qtype + "'}";
        JSONObject responseJSONObject = HttpReq.sendPost(url, methodName, data);
        return commonBack(responseJSONObject, permissionsStr, methodName);
    }

    /**
     * 通用返回
     *
     * @param responseJSONObject
     * @return
     */
    public ReturnResult commonBack(JSONObject responseJSONObject, String permissionsStr) throws Exception {
        return commonBack(responseJSONObject, permissionsStr, null);
    }

    /**
     * 通用返回
     *
     * @param responseJSONObject
     * @return
     */
    public ReturnResult commonBack(JSONObject responseJSONObject, String permissionsStr, String methodName) throws Exception {
        String code = (String) responseJSONObject.get("code");
        if (code.equals("200")) {
            String dataStr = getDataStr(responseJSONObject);
            dataStr = getNewDataStr(methodName, dataStr);
            if (dataStr.indexOf('[') == 0) {
                //获取解密数组json数据
                List<JSONObject> jasonObject = JSONArray.parseArray(dataStr).toJavaList(JSONObject.class);
                //查询无数据
                if (jasonObject == null) {
                    return ReturnResult.ok("[]");
                } else {
                    //根据权限 配值
                    jasonObject = assembleByPermissions(jasonObject, permissionsStr);
                    return ReturnResult.ok(jasonObject);
                }
            } else {
                List<JSONObject> JSONObjectList = new ArrayList<>();
                //获取解密json数据
                JSONObject jasonObject = JSONObject.parseObject(dataStr);
                //根据权限 配值
                JSONObjectList.add(jasonObject);
                jasonObject = assembleByPermissions(JSONObjectList, permissionsStr).get(0);
                return ReturnResult.ok((jasonObject == null) ? "{}" : jasonObject);
            }
        } else {
            //返回错误信息
            return ReturnResult.build(Integer.parseInt(code), (String) responseJSONObject.get("describe"));
        }
    }

    /**
     * 获取权限str
     *
     * @param userId
     * @return
     * @throws Exception
     */
    public String getPermissionsStr(Integer userId) {
        List<HashMap<String, Object>> permissions = statisticalPermissionsService.selectByUserID(userId);
        String permissionsStr = "";
        for (HashMap<String, Object> item : permissions) {
            if (item.get("user_id") != null) {
                permissionsStr = permissionsStr + item.get("code") + ",";
            }
        }
        return permissionsStr.length() == 0 ? "" : permissionsStr.substring(0, permissionsStr.length() - 1);
    }

    /**
     * 根据权限配值
     *
     * @param jasonObject
     * @param permissionsStr
     * @return
     * @throws Exception
     */
    public List<JSONObject> assembleByPermissions(List<JSONObject> jasonObject, String permissionsStr) throws Exception {
//        根据权限配值
        Class class1 = Cons.DECISION_PERMISSIONS.class;
        Field[] fields = class1.getDeclaredFields();
        List<String> permissionsArr = Arrays.asList(permissionsStr.split(","));
        for (Field field : fields) {
            if (!(permissionsArr.contains(field.get(class1).toString()))) {
                List<String> removeKeys = getRemoveKey(field.get(class1).toString().toUpperCase());
                for (JSONObject jsonObj : jasonObject) {
                    for (String removeKey : removeKeys) {
                        jsonObj.remove(removeKey);
                    }
                }
            }
        }
        return jasonObject;
    }

    /**
     * 获取要去除数据的key
     *
     * @param removeKey 权限key
     * @return
     */
    private List<String> getRemoveKey(String removeKey) {
        List<String> removeKeys = new ArrayList<>();
        removeKeys.add(removeKey);
        switch (removeKey) {
            case "EASTTICKET"://东线门票统计
                removeKeys.add("DMMPNUM");
                break;
            case "WESTTICKET"://西线门票统计
                removeKeys.add("XMMPNUM");
                break;
            case "EASTSLIVE"://东线景区实况
                removeKeys.add("prenum_dm");
                removeKeys.add("innum_dm");
                removeKeys.add("waitinnum_dm");
                removeKeys.add("DMTICKET");
                break;
            case "WESTSLIVE"://西线景区实况
                removeKeys.add("prenum_xm");
                removeKeys.add("innum_xm");
                removeKeys.add("waitinnum_xm");
                removeKeys.add("XMTICKET");
                break;
            default:
                break;
        }
        return removeKeys;
    }

    /**
     * SaleTotalAmount根据权限配值
     *
     * @param jasonObject
     * @param permissionsStr
     * @return
     * @throws Exception
     */
    public JSONObject assembleBySaleTotalAmount(JSONObject jasonObject, String permissionsStr) throws Exception {
//        根据权限配值
        jasonObject = jasonObject.getJSONObject("data");
        List<String> permissionsArr = Arrays.asList(permissionsStr.split(","));
        if (!permissionsArr.contains("ticket")) {
            //总门票
            jasonObject.remove("TICKET");
            jasonObject.remove("MPXSS");
        }
        if (!permissionsArr.contains("eastticket")) {
            //东线门票
            jasonObject.remove("DMTICKET");
            jasonObject.remove("DMMPXSS");
        }
        if (!permissionsArr.contains("westticket")) {
            //西线门票
            jasonObject.remove("XMTICKET");
            jasonObject.remove("XMMPXSS");
        }
        if (!permissionsArr.contains("cableway")) {
            //索道
            jasonObject.remove("CABLEWAY");
            jasonObject.remove("SPXSS");
            jasonObject.remove("SPXSSD");
            jasonObject.remove("SWFXSS");
        }
        if (!permissionsArr.contains("car")) {
            //观览车
            jasonObject.remove("CAR");
            jasonObject.remove("CPXSS");
            jasonObject.remove("CPXSSD");
            jasonObject.remove("CWFXSS");
        }
        if (!permissionsArr.contains("count")) {
            //总计
            jasonObject.remove("COUNT");
        }
        return jasonObject;
    }

    /**
     * 获取 数据解密
     *
     * @param parseObject2
     * @return
     * @throws Exception
     */
    public String getDataStr(JSONObject parseObject2) throws Exception {
        String object = (String) parseObject2.get("data");
        return Base64Util.decodeData(object);
    }

    /**
     * 获取userId
     *
     * @param request
     * @return
     */
    public Integer getUserId(HttpServletRequest request) {
        return (Integer) redisTemplate.opsForValue().get(request.getHeader(Cons.TOKEN.WECHAT));
        //return 64;
    }


    public static void main(String[] args) throws Exception {
        DecisionAnalysisController t1 = new DecisionAnalysisController();
        String url = "http://127.0.0.1:8080/services/cytDataService/doWxQueryRequest.action";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("date_end","2019-05-08");
        jsonObject.addProperty("travel","17770974051");
        
        
        //jsonObject.addProperty("travel","BHLXS197910");
        JSONObject test = HttpReq.sendPost(url, "travelTeamDeclare", jsonObject.toString());
        String code = (String) test.get("code");
        if (code.equals("200")) {
            //获取解密json数据
            String dataStr = t1.getDataStr(test);
//            List<JSONObject> jsonObjects = JSONArray.parseArray(dataStr).toJavaList(JSONObject.class);
            System.err.println(dataStr);
        }

    }
}
