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

import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.TenantApplyRecord;
import com.yonge.cooleshow.biz.dal.entity.TenantInfo;
import com.yonge.cooleshow.biz.dal.entity.TenantStaff;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.service.SmsCodeService;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.service.TenantApplyRecordService;
import com.yonge.cooleshow.biz.dal.service.TenantInfoService;
import com.yonge.cooleshow.biz.dal.service.TenantStaffService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantApplyRecordWrapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.toolset.base.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
@RequestMapping("/open/tenant")
@Api(tags = "机构")
public class OpenTenantController {


    @Autowired
    private TenantApplyRecordService tenantApplyRecordService;

    @Autowired
    private TenantStaffService tenantStaffService;

    @Autowired
    private SmsCodeService smsCodeService;

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private SysConfigService sysConfigService;


    @PostMapping("/apply")
    @ApiOperation(value = "申请")
    public HttpResponseResult<Boolean> save(
            @Validated @RequestBody TenantApplyRecordWrapper.TenantApply tenantApply) {

        tenantApplyRecordService.apply(tenantApply);

        return HttpResponseResult.status(true);
    }



    @GetMapping("/checkPhone")
    @ApiOperation(value = "检查手机是否已经注册机构账户")
    public HttpResponseResult<Boolean> checkPhone(String phone) {


        // 根据手机号 判断是否已经有机构账户
        TenantStaff tenantStaff = tenantStaffService.getByPhone(phone);
        if (tenantStaff != null) {
            return HttpResponseResult.succeed(true);
        }
        return HttpResponseResult.succeed(false);
    }



    @GetMapping("/bindWechat")
    @ApiOperation(value = "绑定微信")
    public HttpResponseResult<Boolean> bindWechat(@RequestParam("phone") String phone,
                                                  @RequestParam("openId") String openId,
                                                  @RequestParam("code") String code) {
        if (StringUtils.isEmpty(openId)) {
            throw new BizException("openId不能为空");
        }
        if (StringUtils.isEmpty(phone)) {
            throw new BizException("手机号不能为空");
        }
        // 校验验证码
        boolean validCode = smsCodeService.verifyValidCode(phone, code, "LOGIN");
        if (!validCode) {
            throw new BizException("验证码错误");
        }
        // 判断当前小程序是否绑定账号
        TenantStaff staff = tenantStaffService.lambdaQuery()
                .eq(TenantStaff::getWxOpenid, openId)
                .last("limit 1").one();
        if (staff != null) {
            SysUser sysUser = sysUserService.findUserById(staff.getUserId());
            if (sysUser != null && !phone.equals(sysUser.getPhone())) {
                throw new BizException("当前账号已绑定");
            }
            // 判断当前账号是否锁定
            if (UserLockFlag.LOCKED.equals(staff.getStatus())) {
                throw new BizException("当前账号已锁定");
            }
        }

        TenantStaff tenantStaff = tenantStaffService.getByPhone(phone);
        if (tenantStaff == null) {
            TenantApplyRecord one = tenantApplyRecordService.lambdaQuery()
                    .eq(TenantApplyRecord::getPhone, phone)
                    .orderByDesc(TenantApplyRecord::getCreateTime)
                    .last("limit 1").one();
            if (one == null || AuthStatusEnum.UNPASS.equals(one.getStatus())) {
                throw new BizException(5002, "请先申请机构入驻");
            }
            if (AuthStatusEnum.DOING.equals(one.getStatus())) {
                throw new BizException(5003, "请等待审核完成");
            }
        } else {
            // 判断当前账号是否已绑定
            if (StringUtils.isNotBlank(tenantStaff.getWxOpenid()) && !openId.equals(tenantStaff.getWxOpenid())) {
                throw new BizException("您登录的机构账号与绑定微信不匹配");
            }
        }

        Long tenantId = tenantStaff.getTenantId();
        TenantInfo tenantInfo = tenantInfoService.getById(tenantId);
        if(tenantInfo == null){
            throw new BizException("机构不存在");
        }
        if (Boolean.FALSE.equals(tenantInfo.getEnableFlag())) {
            // 机构冻结
            throw new BizException(5004, openId);
        }
        tenantStaff.setWxOpenid(openId);
        tenantStaffService.updateById(tenantStaff);
        return HttpResponseResult.succeed();
    }
}