package com.xhpc.user.controller;

import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.common.log.annotation.Log;
import com.xhpc.common.log.enums.BusinessType;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.system.api.domain.SysRole;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import com.xhpc.user.service.IXhpcOperatorService;
import com.xhpc.user.service.IXhpcUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/xhpc/user")
public class XhpcUserController extends BaseController {

    @Autowired
    private IXhpcUserService iXhpcUserService;

    @Autowired
    private IXhpcOperatorService iXhpcOperatorService;

    @Autowired
    private TokenService tokenService;


    /**
     * 获取平台用户分页列表
     */
    //@PreAuthorize(hasPermi = "user:pc:page")
    @GetMapping("/pc/page")
    public TableDataInfo pcPage(String userName, String nickName) {
        startPage();
        List<Map<String, Object>> list = iXhpcUserService.selectPcUserList(userName, nickName);
        return getDataTable(list);
    }

    /**
     * 新增平台用户
     */
    @Log(title = "平台用户", businessType = BusinessType.INSERT)
    @ApiOperation("新增平台用户")
    @RequiresRoles("admin")
    @PostMapping("/pc/add")
    public AjaxResult pcAdd(@RequestBody SysUser sysUser) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (iXhpcUserService.checkUserNameUnique(sysUser.getUserName(),null) > 0) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        SysRole role = new SysRole();
        role.setRoleName(sysUser.getNickName()+"平台子账户角色");
        role.setRoleKey(sysUser.getUserName());
        role.setRoleSort("1");
        iXhpcUserService.insertRole(role);
        sysUser.setPhonenumber(sysUser.getUserName());
        sysUser.setTenantId(loginUser.getTenantId());
        sysUser.setDeptId(loginUser.getSysUser().getDeptId());
        sysUser.setDataPowerType(StatusConstants.ALL_POWER_TYPE);
        sysUser.setUserType(StatusConstants.SYSTEM_USER_TYPE);
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setAvatar("https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/avatar/logo.png");
        sysUser.setPassword("123456");
        Long[] roles = new Long[1];
        roles[0] = role.getRoleId();
        sysUser.setRoleIds(roles);
        iXhpcUserService.insertUser(sysUser);

