package com.xhpc.user.controller;

import com.xhpc.common.api.TenantService;
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.XhpcOperator;
import com.xhpc.user.service.IXhpcOperatorService;
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.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 运营商
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/operator")
public class XhpcOperatorController extends BaseController {

    @Autowired
    private IXhpcOperatorService iXhpcOperatorService;

    @Autowired
    private IXhpcUserService iXhpcUserService;
    @Autowired
    private TokenService tokenService;
    @Resource
    TenantService tenantService;

    /**
     * 新增运营商
     */
    @Log(title = "运营商", businessType = BusinessType.INSERT)
    @ApiOperation("新增运营商")
    @RequiresRoles("admin")
    @PostMapping("/add")
    public AjaxResult add(@Valid @RequestBody XhpcOperator xhpcOperator) {

        LoginUser loginUser = tokenService.getLoginUser();
        xhpcOperator.setTenantId(loginUser.getTenantId());
        xhpcOperator.setCorpNo(xhpcOperator.getOperatorIdEvcs());
        SysUser sysUser = new SysUser();
        BigDecimal t3 =new BigDecimal(100);
        BigDecimal t4 =new BigDecimal(0);
        BigDecimal t5 =new BigDecimal(80);
        if(xhpcOperator.getPlatformCommissionRate() !=null && xhpcOperator.getMaintenanceCommissionRate() !=null){
            BigDecimal t1 =new BigDecimal(xhpcOperator.getPlatformCommissionRate());
            BigDecimal t2 =new BigDecimal(xhpcOperator.getMaintenanceCommissionRate());

            if (t3.compareTo(t1.add(t2)) < 0) {
                return AjaxResult.error("平台提成和运维提成之和不能大于100");
            }
            if (t1.compareTo(t4) < 0) {
                return AjaxResult.error("平台提成不能小于0");
            }
            if (t2.compareTo(t4) < 0) {
                return AjaxResult.error("运维提成不能小于0");
            }
        }else{
            return AjaxResult.error("平台提成或运维提成不能小于0");
        }
        if("".equals(xhpcOperator.getSoc()) || xhpcOperator.getSoc() ==null){
            return AjaxResult.error("请填写充电终止的soc");
        }else{
            BigDecimal t2 =new BigDecimal(xhpcOperator.getSoc());
            if (t3.compareTo(t2) < 0) {
                return AjaxResult.error("充电终止的soc不能大于100");
            }
            if (t2.compareTo(t5) < 0) {
                return AjaxResult.error("充电终止的soc不能小于80");
            }
        }
        if(xhpcOperator.getRoleId()==null){
            return AjaxResult.error("请选择角色");
        }

        R r = tenantService.getTenantDetail(xhpcOperator.getTenantId());
        if(r.getCode() != 200){
            return AjaxResult.error("该租户已过期或已停用，请联系管理员");
        }
        Map data =(Map) r.getData();
        int operatorQuote = data.get("operatorQuote") == null ? 1: Integer.parseInt(data.get("operatorQuote").toString());
        List<XhpcOperator> operators = iXhpcOperatorService.getOperatorListByTenantId(xhpcOperator.getTenantId());
        if( -1 != operatorQuote && operators.size() >= operatorQuote){
            return AjaxResult.error("该租户运营商已超限额，无法创建");
        }

        sysUser.setUserName(xhpcOperator.getPhone());
        sysUser.setNickName(xhpcOperator.getName());
        sysUser.setEmail(xhpcOperator.getEmail());
        sysUser.setPhonenumber(xhpcOperator.getPhone());
        sysUser.setDeptId(loginUser.getSysUser().getDeptId());
        sysUser.setSex("0");
        sysUser.setUserType(StatusConstants.OPERATION_USER_TYPE);
        sysUser.setDataPowerType(1);
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setAvatar("https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/avatar/logo.png");
        sysUser.setPassword("123456");
        sysUser.setTenantId(xhpcOperator.getTenantId());
        Long[] roleIds = new Long[1];
        roleIds[0] = xhpcOperator.getRoleId();
        sysUser.setRoleIds(roleIds);
        if (iXhpcUserService.checkUserNameUnique(sysUser.getUserName(),null) > 0) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        }
        iXhpcOperatorService.insert(xhpcOperator);

