package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.admin.io.request.UserTenantAlbumRecordVo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.UserTenantAlbumRecord;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.service.UserTenantAlbumRecordService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.UserTenantAlbumRecordWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
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.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.admin:}/userTenantAlbumRecord")
@Api(tags = "购买训练工具记录")
public class UserTenantAlbumRecordController extends BaseController {

    @Autowired
    private UserTenantAlbumRecordService userTenantAlbumRecordService;

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @ApiOperation(value = "详情", notes = "购买训练工具记录-根据详情ID查询单条, 传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @PreAuthorize("@pcs.hasPermissions('userTenantAlbumRecord/detail', {'BACKEND'})")
//    @GetMapping("/detail/{id}")
    public R<UserTenantAlbumRecordVo.UserTenantAlbumRecord> detail(@PathVariable("id") Long id) {

        UserTenantAlbumRecord wrapper = userTenantAlbumRecordService.detail(id);

        return R.from(UserTenantAlbumRecordVo.UserTenantAlbumRecord.from(JSON.toJSONString(wrapper)));
    }

    @ApiOperation(value = "查询分页", notes = "购买训练工具记录- 传入 UserTenantAlbumRecordVo.UserTenantAlbumRecordQuery")
    @PreAuthorize("@pcs.hasPermissions('userTenantAlbumRecord/page', {'BACKEND'})")
    @PostMapping("/page")
    public R<PageInfo<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord>> page(@RequestBody UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery query) {
        return R.from(PageUtil.pageInfo(userTenantAlbumRecordService.selectUserTenantAlbumRecordPage(QueryInfo.getPage(query), query)));
    }

    @ApiOperation(value = "新增", notes = "购买训练工具记录- 传入 UserTenantAlbumRecordVo.UserTenantAlbumRecord")
    @PreAuthorize("@pcs.hasPermissions('userTenantAlbumRecord/save', {'BACKEND'})")
    @PostMapping("/save")
    public R<JSONObject> add(@Validated @RequestBody UserTenantAlbumRecordVo.UserTenantAlbumRecord userTenantAlbumRecordVo) {

        // 新增数据
        UserTenantAlbumRecord userTenantAlbumRecord = new UserTenantAlbumRecord();
        userTenantAlbumRecord.setTenantId(userTenantAlbumRecordVo.getTenantId());
        userTenantAlbumRecord.setTenantAlbumId(userTenantAlbumRecordVo.getTenantAlbumId());
        userTenantAlbumRecord.setTimes(userTenantAlbumRecordVo.getTimes());
        userTenantAlbumRecord.setType(userTenantAlbumRecordVo.getType());
        userTenantAlbumRecord.setReason(userTenantAlbumRecordVo.getReason());
        userTenantAlbumRecord.setUserId(userTenantAlbumRecordVo.getUserId());
        userTenantAlbumRecord.setClientType(ClientEnum.STUDENT);
        userTenantAlbumRecord.setSourceType(SourceTypeEnum.BACKEND_GIVE);

        SysUser sysUser = sysUserFeignService.queryUserInfo();
        userTenantAlbumRecord.setCreateBy(sysUser.getId());

        RLock lock = redissonClient.getLock("UserTenantAlbumRecord_" + userTenantAlbumRecordVo.getUserId() + "_" + userTenantAlbumRecordVo.getTenantAlbumId());
        try {
            boolean b = lock.tryLock(60, 60, TimeUnit.SECONDS);
            if (b) {
                userTenantAlbumRecordService.add(userTenantAlbumRecord);
            } else {
                throw new BizException("请勿重复点击");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.getHoldCount() > 0) {
                lock.unlock();
            }
        }
        return R.defaultR();
    }

    @ApiOperation(value = "修改", notes = "购买训练工具记录- 传入 UserTenantAlbumRecordVo.UserTenantAlbumRecord")
    @PreAuthorize("@pcs.hasPermissions('userTenantAlbumRecord/update', {'BACKEND'})")
//    @PostMapping("/update")
    public R<JSONObject> update(@Validated @RequestBody UserTenantAlbumRecordVo.UserTenantAlbumRecord userTenantAlbumRecordVo) {

        // 更新数据
        userTenantAlbumRecordService.updateById(JSON.parseObject(userTenantAlbumRecordVo.jsonString(), UserTenantAlbumRecord.class));

        return R.defaultR();
    }

    @ApiOperation(value = "删除", notes = "购买训练工具记录- 传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @PreAuthorize("@pcs.hasPermissions('userTenantAlbumRecord/remove', {'BACKEND'})")
//    @PostMapping("/remove")
    public R<Boolean> remove(@RequestParam Long id) {

        return R.from(userTenantAlbumRecordService.removeById(id));
    }
}