package com.yonge.cooleshow.admin.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.excel.UserWithdrawalExport;
import com.yonge.cooleshow.biz.dal.dto.req.AuthOperaReq;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.utils.easyexcel.*;
import io.swagger.annotations.*;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.yonge.cooleshow.biz.dal.vo.UserWithdrawalVo;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherWithdrawalSearch;
import com.yonge.cooleshow.biz.dal.service.UserWithdrawalService;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/userWithdrawal")
@Api(value = "用户结算", tags = "用户结算")
public class UserWithdrawalController extends BaseController {
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private UserWithdrawalService userWithdrawalService;

    /**
     * 查询单条
     */
    @GetMapping("/detail/{id}")
    @ApiOperation(value = "详情", notes = "传入id")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/detail')")
    public HttpResponseResult<UserWithdrawalVo> detail(@PathVariable("id") Long id) {
        return succeed(userWithdrawalService.detail(id));
    }

    /**
     * 查询分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页", notes = "传入teacherWithdrawalSearch")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/page')")
    public HttpResponseResult<PageInfo<UserWithdrawalVo>> page(@RequestBody TeacherWithdrawalSearch query) {
        IPage<UserWithdrawalVo> pages = userWithdrawalService.selectPage(PageUtil.getPage(query), query);
        return succeed(PageUtil.pageInfo(pages));
    }

    /**
     * 查询导出
     */
    @PostMapping("/exportExcel")
    @ApiOperation(value = "查询导出", notes = "传入TeacherWithdrawalSearch")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/exportExcel')")
    public void exportExcel(@RequestBody TeacherWithdrawalSearch query) {
        List<UserWithdrawalVo> withdrawalVoList = userWithdrawalService.selectList(query);
        List<UserWithdrawalExport> list = new ArrayList<>();
        withdrawalVoList.forEach(o -> {
            UserWithdrawalExport export = new UserWithdrawalExport();
            BeanUtils.copyProperties(o, export);
            list.add(export);

        });
        ExcelUtils.exportExcel(list, "结算列表数据" + System.currentTimeMillis(),
                "列表数据");
    }

    @GetMapping("/totalAmount")
    @ApiOperation(value = "统计金额")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/totalAmount')")
    public HttpResponseResult<UserWithdrawalVo> totalAmount() {
        return succeed(userWithdrawalService.totalAmount());
    }

    @PostMapping("/doAuth")
    @ApiOperation(value = "审核", notes = "传入authOperaReq")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/doAuth')")
    public HttpResponseResult<Boolean> doAuth(@Valid @RequestBody AuthOperaReq authOperaReq) throws Exception {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return userWithdrawalService.batchAuth(authOperaReq, user);
    }

    /*@ApiImplicitParams({
            @ApiImplicitParam(
                    name = "id",
                    value = "审核单id",
                    paramType = "query", dataType = "Long"
            )
    })
    @PostMapping("/transferAccount")
    @ApiOperation(value = "继续转账", notes = "传入authOperaReq")
    @PreAuthorize("@pcs.hasPermissions('userWithdrawal/transferAccount')")
    public HttpResponseResult<Boolean> transferAccount(@ApiIgnore @RequestBody AuthOperaReq authOperaReq) throws Exception {
        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(authOperaReq.getId())
                            , () -> userWithdrawalService.transferAccount(authOperaReq, user), 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("转账失败");
        }
    }*/
}