package shop.alien.storeplatform.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.config.redis.BaseRedisService;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.StoreUserVo;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.storeplatform.service.StorePlatformLoginervice;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@Api(tags = {"商户平台-注册登录"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("/storePlatformLogin")
public class StorePlatformLoginController {

    private final BaseRedisService baseRedisService;
    private final StoreUserMapper storeUserMapper;
    private final StorePlatformLoginervice storePlatformLoginService;

    @ApiOperation("注册")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/register")
    public R<Boolean> register(@RequestParam("phone") String phone, @RequestParam("password") String password, @RequestParam("code") String code) {
        log.info("StorePlatformLoginController.register?phone={}&password={}&code={}", phone, password, code);
        String cacheCode = baseRedisService.getString("verification_store_platform_register_" + phone);
        if (null == cacheCode) {
            return R.fail("当前验证码已过期或未发送");
        }
        if (!cacheCode.trim().equals(code.trim())) {
            return R.fail("验证码错误，请重新输入");
        }
        log.info("StorePlatformLoginController.register?phone={}&password={}", phone, password);
        return storePlatformLoginService.register(phone, password);
    }

    @ApiOperation("注册校验")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({@ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true)})
    @GetMapping("/checkRegister")
    public R<Boolean> checkRegister(String phone) {
        log.info("StorePlatformLoginController.checkRegister?phone={}", phone);
        Boolean res = storePlatformLoginService.checkRegister(phone);
        return R.data(res);
    }

    @ApiOperation("登录")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "isPassword", value = "是否密码登录", dataType = "Boolean", paramType = "query", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "captcha", value = "图片验证码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query")
    })
    @GetMapping("/login")
    public R<StoreUserVo> login(
            @RequestParam("phone") String phone,
            @RequestParam("isPassword") Boolean isPassword,
            String password,
            String code,
            String captcha,
            HttpSession session) {
        log.info("StorePlatformLoginController.login?phone={}&password={}&isPassword={}&code={}&captcha={}", phone, password, isPassword, code, captcha);
        if (!isPassword) {
            // 2025-11-04 验证码-商户端登录
            String cacheCode = baseRedisService.getString("verification_store_platform_login_" + phone);
            if (null == cacheCode) {
                return R.fail("验证码过期或未发送");
            }
            if (!cacheCode.trim().equals(code.trim())) {
                return R.fail("验证码错误，请重新输入");
            }
        } else {
//            String cacheCode = baseRedisService.getString("store_platform_captcha_" + phone);
            String cacheCode = (String) session.getAttribute("captcha");
            if (null == cacheCode) {
                return R.fail("验证码已过期");
            }
            if (!cacheCode.trim().equals(captcha.trim())) {
                return R.fail("验证码错误，请重新输入");
            }
        }

        StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                .eq(StoreUser::getPhone, phone));
        if (null == storeUser) {
            return R.fail("当前账号不存在，请先去注册账号！");
        }
        if (storeUser.getStatus() == 1) {
            return R.fail("账号被禁用");
        }
        if (storeUser.getLogoutFlag() != null && StoreUser.LOGOUT_FLAG_DONE == storeUser.getLogoutFlag()
                && !Integer.valueOf(-1).equals(storeUser.getStatus())) {
            return R.fail("账号已注销");
        }

        return Optional.ofNullable(storeUser).
                map(user -> isPassword ? checkPassword(user, password) : storePlatformLoginService.createToKen(user)).
                orElseGet(() -> R.fail("手机号不存在"));
    }

    private R<StoreUserVo> checkPassword(StoreUser user, String password) {
        return Objects.equals(password, user.getPassword())
                ? storePlatformLoginService.createToKen(user)
                : R.fail("密码错误");
    }

    @ApiOperation("忘记密码/修改密码/更换绑定手机号")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "newPhone", value = "新手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "confirmNewPassword", value = "新密码确认", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "类型:0:忘记密码,1:修改密码,2:更换绑定手机号", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/updatePassword")
    public R<String> updatePassword(String phone, String newPhone, String oldPassword, String newPassword, String confirmNewPassword, String verificationCode, Integer type) {
        log.info("StorePlatformLoginController.updatePassword?phone={}&newPhone={}&oldPassword={}&newPassword={}&confirmNewPassword={}&verificationCode={}&type={}", phone, newPhone, oldPassword, newPassword, confirmNewPassword, verificationCode, type);
        // 2025-11-04 验证码-商家端修改密码/忘记密码/更换绑定手机号
        String businessType = "";
        switch (type) {
            case 0:
                businessType = "forget_password";
                break;
            case 1:
                businessType = "modify_password";
                break;
            case 2:
                businessType = "modify_phone";
                break;
        }
        if (1 != type) {
            String cacheCode = baseRedisService.getString("verification_store_platform_" + businessType + "_" + phone);
            if (null == cacheCode) {
                return R.fail("当验证码过期或未发送");
            }
            if (!cacheCode.trim().equals(verificationCode.trim())) {
                return R.fail("验证码错误，请重新输入");
            }
        }
        return storePlatformLoginService.forgetOrModifyPassword(phone, newPhone, oldPassword, newPassword, confirmNewPassword, verificationCode, type);
    }

    @ApiOperation("生成验证码")
    @ApiOperationSupport(order = 5)
    @GetMapping("/generateCaptcha")
    public void generateCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        log.info("StorePlatformLoginController.generateCaptcha?session={}", session.toString());
        storePlatformLoginService.generateCaptcha(response, session);
    }

    @ApiOperation("判断当前店铺是否已到期")
    @ApiOperationSupport(order = 6)
    @GetMapping("/getExpirationTime")
    public JSONObject getExpirationTime(Integer storeId) throws Exception {
        log.info("StorePlatformLoginController.getExpirationTime?storeId={}", storeId);
        return storePlatformLoginService.getExpirationTime(storeId);
    }

}
