package cn.pluss.platform.controller;

import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.entity.PhoneValidateCode;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.entity.UserInfo;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.phoneValidateCode.PhoneValidateCodeService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.util.ValidateCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/phoneValidateCode")
@Transactional
@Api(value = "PhoneValidateCode控制类", tags = {"PhoneValidateCode接口"})
public class PhoneValidateCodeController {

    @Autowired
    private ValidateCodeUtil validateCodeUtil;

    @Resource
    private PhoneValidateCodeService phoneValidateCodeService;
    @Resource
    private UserInfoService uiService;

    @Autowired
    private UserAppService uaService;

    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")
    })
    public Result<PageInfo<PhoneValidateCode>> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        List<PhoneValidateCode> phoneValidateCodeList = phoneValidateCodeService.queryPhoneValidateCodePage(map);
        Integer count = phoneValidateCodeService.queryPhoneValidateCodePageCount(map);
        //返回参数
        PageInfo pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count,size), page.longValue(), size.longValue(), phoneValidateCodeList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @PostMapping
    @ApiOperation(tags = {"页面-忘记密码"}, value = "发送验证码", notes = "必须要已经注册的手机号可调用该验证码接口", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "PhoneValidateCode", value = "待添加的PhoneValidateCode实例", paramType = "body", dataType = "PhoneValidateCode", required = true)
    })
    public Result<Object> add(HttpServletRequest request, @RequestBody PhoneValidateCode phoneValidateCode) {

        String phone = phoneValidateCode.getPhone();
        if (StringUtil.isEmpty(phone)) {
            return ResultGenerator.genFailResult("没有手机号！");
        }

        LambdaQueryWrapper<UserInfo> qWui = Wrappers.lambdaQuery();
        qWui.eq(UserInfo::getLoginName, phone);
        UserInfo ui = uiService.getOne(qWui);
        if (ui == null) {
            throw new MsgException("帐号不存在");
        }

        LambdaQueryWrapper<UserApp> qWua = Wrappers.lambdaQuery();
        qWua.eq(UserApp::getUserId, ui.getId());
        UserApp ua = uaService.getOne(qWua);
        if ("promoter".equals(ua.getUserType()) && phone.length() > 11) {
            throw new MsgException("子商户不允许执行该操作");
        }

        phoneValidateCode.setPhone(ui.getPhone());

        String checkCode = StringUtil.random(4);
        phoneValidateCode.setCode(checkCode);
        try {
            Result<Object> result = validateCodeUtil.requestValidateCodeALi(phoneValidateCode.getPhone(), checkCode);
            if (result != null) {
                return result;
            }
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }

        //根据当前手机号查询当前手机号是否有验证码信息
        phoneValidateCodeService.saveOrReplaceIfExist(phoneValidateCode);
        return ResultGenerator.genSuccessResult(phoneValidateCode);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id", paramType = "path", required = true, dataType = "Integer", defaultValue = "0")
    })
    public Result<Object> detail(@PathVariable Long id) {
        PhoneValidateCode phoneValidateCode = new PhoneValidateCode();
        phoneValidateCode.setId(id.intValue());
        phoneValidateCode = phoneValidateCodeService.queryPhoneValidateCode(phoneValidateCode);
        return ResultGenerator.genSuccessResult(phoneValidateCode);
    }

}

