package com.yonge.cooleshow.teacher.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.req.WithdrawalReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherWithdrawalSearch;
import com.yonge.cooleshow.biz.dal.service.UserWithdrawalService;
import com.yonge.toolset.payment.util.DistributedLock;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.cooleshow.biz.dal.vo.UserWithdrawalVo;
import com.yonge.cooleshow.biz.dal.vo.res.WithdrawalInfoRes;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.utils.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/userWithdrawal")
@Api(value = "用户账户结算表", tags = "用户账户结算表")
public class UserWithdrawalController extends BaseController {

    @Autowired
    private UserWithdrawalService userWithdrawalService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @PostMapping("/getWithdrawalInfo")
    @ApiOperation(value = "查询结算页面信息")
    public HttpResponseResult<WithdrawalInfoRes> getWithdrawalInfo() {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return userWithdrawalService.getWithdrawalInfo(user.getId());
    }

    @PostMapping("/withdrawal")
    @ApiOperation(value = "用户结算")
    public HttpResponseResult<Boolean> withdrawal(@Valid @RequestBody WithdrawalReq withdrawalReq) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        try {
            HttpResponseResult<Boolean> res = DistributedLock.of(redissonClient)
                    .runIfLockCanGet(CacheNameEnum.LOCK_WITHDRAWAL.getRedisKey(user.getId())
                            , () -> userWithdrawalService.withdrawal(user, withdrawalReq), 60L, TimeUnit.SECONDS);
            if(null != res){
                return res;
            }else{
                return HttpResponseResult.failed("结算失败");
            }
        } catch (BizException e) {
            return HttpResponseResult.failed(e.getMessage());
        }  catch (Exception e) {
            e.printStackTrace();
            return HttpResponseResult.failed("结算失败");
        }
    }


    @PostMapping("/withdrawalPage")
    @ApiOperation(value = "结算记录")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "status",
                    value = "状态 DOING、审核中 PASS、通过 UNPASS、不通过",
                    paramType = "query", dataType = "String"
            ),
            @ApiImplicitParam(
                    name = "searchDate",
                    value = "查询时间（yyyy-mm）",
                    paramType = "query", dataType = "String"
            )
    })
    public HttpResponseResult<PageInfo<UserWithdrawalVo>> withdrawalPage(@ApiIgnore @RequestBody TeacherWithdrawalSearch query) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        query.setUserId(user.getId());

        if (StringUtil.isEmpty(query.getSearchDate())) {
            query.setSearchDate(DateUtil.format(new Date(), "yyyy-MM"));
        }
        String[] classDateSp = query.getSearchDate().split("-");
        try {
            LocalDate date = LocalDate.of(Integer.parseInt(classDateSp[0]), Integer.parseInt(classDateSp[1]), 1);

            LocalDateTime firstDay = LocalDateTime.of(date.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
            LocalDateTime lastDay = LocalDateTime.of(date.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);

            query.setStartTime(firstDay);
            query.setEndTime(lastDay);
        } catch (Exception e) {
            throw new BizException("查询时间格式不正确 [" + query.getSearchDate() + "]");
        }

        IPage<UserWithdrawalVo> pages = userWithdrawalService.selectPage(PageUtil.getPage(query), query);
        return succeed(PageUtil.pageInfo(pages));
    }
}