package com.yonge.cooleshow.admin.controller.coupon;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.admin.io.request.coupon.CouponInfoVO;
import com.yonge.cooleshow.admin.io.request.coupon.CouponInventoryVO;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.CouponInfo;
import com.yonge.cooleshow.biz.dal.entity.CouponInventory;
import com.yonge.cooleshow.biz.dal.queryInfo.CouponInfoQuery;
import com.yonge.cooleshow.biz.dal.queryInfo.CouponInventoryQuery;
import com.yonge.cooleshow.biz.dal.service.CouponInfoService;
import com.yonge.cooleshow.biz.dal.vo.coupon.CouponInfoWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.coupon.CouponInventoryWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.EStatus;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 优惠券信息 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2022-09-02
 */
@RestController
@RequestMapping("/couponInfo")
@Api(value = "优惠券信息", tags = "优惠券信息")
public class CouponInfoController extends BaseController {

    @Autowired
    private CouponInfoService couponInfoService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    /**
     * 优惠券信息
     * @param request CouponInfoVO.RequestInfo
     * @return HttpResponseResult<PageInfo<CouponInfoVO.ResponseInfo>>
     */
    @PostMapping(value = "/page", consumes="application/json", produces="application/json")
    @ApiOperation(value = "查询优惠券分页", notes = "CouponInfoVO.PageRequest")
    public HttpResponseResult<PageInfo<CouponInfoVO.CouponPageInfo>> queryCouponPageInfo(@RequestBody CouponInfoVO.PageRequest request) {

        // 优惠券信息
        IPage<CouponInfoWrapper> wrapper = couponInfoService.queryCouponPageInfo(PageUtil.getPage(request),
                CouponInfoQuery.from(request.jsonString()));

        // 数据转换
        List<CouponInfoVO.CouponPageInfo> pageInfos = JSON.parseArray(JSON.toJSONString(wrapper.getRecords()),
                CouponInfoVO.CouponPageInfo.class);

        // 分页数据信息
        return succeed(PageUtil.getPageInfo(wrapper, pageInfos));
    }

    /**
     * 优惠券详情信息
     * @param id 优惠券ID
     * @return HttpResponseResult<CouponInfoVO.CouponQueryInfo>
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "优惠券详情", notes = "传入优惠券ID")
    public HttpResponseResult<CouponInfoVO.CouponQueryInfo> findCouponById(@PathVariable("id") Long id) {

        if (Objects.isNull(id)) {
            return failed("无效的优惠券ID");
        }

        // 优惠券信息
        CouponInfo couponInfo = couponInfoService.queryCouponInfoById(id);

        return succeed(CouponInfoVO.CouponQueryInfo.from(JSON.toJSONString(couponInfo)));
    }

    /**
     * 新增或者更新优惠券信息
     * - ID为空新增；否则进行更新
     * @param info CouponInfoVO.CouponInfo
     * @return HttpResponseResult<CouponInfoVO.CouponInfo>
     */
    @PostMapping(value = "/save", consumes="application/json", produces="application/json")
    @ApiOperation(value = "新增或修改", notes = "CouponInfoVO.CouponInfo")
    public HttpResponseResult<CouponInfoVO.CouponQueryInfo> saveOrUpdate(@Valid @RequestBody CouponInfoVO.CouponInfo info) {

        // 获取当前登录用户信息
        SysUser user = sysUserFeignService.queryUserInfo();
        if (Objects.isNull(user) || Objects.isNull(user.getId())) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        // 校验参数合法性
        if (info.invalidRequestParam(user.getId())) {
            throw new BizException("无效的请求参数");
        }

        // 新增或更新信息
        CouponInfo couponInfo = couponInfoService.saveOrUpdateCouponInfo(JSON.parseObject(info.jsonString(), CouponInfo.class), false);

        return succeed(CouponInfoVO.CouponQueryInfo.from(JSON.toJSONString(couponInfo)));
    }

