package com.platform.modules.sys.controller;

import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.platform.common.validator.ValidatorUtils;
import com.platform.common.validator.group.AddGroup;
import com.platform.modules.live.entity.LiveSceneEntity;
import com.platform.modules.live.service.LiveSceneService;
import com.platform.modules.live.utils.PlatformTenantProperties;
import com.platform.modules.sys.dto.SaveTenantDTO;
import com.platform.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.platform.modules.sys.entity.SysTenantEntity;
import com.platform.modules.sys.service.SysTenantService;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.R;

import static com.platform.common.utils.ShiroUtils.getUserId;


/**
 * @author MXY
 * 2019-11-12 15:25:44
 */
@RestController
@RequestMapping("sys/systenant")
@Api(value = "机构管理", tags = "机构管理")
public class SysTenantController extends AbstractController {

    @Autowired
    private SysTenantService sysTenantService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PlatformTenantProperties tenantProperties;

    @Autowired
    private LiveSceneService liveSceneService;

    @Value(value = "${platform.tenant.other-tenant-default-admin-role-id}")
    private Long roleId;

    /**
     * 新增机构
     * */
    @ApiOperationSort(1)
    @ApiOperation(value = "新增机构及用户", notes = "机构信息及用户信息")
    @PostMapping("/save")
    @RequiresPermissions("sys:systenant:save")
    public R save(SaveTenantDTO tenantDTO){

        if (StringUtils.isBlank(tenantDTO.getTenantName()) || StringUtils.isBlank(tenantDTO.getUsername()) || StringUtils.isBlank(tenantDTO.getRealName()) || StringUtils.isBlank(tenantDTO.getPassword()) || StringUtils.isBlank(tenantDTO.getConfirmPwd())){
            return R.error("必填信息不能为空");
        }

        // 判断两次密码输入是否一致
        if (!tenantDTO.getPassword().equals(tenantDTO.getConfirmPwd())){
            return R.error("两次密码输入不一致");
        }

        ValidatorUtils.validateEntity(tenantDTO, AddGroup.class);

        // TODO 角色设置
        List<Long> list = new ArrayList<>();

        if (null != roleId)
            list.add(roleId);
        tenantDTO.setRoleIdList(list);
        // 判断企业名称或注册号是否重复
        String tenantCheckResult = sysTenantService.tenantCheckExist(tenantDTO.getTenantName(), tenantDTO.getLicense());
        if (StringUtils.isNotBlank(tenantCheckResult)){
            return R.error(tenantCheckResult);
        }
        // 判断用户是否重复
        String userCheckResult = sysUserService.checkExist(getUserId(), tenantDTO.getUsername(),tenantDTO.getMobile(), tenantDTO.getEmail());
        if (StringUtils.isNotBlank(userCheckResult)){
            return R.error(userCheckResult);
        }
        return sysTenantService.saveTenant(tenantDTO);
    }

    /**
     * 机构修改
     */
    @ApiOperationSort(2)
    @ApiOperation(value = "机构修改", notes = "机构信息DTO")
    @PostMapping("/update")
    @RequiresPermissions("sys:systenant:update")
    public R update(SysTenantEntity sysTenant){
        return sysTenantService.updateTenant(sysTenant);
    }

    /**
     * 机构删除
     */
    @ApiOperationSort(3)
    @ApiOperation(value = "机构删除", notes = "机构id")
    @PostMapping("/delete")
    @RequiresPermissions("sys:systenant:delete")
    public R delete(Long[] ids){

        // 判断是否存在关联数据
        for (Long id : ids){
            List<LiveSceneEntity> sceneEntityList = liveSceneService.selectList(new EntityWrapper<LiveSceneEntity>().eq("tenant_id", id));
            if (null != sceneEntityList && sceneEntityList.size() > 0)
                return R.error("所选ID为" + id + "的机构存在关联数据，不能删除");
        }

        return sysTenantService.delete(ids);
    }

    /**
     * 分页
     */
    @ApiOperationSort(4)
    @ApiOperation(value = "分页查询")
    @GetMapping("/page")
    @RequiresPermissions("sys:systenant:page")
    public R page(@RequestParam Map<String, Object> params){
        PageUtils page = sysTenantService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @ApiOperationSort(5)
    @ApiOperation(value = "列表")
    @GetMapping("/list")
    @RequiresPermissions("sys:systenant:list")
    public R list(){
        Map<String, Object> map = new HashMap<>();
        Long tenantId = getUser().getTenantId();
        List<SysTenantEntity> list;

        map.put("tenant_id", tenantId);
        if (null != tenantId && !tenantProperties.getManageTenantId().equals(tenantId)){
            list =  sysTenantService.selectByMap(map);
        }else {
            list = sysTenantService.selectList(null);
        }
        return R.ok().put("list", list);
    }

    /**
     * 信息
     */
    @ApiOperationSort(6)
    @ApiOperation(value = "机构详情")
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:systenant:info")
    public R info(@PathVariable("id") Long id){
        return sysTenantService.info(id);
    }

}