        return AjaxResult.success();
    }

    /**
     * 修改平台用户
     */
    @Log(title = "平台用户", businessType = BusinessType.UPDATE)
    @ApiOperation("修改平台用户")
    @RequiresRoles("admin")
    @PostMapping("/pc/edit")
    public AjaxResult pcEdit(@RequestBody SysUser sysUser) {
        if (null == sysUser.getUserId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户id不能为空");
        }
        if (iXhpcUserService.checkUserNameUnique(sysUser.getUserName(),sysUser.getUserId()) > 0) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }

        iXhpcUserService.updateUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 平台用户详情
     */
    @ApiOperation("平台用户详情")
    //@PreAuthorize(hasPermi = "user:pc:info")
    @GetMapping("/pc/info")
    public AjaxResult pcInfo(@RequestParam Long userId) {
        return AjaxResult.success(iXhpcUserService.pcInfo(userId));
    }


    /**
     * 获取运营上用户分页列表
     */
    @ApiOperation("获取运营上用户分页列表")
    //@PreAuthorize(hasPermi = "user:operator:page")
    @GetMapping("/operator/page")
    public TableDataInfo operatorPage(String userName, String nickName, Long operatorId) {
        List<Map<String, Object>> list = iXhpcUserService.selectOperatorUserList(userName, nickName, operatorId);
        return getDataTable(list);
    }

    /**
     * 新增运营商用户
     */
    @Log(title = "运营商用户", businessType = BusinessType.INSERT)
    @ApiOperation("新增运营商用户")
    @RequiresPermissions("user:operator:add")
    @PostMapping("/operator/add")
    public AjaxResult operatorAdd(@RequestBody SysUser sysUser) {
        if (null == sysUser.getOperatorId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "所属运营商不能为空");
        }
        if (iXhpcUserService.checkUserNameUnique(sysUser.getUserName(),null) > 0) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        SysRole role = new SysRole();
        role.setRoleName(sysUser.getNickName()+"运营商子角色");
        role.setRoleKey(sysUser.getUserName());
        role.setRoleSort("1");
        iXhpcUserService.insertRole(role);
        sysUser.setPhonenumber(sysUser.getUserName());
        sysUser.setDeptId(103L);
        sysUser.setDataPowerType(StatusConstants.SON_POWER_TYPE);
        sysUser.setUserType(StatusConstants.OPERATION_SON_USER_TYPE);
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setAvatar("https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/avatar/logo.png");
        Long[] roles = new Long[1];
        roles[0] = role.getRoleId();
        sysUser.setRoleIds(roles);
        sysUser.setPassword("123456");
        iXhpcUserService.insertUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 修改运营商用户
     */
    @Log(title = "运营商用户", businessType = BusinessType.UPDATE)
    @ApiOperation("修改运营商用户")
    @RequiresPermissions("user:operator:edit")
    @PostMapping("/operator/edit")
    public AjaxResult operatorEdit(@RequestBody SysUser sysUser) {
        if (null == sysUser.getUserId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户id不能为空");
        }
        if (null == sysUser.getOperatorId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "所属运营上不能为空");
        }
        iXhpcUserService.updateUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 运营商用户详情
     */
    @ApiOperation("运营商用户详情")
    //@PreAuthorize(hasPermi = "user:operator:info")
    @GetMapping("/operator/info")
    public AjaxResult operatorInfo(@RequestParam Long userId) {
        return AjaxResult.success(iXhpcUserService.operatorInfo(userId));
    }

    /**
     * 禁用/启用平台和运营商子账号
     */
    @Log(title = "平台和运营商子账号-禁用启用", businessType = BusinessType.UPDATE)
    @ApiOperation("禁用/启用平台和运营商子账号")
    //@PreAuthorize(hasPermi = "user:pc:status")
    @PostMapping("/status")
    public AjaxResult status(@RequestBody Map<String, Object> map) {
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }
        iXhpcUserService.status(Long.parseLong(userId));
        return AjaxResult.success();
    }

    /**
     * 禁用/启用平台和运营商子账号
     */
    @Log(title = "平台和运营商子账号-禁用启用", businessType = BusinessType.UPDATE)
    @ApiOperation("禁用/启用平台和运营商子账号")
    //@PreAuthorize(hasPermi = "user:pc:status")
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody Map<String, Object> map) {
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户信息不能为空");
        }
        iXhpcOperatorService.removeUser(Long.parseLong(userId));
        return AjaxResult.success();
    }


    /**
     * 重置密码
     */
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/reset")
    public AjaxResult reset(@RequestParam Long userId){

        Long userIds = SecurityUtils.getUserId();
        SysUser sysUser = iXhpcUserService.pcInfo(userIds);
        if("00".equals(sysUser.getUserType())){
            SysUser user = iXhpcUserService.pcInfo(userId);
            user.setPassword("123456");
            iXhpcUserService.updateUser(user);
        }else{
            return AjaxResult.error("无访问权限");
        }

        return AjaxResult.success();
    }

    /**
     * C端用户数据维度
     * @param activity   活跃度
     * @param frequency  充电次数
     * @param amount     充电金额
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param phone    手机号
     * @return
     */
    @GetMapping("/getUserDimension")
    public TableDataInfo getUserDimension(Integer activity, Integer frequency, BigDecimal amount, String startTime, String endTime,String phone){
        List<Map<String, Object>> userDimension = iXhpcUserService.getUserDimension(activity, frequency, amount, startTime, endTime,phone);
        return getDataTable(userDimension);
    }













    private void addXhpcDataDimension(Long[] menuIds,Long userId){
        if(menuIds !=null){
            //添加数据维度
            System.out.println(menuIds.toString());
            if(menuIds !=null && menuIds.length>0){
                for (int i = 0; i <menuIds.length ; i++) {
                    Long menuId =menuIds[i];
                    //区分父级和子集
                    if(menuId>99990 && "9999".equals(menuId.toString().substring(0,4))){
                        continue;
                    }
                    iXhpcUserService.addXhpcDataDimension(userId,menuId);
                }
            }
        }
    }
}
