package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.HuiLianTongUnionCardConfig;
import com.hai.entity.HighUser;
import com.hai.model.ResponseData;
import com.hai.service.HighUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Sum1Dream
 */
@RestController
@RequestMapping(value = "/highUser")
@Api(value = "用户管理")
public class HighUserController {

    private static Logger log = LoggerFactory.getLogger(HighUserController.class);

    @Resource
    private HighUserService highUserService;

    @RequestMapping(value = "/getListUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询用户列表")
    public ResponseData getPagePosition(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "regTimeStart", required = false) Long regTimeStart,
            @RequestParam(value = "regTimeEnd", required = false) Long regTimeEnd,
            @RequestParam(name = "pageNum", required = true) Integer pageNum,
            @RequestParam(name = "pageSize", required = true) Integer pageSize
    ) {
        try {

            Map<String, String> map = new HashMap<>();

            if (StringUtils.isNotBlank(name)) {
                map.put("name", name);
            }
            if (StringUtils.isNotBlank(phone)) {
                map.put("phone", phone);
            }
            if (status != null) {
                map.put("status", Integer.toString(status));
            }
            if (regTimeStart != null) {
                map.put("regTimeStart", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(regTimeStart));
            }
            if (regTimeEnd != null) {
                map.put("regTimeEnd", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(regTimeEnd));
            }

            PageHelper.startPage(pageNum, pageSize);

            List<HighUser> highUsers = highUserService.getListUser(map);

            return   ResponseMsgUtil.success(new PageInfo<>(highUsers));
        } catch (Exception e) {
            log.error("HighUserController --> getListUser() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/findByUserId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据id查询详情")
    public ResponseData findById(@RequestParam(value = "userId", required = true) Long userId) {
        try {
            return ResponseMsgUtil.success(highUserService.findByUserId(userId));

        } catch (Exception e) {
            log.error("HighUserController --> findByUserId() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/forbiddenUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "禁用启用账号")
    public ResponseData forbiddenUser(@RequestParam(value =  "userId" , required = true) Long userId) {
        try {

            HighUser highUser = highUserService.findByUserId(userId);

            if (highUser == null) {
                log.error("HighUserController --> forbiddenUser() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }

            if (highUser.getStatus() == 1) {
                highUser.setStatus(0);
            } else {
                highUser.setStatus(1);
            }

            highUserService.updateUser(highUser);

            return ResponseMsgUtil.success("禁用成功");

        } catch (Exception e) {
            log.error("BsPositionController --> addPosition() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改用户")
    public ResponseData updateUser(@RequestBody HighUser reqBody) {
        try {

            if (
                    reqBody.getId() == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            HighUser highUser = highUserService.findByUserId(reqBody.getId());

            if (highUser == null) {
                log.error("HighUserController --> updateUser() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }

            highUserService.updateUser(reqBody);

            return ResponseMsgUtil.success("修改成功");

        } catch (Exception e) {
            log.error("BsPositionController --> addPosition() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/TCheckEMsgUnionCardVipRights", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "请求会员体系")
    public ResponseData TCheckEMsgUnionCardVipRights(@RequestParam(name = "phone", required = true) String phone) {
        try {
            JSONObject consumptionRecord = HuiLianTongUnionCardConfig.checkEMsgUnionCardVipRights(phone);
            JSONObject cardInfoObject = HuiLianTongUnionCardConfig.resolveResponseMembership(consumptionRecord.getString("data"));
            return ResponseMsgUtil.success(cardInfoObject);
        } catch (Exception e) {
            log.error("HighOrderController --> getBackendToken() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value = "/setUpAgent", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "设置代理商")
    public ResponseData setUpAgent(@RequestParam(value =  "userId" , required = true) Long userId) {
        try {

            HighUser highUser = highUserService.findByUserId(userId);

            if (highUser == null) {
                log.error("HighUserController --> forbiddenUser() error!");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.NOT_FOUND_USER_ERROR, "");
            }

            if (highUser.getIsAgent() == null || !highUser.getIsAgent()) {
                    highUser.setIsAgent(true);
            } else {
                         highUser.setIsAgent(false);
            }

            highUserService.updateUser(highUser);

            return ResponseMsgUtil.success("设置成功");

        } catch (Exception e) {
            log.error("BsPositionController --> addPosition() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
