package com.starry.admin.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.modules.clerk.service.IPlayClerkUserInfoService;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.modules.system.module.entity.SysTenantEntity;
import com.starry.admin.modules.system.service.ISysTenantService;
import com.starry.admin.modules.system.vo.SysTenantAddVo;
import com.starry.admin.modules.system.vo.SysTenantQueryVo;
import com.starry.admin.modules.system.vo.SysTenantReturnVo;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.math.BigDecimal;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 租户表Controller
 *
 * @author admin
 */
@Api(tags = "租户管理", description = "系统租户相关接口")
@RestController
@RequestMapping("/platform/tenant")
public class SysTenantController {
    @Resource
    private ISysTenantService sysTenantService;

    @Resource
    private IPlayClerkUserInfoService playClerkUserInfoService;

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    /**
     * 新增租户表
     */
    @ApiOperation(value = "新增租户", notes = "创建新的系统租户")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "添加失败")})
    // @PreAuthorize("@customSs.hasPermission('platform:tenant:create')")
    @Log(title = "租户表", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@ApiParam(value = "租户信息", required = true) @Validated @RequestBody SysTenantAddVo vo) {
        SysTenantEntity entity = ConvertUtil.entityToVo(vo, SysTenantEntity.class);
        return sysTenantService.addTenant(entity);
    }

    /**
     * 查询租户表列表
     */
    @ApiOperation(value = "分页查询租户列表", notes = "根据条件分页查询租户列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = SysTenantReturnVo.class, responseContainer = "Page")})
    @PreAuthorize("@customSs.hasPermission('platform:tenant:list')")
    @PostMapping("/listByPage")
    public R listByPage(@ApiParam(value = "查询条件", required = true) @RequestBody SysTenantQueryVo vo) {
        IPage<SysTenantEntity> page = sysTenantService.selectSysTenantList(vo);
        IPage<SysTenantReturnVo> voPage = page.convert(u -> {
            SysTenantReturnVo returnVo = new SysTenantReturnVo();
            List<PlayOrderInfoEntity> orderInfoEntities = playOrderInfoService.getTotalOrderInfo(u.getTenantId());
            BigDecimal rechargeAmount = BigDecimal.ZERO;
            for (PlayOrderInfoEntity orderInfoEntity : orderInfoEntities) {
                if ("0".equals(orderInfoEntity.getOrderType())) {
                    rechargeAmount = rechargeAmount.add(orderInfoEntity.getFinalAmount());
                }
            }

            BeanUtils.copyProperties(u, returnVo);
            returnVo.setClerkNumber(playClerkUserInfoService.getTotalClerkUser(u.getTenantId()));
            returnVo.setOrderNumber((long) orderInfoEntities.size());
            returnVo.setRechargeAmount(rechargeAmount);
            return returnVo;
        });

        return R.ok(voPage);
    }

    /**
     * 获取租户表详细信息
     */
    @ApiOperation(value = "获取租户详情", notes = "根据租户ID获取租户详细信息")
    @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = SysTenantEntity.class)})
    @PreAuthorize("@customSs.hasPermission('platform:tenant:query')")
    @GetMapping(value = "/{tenantId}")
    public R getInfo(@PathVariable("tenantId") String tenantId) {
        return R.ok(sysTenantService.selectSysTenantByTenantId(tenantId));
    }

    /**
     * 修改租户表
     */
    @ApiOperation(value = "修改租户", notes = "根据租户ID修改租户信息")
    @ApiImplicitParam(name = "tenantId", value = "租户ID", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败")})
    @PreAuthorize("@customSs.hasPermission('platform:tenant:edit')")
    @Log(title = "租户表", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/{tenantId}")
    public R update(@PathVariable String tenantId,
            @ApiParam(value = "租户信息", required = true) @RequestBody SysTenantEntity sysTenantEntity) {
        return sysTenantService.updateTenant(sysTenantEntity);
    }

    /**
     * 删除租户表
     */
    @ApiOperation(value = "删除租户", notes = "根据租户ID批量删除租户")
    @ApiImplicitParam(name = "tenantIds", value = "租户ID数组", required = true, dataType = "String[]", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Boolean.class)})
    @PreAuthorize("@customSs.hasPermission('platform:tenant:remove')")
    @Log(title = "租户表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tenantIds}")
    public R remove(@PathVariable String[] tenantIds) {
        return R.ok(sysTenantService.deleteSysTenantByTenantIds(tenantIds));
    }
}