    /**
     * 启用/停用 优惠券
     */
    @PostMapping("/updateState")
    @ApiOperation(value = "优惠券状态启/停用")
    public HttpResponseResult<Boolean> updateCouponStateInfo(@RequestBody CouponInfoVO.CouponInfo request) {

        // 获取当前登录用户信息
        SysUser user = sysUserFeignService.queryUserInfo();
        if (Objects.isNull(user) || Objects.isNull(user.getId())) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        if (Objects.isNull(request)
                || Objects.isNull(request.getId())
                || EStatus.invalid(request.getStatus())) {
            throw new BizException("无效请求参数");
        }

        // 更新数据信息
        CouponInfoVO.CouponInfo info = CouponInfoVO.CouponInfo.builder()
                .id(request.getId())
                .status(request.getStatus())
                .updatedBy(user.getId())
                .updateTime(DateTime.now().getMillis())
                .build();

        CouponInfo couponInfo = couponInfoService.saveOrUpdateCouponInfo(JSON.parseObject(info.jsonString(), CouponInfo.class), true);

        // 校验状态更新结果
        return status(couponInfo.getStatus().intValue() == request.getStatus());
    }

    /**
     * 优惠券库存量信息
     * @param request CouponInventoryVO.PageRequest
     * @return HttpResponseResult<PageInfo<CouponInventoryVO.PageInfo>>
     */
    @PostMapping(value = "/inventory/page", consumes="application/json", produces="application/json")
    @ApiOperation(value = "查询库存量调整分页信息", notes = "CouponInventoryVO.PageRequest")
    public HttpResponseResult<PageInfo<CouponInventoryVO.PageInfo>> queryCouponInventoryPageInfo(@RequestBody CouponInventoryVO.PageRequest request) {

        // 校验请求参数
        if (request.invalidRequestParam()) {
            throw new BizException("无效的优惠券ID");
        }

        // 优惠券信息
        IPage<CouponInventoryWrapper> wrapper = couponInfoService.queryCouponInventoryPageInfo(PageUtil.getPage(request),
                CouponInventoryQuery.from(request.jsonString()));

        // 数据转换
        List<CouponInventoryVO.PageInfo> pageInfos = JSON.parseArray(JSON.toJSONString(wrapper.getRecords()),
                CouponInventoryVO.PageInfo.class);

        // 分页数据信息
        return succeed(PageUtil.getPageInfo(wrapper, pageInfos));
    }

    /**
     * 调整新优惠券库存量信息
     * @param info CouponInfoVO.CouponInfo
     * @return HttpResponseResult<CouponInfoVO.CouponInfo>
     */
    @PostMapping(value = "/inventory/update", consumes="application/json", produces="application/json")
    @ApiOperation(value = "优惠券库存量更新", notes = "CouponInventoryVO.InventoryInfo")
    public HttpResponseResult<Boolean> saveOrUpdate(@Valid @RequestBody CouponInventoryVO.InventoryInfo info) {

        // 获取当前登录用户信息
        SysUser user = sysUserFeignService.queryUserInfo();
        if (Objects.isNull(user) || Objects.isNull(user.getId())) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }

        // 校验参数合法性
        if (info.invalidRequestParam(user.getId())) {
            throw new BizException("无效的请求参数");
        }

        // 新增或更新信息
        int rows = couponInfoService.saveOrUpdateCouponInventoryInfo(JSON.parseObject(info.jsonString(),
                CouponInventory.class));

        return status(rows > 0);
    }

    /**
     * 库存调整用户信息
     * @param request CouponInventoryVO.PageRequest
     * @return HttpResponseResult<PageInfo<CouponInventoryVO.PageInfo>>
     */
    @PostMapping(value = "/inventory/user", consumes="application/json", produces="application/json")
    @ApiOperation(value = "查询库存调整用户信息分页", notes = "CouponInventoryVO.PageRequest")
    public HttpResponseResult<PageInfo<CouponInventoryVO.PageUserInfo>> queryInventoryUserPageInfo(@RequestBody CouponInventoryVO.PageRequest request) {

        // 校验请求参数
        if (Objects.isNull(request) || Objects.isNull(request.getCouponId())) {
            throw new BizException("无效的优惠券ID");
        }

        // 优惠券信息
        IPage<CouponInventoryWrapper> wrapper = couponInfoService.queryCouponInventoryPageInfo(PageUtil.getPage(request),
                CouponInventoryQuery.from(request.jsonString()).groupByUser(true));

        // 数据转换
        List<CouponInventoryVO.PageUserInfo> pageInfos = JSON.parseArray(JSON.toJSONString(wrapper.getRecords()),
                CouponInventoryVO.PageUserInfo.class);

        // 分页数据信息
        return succeed(PageUtil.getPageInfo(wrapper, pageInfos));
    }

}
