package com.liangjian.dataplatform.member.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersData;
import com.liangjian.dataplatform.member.entity.po.secondary.UserPointDesc;
import com.liangjian.dataplatform.member.entity.po.elasticsearch.UserPointLog;
import com.liangjian.dataplatform.member.entity.response.ResultObject;
import com.liangjian.dataplatform.member.entity.vo.request.BirdGirdRequest;
import com.liangjian.dataplatform.member.entity.vo.response.BirdGirdTableResponse2;
import com.liangjian.dataplatform.member.safe.Tuple3;
import com.liangjian.dataplatform.member.service.IUserPointLogService;
import com.liangjian.dataplatform.member.util.http.SimpleHttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/15
 */
@RestController
@RequestMapping("/userPointLog")
@Api(value = "用户积分记录控制器", tags = "用户积分记录控制器", description = "用户积分记录控制器")
public class UserPointLogController {
    @Autowired
    private IUserPointLogService iUserPointLogService;

    @Deprecated
    @PostMapping("/logs")
    @ApiOperation("首页的查询用户和积分")
    public Map<String,Object> index(HttpServletRequest request,
                                    @ApiParam(value = "查询条件") @RequestBody String filterJson) throws Exception {
        String ssoToken = request.getHeader("Sso-Token");
        String url = "http://119.130.113.245:8004/web/ES_Member/index";
        Tuple3<Boolean, String, Exception> result = SimpleHttpClient.httpPost(url, filterJson, Collections.singletonMap("Sso-Token", ssoToken));
        if(result.get_1()) {
            String json = result.get_2();
            ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Map<String,Object>>() {});
            Map<String,Object> obj = reader.readValue(json);
            List<Map<String,Object>> rows = (List<Map<String, Object>>) obj.get("items");
            rows = iUserPointLogService.relatedWithMember(rows);
            obj.put("items", rows);
            return obj;
        } else {
            throw result.get_3();
        }

    }

    @GetMapping("/logs")
    @ApiOperation(value = "查询积分记录")
    public Page<UserPointLog> query(@ApiParam(value = "页数", required = true) @RequestParam Integer page,
                                    @ApiParam(value = "每页数量", required = true) @RequestParam Integer size,
                                    @ApiParam(value = "密文手机号", required = true) @RequestParam String secretPhone,
                                    @ApiParam(value = "是否增加积分(true:增加，false:减少)") @RequestParam(required = false) Boolean increase) {
        if(increase != null ){
            return iUserPointLogService.queryBySecretPhoneAndIncrease(secretPhone,increase,page - 1 , size);
        } else {
            return iUserPointLogService.queryBySecretPhone(secretPhone,page - 1,size);
        }
    }

    @Deprecated
    @GetMapping("/logsCondition")
    @ApiOperation(value = "查询积分记录2")
    public Page<UserPointLog> query(@ApiParam(value = "终端名称") @RequestParam(required = false) String terminal,
                                    @ApiParam(value = "终端编码") @RequestParam(required = false) String terminalCode,
                                    @ApiParam(value = "用户行为") @RequestParam(required = false) String action,
                                    @ApiParam(value = "开始时间") @RequestParam(required = false)  Date startTime,
                                    @ApiParam(value = "结束时间") @RequestParam(required = false)  Date endTime,
                                    @ApiParam(value = "页数", required = true) @RequestParam Integer page,
                                    @ApiParam(value = "每页数量", required = true) @RequestParam Integer size) {
        return iUserPointLogService.queryByCondition(terminal, terminalCode, action, startTime, endTime, page, size);
    }

    @GetMapping("/logsConditionOneUser")
    @ApiOperation(value = "查询单个用户积分记录2")
    public Page<UserPointLog> queryOneUser(@ApiParam(value = "加密手机号码", required = true) @RequestParam String secretPhone) {
        return iUserPointLogService.queryByConditionOneUser(secretPhone);
    }

    @PostMapping("/logsConditionOneUserV3")
    @ApiOperation(value = "查询单个用户积分记录3")
    public Map<String,Object> queryOneUser(@ApiParam(value = "参数", required = true) @RequestBody FiltersData data) {
        Map<String,Object> map=new HashMap<String,Object>();
        Page<UserPointLog> page= iUserPointLogService.queryByConditionOneUserV3(data.getFilters().get(0).getValue(),data.getPageIndex()-1,data.getPageSize());
        map.put("items",page.getContent());
        map.put("totalCount",page.getTotalElements());
        return map;
    }

    @PostMapping("/logsCondition")
    @ApiOperation(value = "查询积分记录(BirdGird)")
    public BirdGirdTableResponse2<UserPointLog> query2(@ApiParam(value = "birdgird的条件请求对象") @RequestBody BirdGirdRequest girdRequest) {
        girdRequest.setPageIndex(girdRequest.getPageIndex() - 1);
        return iUserPointLogService.queryByCondition(girdRequest);
    }

    @GetMapping("/lastLog")
    @ApiOperation(value = "获取最后记录")
    public ResultObject<UserPointLog> getLastLog(@ApiParam(value = "密文手机号", required = true) @RequestParam String secretPhone) {
        UserPointLog log = iUserPointLogService.getLastLog(secretPhone);
        if(log == null) {
            return ResultObject.success("没有记录",null);
        } else {
            return ResultObject.success(log);
        }
    }

    @GetMapping("/balance")
    @ApiOperation(value = "获取积分余额")
    public ResultObject<Integer> getBalance(@ApiParam(value = "密文手机号", required = true) @RequestParam String secretPhone) {
        return ResultObject.success(iUserPointLogService.getPointBalance(secretPhone));
    }

    @PostMapping("/log")
    @ApiOperation(value = "添加积分记录")
    public ResultObject<Object> addLog(@ApiParam(value = "积分记录对象", required = true) @RequestBody UserPointLog log) {
        if(iUserPointLogService.addLog(log)) {
            return ResultObject.success("保存成功",null);
        } else {
            return ResultObject.error("保存失败");
        }
    }

    @GetMapping("/lastBalance")
    @ApiOperation(value = "获取昨天未添加积分的记录")
    public ResultObject<UserPointLog> getLastBalance(@ApiParam(value = "密文手机号", required = true) @RequestParam String secretPhone) {
        UserPointLog log = iUserPointLogService.getLastDayLog(secretPhone);
        if(log == null) {
            return ResultObject.success("没有记录",null);
        } else {
            return ResultObject.success(log);
        }
    }

    @GetMapping("/lastDayLogs")
    @ApiOperation(value = "获取昨天积分操作记录")
    public ResultObject<List<UserPointLog>> getLastLogs(@ApiParam(value = "密文手机号", required = true) @RequestParam String secretPhone) {
        List<UserPointLog> logs = iUserPointLogService.getLastDayLogList(secretPhone);
        return ResultObject.success(logs);
    }

    @GetMapping("/desc")
    @ApiOperation(value = "获取积分说明")
    public ResultObject<UserPointDesc> getDesc() {
        UserPointDesc desc = iUserPointLogService.getUserPointDesc();
        return ResultObject.success(desc);
    }

    @PostMapping("/desc")
    @ApiOperation(value = "保存积分说明")
    public ResultObject<Object> saveDesc(@ApiParam(value = "积分说明对象", required = true) @RequestBody UserPointDesc desc) {
        if(iUserPointLogService.setUserPointDesc(desc)) {
            return ResultObject.success("保存成功",null);
        } else {
            return ResultObject.error("保存失败");
        }
    }


}
