package com.xhpc.user.controller;

import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.domain.R;
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.annotation.PreAuthorize;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import com.xhpc.user.domain.XhpcInternetUser;
import com.xhpc.user.service.IXhpcInternetUserService;
import com.xhpc.user.service.IXhpcStationInternetBlacklistService;
import com.xhpc.user.service.IXhpcUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 流量用户
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/internet")
public class XhpcInternetUserController extends BaseController {

    @Autowired
    private IXhpcInternetUserService iXhpcInternetUserService;

    @Autowired
    private IXhpcUserService iXhpcUserService;

    @Autowired
    private IXhpcStationInternetBlacklistService xhpcStationInternetBlacklistService;

    @Autowired
    private TokenService tokenService;
    /**
     * 新增流量用户
     */
    @Log(title = "流量用户", businessType = BusinessType.INSERT)
    @ApiOperation("新增流量用户")
    @PostMapping("/add")
    public AjaxResult add(@Valid @RequestBody XhpcInternetUser xhpcInternetUser) {

        LoginUser loginUser = tokenService.getLoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(xhpcInternetUser.getPhone());
        sysUser.setNickName(xhpcInternetUser.getName());
        sysUser.setPhonenumber(xhpcInternetUser.getPhone());
        sysUser.setDeptId(loginUser.getSysUser().getDeptId());
        sysUser.setSex("0");
        sysUser.setUserType(StatusConstants.INTERNET_USER_TYPE);
        sysUser.setDataPowerType(StatusConstants.INTERNET_POWER_TYPE);
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setPassword("123456");
        sysUser.setTenantId(loginUser.getTenantId());
        sysUser.setAvatar("https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/avatar/logo.png");
        Long[] role = new Long[1];
        role[0] = xhpcInternetUser.getRoleId();
        sysUser.setRoleIds(role);
        if (iXhpcUserService.checkUserNameUnique(sysUser.getUserName(),null) > 0) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        if(xhpcInternetUser.getOperatorIdEvcs().length()!=9){
            return AjaxResult.error("operatorId长度9位");
        }
        //第三方平台及监管平台的operatorId 不能重复
        int count = iXhpcInternetUserService.getCountOperatorIdEvcs(null, xhpcInternetUser.getOperatorIdEvcs());
        if(count>0){
            return AjaxResult.error("operatorId已存在");
        }
        xhpcInternetUser.setTenantId(loginUser.getTenantId());
        iXhpcInternetUserService.insert(xhpcInternetUser);
        sysUser.setInternetUserId(xhpcInternetUser.getInternetUserId());
        iXhpcUserService.insertUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 修改流量用户
     */
    @Log(title = "流量用户", businessType = BusinessType.UPDATE)
    @ApiOperation("修改流量用户")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody XhpcInternetUser xhpcInternetUser) {
        if (null == xhpcInternetUser.getInternetUserId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户id不能为空");
        }
        String operatorIdEvcs = xhpcInternetUser.getOperatorIdEvcs();
        if(operatorIdEvcs.length()!=9){
            return AjaxResult.error("operatorId长度9位");
        }

        //第三方平台及监管平台的operatorId 不能重复
        int count = iXhpcInternetUserService.getCountOperatorIdEvcs(xhpcInternetUser.getInternetUserId(), operatorIdEvcs);
        if(count>0){
            return AjaxResult.error("operatorId已存在");
        }
        //operatorId变化，修改黑名单
        Long internetUserId = xhpcInternetUser.getInternetUserId();
        Map<String, Object> info = iXhpcInternetUserService.info(internetUserId);
        if(info !=null && info.get("operatorIdEvcs") !=null){
            if(!xhpcInternetUser.getOperatorIdEvcs().equals(info.get("operatorIdEvcs").toString())){
                xhpcStationInternetBlacklistService.updateByOperatorIdEvcs(internetUserId+"",operatorIdEvcs);
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(xhpcInternetUser.getPhone());
        sysUser.setNickName(xhpcInternetUser.getName());
        sysUser.setPhonenumber(xhpcInternetUser.getPhone());
        sysUser.setUserName(xhpcInternetUser.getPhone());
        sysUser.setPassword("123456");
        sysUser.setInternetUserId(internetUserId);
        iXhpcUserService.updateInternetUser(sysUser);
        return toAjax(iXhpcInternetUserService.update(xhpcInternetUser));
    }

    /**
     * 删除流量用户
     */
    @Log(title = "流量用户", businessType = BusinessType.DELETE)
    @ApiOperation("删除流量用户")
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody Map<String, Object> map) {
        String ids = StringUtils.valueOf(map.get("ids"));
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "流量用户信息不能为空");
        }
        boolean b = iXhpcInternetUserService.deleteByIds(ids.split(","));
        if(b){
            return AjaxResult.success();
        }
        return AjaxResult.error("删除失败请联系管理员");
    }

    /**
     * 流量用户详情
     */
    @ApiOperation("流量用户详情")
    //@PreAuthorize(hasPermi = "user:internet:info")
    @GetMapping("/info")
    public AjaxResult info(@RequestParam Long internetUserId) {
        return AjaxResult.success(iXhpcInternetUserService.info(internetUserId));
    }

    /**
     * 流量用户分页列表
     */
    //@PreAuthorize(hasPermi = "system:internet:page")
    @GetMapping("/page")
    public TableDataInfo page(String name, String contactName, String contactPhone, String createTimeStart, String createTimeEnd) {
        startPage();
        List<Map<String, Object>> list = iXhpcInternetUserService.selectInternetList(name, contactName, contactPhone, createTimeStart, createTimeEnd);
        return getDataTable(list);
    }

    /**
     * 禁用/启用流量用户
     */
    @Log(title = "流量用户-禁用启用", businessType = BusinessType.UPDATE)
    @ApiOperation("禁用/启用流量用户")
    @PostMapping("/status")
    public AjaxResult status(@RequestBody Map<String, Object> map) {
        String internetUserId = StringUtils.valueOf(map.get("internetUserId"));
        if (StringUtils.isEmpty(internetUserId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "流量用户信息不能为空");
        }
        boolean b = iXhpcInternetUserService.status(Long.parseLong(internetUserId));
        if(b){
            return AjaxResult.success();
        }
        return AjaxResult.error("修改状态失败，请联系管理员");
    }

    /**
     * 流量用户列表
     */
    @ApiOperation("流量用户列表")
    //@PreAuthorize(hasPermi = "user:internet:list")
    @GetMapping("/list")
    public TableDataInfo list(String name) {
        startPage();
        List<Map<String, Object>> list = iXhpcInternetUserService.list(name);
        return getDataTable(list);
    }

    /**
     * 获取流量用户
     */
    @ApiOperation("获取流量用户")
    @GetMapping("/getOperatorIdEvcs")
    public R getOperatorIdEvcs(@RequestParam(value = "operatorIdEvcs")String operatorIdEvcs) {
        XhpcInternetUser operatorId = iXhpcInternetUserService.getOperatorIdEvcs(operatorIdEvcs);
        return R.ok(operatorId);
    }
}