        sysUser.setOperatorId(xhpcOperator.getOperatorId());
        sysUser = iXhpcUserService.insertUser(sysUser);
        return AjaxResult.success();
    }

    /**
     * 修改运营商
     */
    @Log(title = "运营商", businessType = BusinessType.UPDATE)
    @ApiOperation("修改运营商")
    @PreAuthorize(hasPermi = "user:operator:edit")
    @RequiresRoles("admin")
    @PostMapping("/edit")
    public AjaxResult edit(@Valid @RequestBody XhpcOperator xhpcOperator) {
        if (null == xhpcOperator.getOperatorId()) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "运营商id不能为空");
        }
        SysUser sysUser = new SysUser();
        sysUser.setNickName(xhpcOperator.getName());
        sysUser.setEmail(xhpcOperator.getEmail());
        sysUser.setPhonenumber(xhpcOperator.getPhone());
        sysUser.setUserName(xhpcOperator.getPhone());
        sysUser.setPassword("123456");
        iXhpcUserService.updateUser(sysUser);
        xhpcOperator.setCorpNo(xhpcOperator.getOperatorIdEvcs());
        return toAjax(iXhpcOperatorService.update(xhpcOperator));
    }

    /**
     * 删除运营商
     */
    @Log(title = "运营商", businessType = BusinessType.DELETE)
    @ApiOperation("删除运营商")
    @RequiresRoles("admin")
    @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, "运营商信息不能为空");
        }
        iXhpcOperatorService.deleteByIds(ids);
        return AjaxResult.success();
    }

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

    /**
     * 获取运营商分页列表
     */
    //@PreAuthorize(hasPermi = "system:operator:page")
    @GetMapping("/page")
    public TableDataInfo page(String tenantId,Long operatorId,String name, String contactName, String contactPhone, String createTimeStart, String createTimeEnd) {
        startPage();
        List<Map<String, Object>> list = iXhpcOperatorService.selectOperatorList(tenantId,operatorId,name,contactName, contactPhone, createTimeStart, createTimeEnd);
        return getDataTable(list);
    }

    /**
     * 禁用/启用运营商
     */
    @Log(title = "运营商-禁用启用", businessType = BusinessType.UPDATE)
    @ApiOperation("禁用/启用运营商")
    @RequiresRoles("admin")
    @PostMapping("/status")
    public AjaxResult status(@RequestBody Map<String, Object> map) {
        String operatorId = StringUtils.valueOf(map.get("operatorId"));
        if (StringUtils.isEmpty(operatorId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "运营商信息不能为空");
        }
        iXhpcOperatorService.status(Long.parseLong(operatorId));
        return AjaxResult.success();
    }

    /**
     * 获取运营商分页列表
     */
    //@PreAuthorize(hasPermi = "system:operator:page")
    @GetMapping("/list")
    public AjaxResult list(String tenantId,Long operatorId,String name, String contactName, String contactPhone, String createTimeStart, String createTimeEnd) {
        List<Map<String, Object>> list = iXhpcOperatorService.selectOperatorList(tenantId,operatorId,name, contactName, contactPhone, createTimeStart, createTimeEnd);
        return AjaxResult.success(list);
    }


    public static void main(String[] args) {
        BigDecimal t1 =new BigDecimal("79");
        BigDecimal t2 =new BigDecimal(13);
        BigDecimal t3 =new BigDecimal(100);
        BigDecimal t4 =new BigDecimal(0);
        BigDecimal t5 =new BigDecimal(80);
        if (t1.compareTo(t5) < 0) {
            System.out.println("333");
        }


        if (t3.compareTo(t1.add(t2)) < 0) {
            System.out.println("2222222");
        }else{
            System.out.println("111");
        }

    }

}
