package com.qs.mp.web.controller.api.channel;

import cn.jsms.api.ValidSMSResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.domain.param.PromoterCreateParam;
import com.qs.mp.channel.domain.param.PromoterDataQueryParam;
import com.qs.mp.channel.domain.param.PromoterEditParam;
import com.qs.mp.channel.domain.param.PromoterQueryParam;
import com.qs.mp.channel.domain.vo.ChannelOperDataVO;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.jsms.JSMSUtils;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Cup
 * @date 2022/8/9
 */
@Api(tags = "推广员相关API")
@RestController
@RequestMapping("/api/v1/mp/channel/promoter")
public class PromoterController extends BaseApiController {

    @Autowired
    private IChannelService channelService;


    @PostMapping("/operdata/query")
    @ApiOperation("获取推广员的销售数据")
    @ApiResponses(
        @ApiResponse(code = 200, message = "成功", response = ChannelOperDataVO.class)
    )
    public AjaxResult saleDetail(@Validated @RequestBody PromoterDataQueryParam param) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        if (param.getChannelId() == null) {
            param.setChannelId(channelId);
        }
        Channel channel = channelService.getById(param.getChannelId());
        if (channel == null) {
            return AjaxResult.error("推广员不存在");
        }

        Integer days = param.getDays();
        days = days > 0 ? days : 1;

        return AjaxResult.success(channelService.getPromoterOperData(channel.getChannelNo(), days));
    }

    @PostMapping("/edit")
    @ApiOperation("编辑推广员信息")
    public AjaxResult edit(@Validated @RequestBody PromoterEditParam param) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        Channel channel = channelService.getById(channelId);
        if (channel == null) {
            return AjaxResult.error("门店信息不正确");
        }

        int count = channelService.count(
            new LambdaQueryWrapper<Channel>().eq(Channel::getChannelId, param.getChannelId())
                .eq(Channel::getParentId, channelId));

        if (count <= 0) {
            return AjaxResult.error("您没有权限编辑该推广员信息");
        }

        if (param.getCommRate().compareTo(channel.getCommRate()) > 0) {
            return AjaxResult.error("佣金比例不能大于门店的佣金比例");
        }

        if (param.getCommRate().compareTo(BigDecimal.ZERO) < 0) {
            return AjaxResult.error("佣金比例不能小于0");
        }

        // 更新推广员信息
        channelService.update(new LambdaUpdateWrapper<Channel>()
            .set(Channel::getWorkNo, param.getWorkNo())
            .set(Channel::getName, param.getName())
            .set(Channel::getCommRate, param.getCommRate())
            .eq(Channel::getChannelId, param.getChannelId()));

        return AjaxResult.success();
    }


    @PostMapping("/delete/{id}")
    @ApiOperation("删除推广员")
    @ApiImplicitParams(
        @ApiImplicitParam(name = "id", value = "推广员id", required = true, dataType = "Long", paramType = "path")
    )
    public AjaxResult delete(@PathVariable("id") Long id) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        int count = channelService.count(
            new LambdaQueryWrapper<Channel>().eq(Channel::getChannelId, id)
                .eq(Channel::getParentId, channelId));
        if (count <= 0) {
            return AjaxResult.error("您没有权限删除该推广员");
        }

        channelService.deletePromoter(id);
        return AjaxResult.success();
    }


    @PostMapping("/list")
    @ApiOperation("门店下推广员列表")
    @ApiResponses(
        @ApiResponse(code = 200, message = "OK", response = Channel.class)
    )
    public TableDataInfo promoterList(@RequestBody PromoterQueryParam param) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();

        if (param.getChannelId() == null) {
            param.setChannelId(channelId);
        }

        Channel channel = channelService.getById(param.getChannelId());
        if (channel == null) {
            getErrorDataTable("门店信息不正确");
        }

        startPage();
        List<Channel> list = channelService.list(new LambdaQueryWrapper<Channel>()
            .eq(Channel::getParentId, param.getChannelId())
            .nested(StringUtils.isNotBlank(param.getSearchValue()), queryWrapper -> {
                queryWrapper.like(Channel::getName, param.getSearchValue())
                    .or()
                    .like(Channel::getWorkNo, param.getSearchValue());
            }));

        return getDataTable(list);
    }


    @PostMapping("/create")
    @ApiOperation("门店创建推广员接口")
    @ApiResponses(
        @ApiResponse(code = 200, message = "成功")
    )
    public AjaxResult promoterCreate(@Validated @RequestBody PromoterCreateParam param) {
        Long channelId = SecurityUtils.getLoginUser().getChannelId();
        param.setChannelId(channelId);


        int mobileCount = channelService.count(new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, param.getMobile()));
        if (mobileCount > 0) {
            return AjaxResult.error("手机号码" + param.getMobile() + "已注册！");
        }

        // 校验推广员信息合法性
        String checkRes = channelService.checkPromoter(param);
        if (StringUtils.isNotBlank(checkRes)) {
            return AjaxResult.error(checkRes);
        }

        // 创建推广员
        channelService.createPromoter(param);

        return AjaxResult.success();
    }


    @PostMapping("/register")
    @ApiOperation("邀请链接注册推广员接口")
    @ApiResponses(
        @ApiResponse(code = 200, message = "成功")
    )
    public AjaxResult promoterRegister(@Validated @RequestBody PromoterCreateParam param) {
        Long channelId = param.getChannelId();
        Channel channel = channelService.getById(channelId);
        if (channel == null) {
            return AjaxResult.error("门店信息不正确");
        }

        // 校验短信
        ValidSMSResult res = JSMSUtils.sendValidSMSCode(param.getMessageId(), param.getCode());
        if (res == null || !res.getIsValid()) {
            return AjaxResult.error("短信验证码错误");
        }

        int mobileCount = channelService.count(new LambdaQueryWrapper<Channel>().eq(Channel::getMobile, param.getMobile()));
        if (mobileCount > 0) {
            return AjaxResult.error("手机号码" + param.getMobile() + "已注册！");
        }


        // 校验推广员信息合法性
        String checkRes = channelService.checkPromoter(param);
        if (StringUtils.isNotBlank(checkRes)) {
            return AjaxResult.error(checkRes);
        }

        // 创建推广员
        channelService.createPromoter(param);

        return AjaxResult.success();
    }


}
