package com.yonge.cooleshow.tenant.controller.open;

import com.alibaba.fastjson.JSON;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.Student;
import com.yonge.cooleshow.biz.dal.entity.TenantGroup;
import com.yonge.cooleshow.biz.dal.entity.TenantInfo;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.TenantGroupMapper;
import com.yonge.cooleshow.biz.dal.service.SmsCodeService;
import com.yonge.cooleshow.biz.dal.service.StudentService;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.service.TenantInfoService;
import com.yonge.cooleshow.biz.dal.wrapper.StudentWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.tenant.vo.StudentVo;
import com.yonge.toolset.base.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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;

import java.util.Objects;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("${app-config.url.tenant:}/open/student")
@Api(value = "学生表", tags = "学生表")
public class OpenStudentController extends BaseController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SmsCodeService smsCodeService;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TenantGroupMapper tenantGroupMapper;

    @PostMapping("/save")
    @ApiOperation(value = "新增/修改", notes = "传入Student,换绑时按照返回错误码5004判断，是否需要换绑，updateTenant=true表示换绑")
    public HttpResponseResult<String> save(@Validated @RequestBody StudentVo.Student student) {
        String code = student.getCode();
        if (StringUtils.isEmpty(code)) {
            throw new BizException("验证码不能为空");
        }
        if (!smsCodeService.verifyValidCode(student.getPhone(), code, "REGISTER")) {
            throw new BizException("验证码错误");
        }
        Long tenantId = student.getTenantId();
        if (tenantId == null) {
            throw new BizException("未指定机构");
        }
        TenantInfo tenantInfo = tenantInfoService.getById(tenantId);
        if (tenantInfo == null) {
            throw new BizException("机构不存在");
        }
        Long tenantGroupId = student.getTenantGroupId();
        TenantGroup tenantGroup = tenantGroupMapper.selectById(tenantGroupId);
        if (tenantGroup == null) {
            throw new BizException("该链接已失效");
        }
        Long studentId = student.getId();

        if (studentId == null) {
            SysUser sysUser = sysUserFeignService.queryUserByMobile(student.getPhone());
            if (sysUser != null && sysUser.getUserType().contains(ClientEnum.STUDENT.getCode())) {
                studentId = sysUser.getId();
            }
        }

        if (studentId != null) {
            Student one = studentService.lambdaQuery()
                    .eq(Student::getUserId, studentId)
                    .last("limit 1").one();
            if (one != null) {
                if (one.getTenantId().equals(-1L)) {
                    throw new BizException("该手机号已经注册为平台学生");
                }
                if (one.getTenantId().equals(tenantId)) {
                    //已经注册当前机构，请勿重复注册
                    throw new BizException("已经注册当前机构，请勿重复注册");
                }
                // 转到其他机构
                if ((!Objects.equals(student.getTenantId(), one.getTenantId()))) {
                    if (student.getUpdateTenant() == null || Boolean.FALSE.equals(student.getUpdateTenant())) {
                        TenantInfo oldTenant = tenantInfoService.getById(one.getTenantId());
                        throw new BizException(5004, oldTenant.getName());
                    }
                }

                // 更新头像
                if (StringUtils.isEmpty(student.getAvatar())) {
                    student.setAvatar(one.getAvatar());
                }
            }
            student.setId(studentId);
        }

        // 自动注册登陆验证码
        String loginCode = "";
        if (Optional.ofNullable(student.getLoginCode()).orElse(false)) {
            // 生成登陆验证码
            loginCode = sysMessageService.sendSecurityCode(MessageTypeEnum.SMS_VERIFY_CODE_LOGIN, student.getPhone());
        }

        // 保存学生信息
        StudentWrapper.Student studentInfo = JSON.parseObject(JSON.toJSONString(student), StudentWrapper.Student.class);
        studentInfo.setTenantId(tenantInfo.getId());

        studentService.save(studentInfo);

        return succeed(loginCode);
    }
}