package shop.alien.gateway.controller;

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.entity.result.R;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.StoreUserVo;
import shop.alien.gateway.config.BaseRedisService;
import shop.alien.gateway.mapper.StoreUserGatewayMapper;
import shop.alien.gateway.service.StoreUserService;

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

/**
 * 门店用户 前端控制器
 *
 * @author ssk
 * @since 2024-12-11
 */
@Slf4j
@Api(tags = {"二期-门店用户"})
@ApiSort(8)
@CrossOrigin
@RestController
@RequestMapping("/store/user")
@RequiredArgsConstructor
public class StoreUserController {

    private final StoreUserService storeUserService;

    private final StoreUserGatewayMapper storeUserMapper;

    private final BaseRedisService baseRedisService;

    @ApiOperation("门店用户登录")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "isPassword", value = "是否密码登录", dataType = "Boolean", paramType = "query", required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", paramType = "query", required = false)
    })
    @GetMapping("/login")
    public R<StoreUserVo> login(
            @RequestParam("phone") String phone,
            @RequestParam(value ="password",required = false) String password,
            @RequestParam("isPassword") Boolean isPassword,
            @RequestParam(value ="code",required = false) String code) {
        log.info("StoreUserController.login?phone={}&password={}&isPassword={}&code={}", phone, password, isPassword, code);
        if (!isPassword) {
            // 2025-11-04 验证码-商户端登录
            String cacheCode = baseRedisService.getString("verification_store_login_" + phone);
            if (null == cacheCode) {
                return R.fail("验证码过期或未发送");
            }
            if (!cacheCode.trim().equals(code.trim())) {
                return R.fail("验证码错误，请重新输入");
            }
        }
        StoreUser storeUser = new StoreUser();
        storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                .eq(StoreUser::getPhone, phone));
        if (null == storeUser) {
            StoreUser user = new StoreUser();
            user.setPhone(phone);
            user.setPassType(2);
            user.setNickName(phone);
            user.setCreatedTime(new Date());
            user.setPassword("");
            int num = storeUserMapper.insert(user);
            if(num > 0){
                storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                        .eq(StoreUser::getPhone, phone));
                storeUserService.createToKen(storeUser);
            }
        }
        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) : storeUserService.createToKen(user)).
                orElseGet(() -> R.fail("手机号不存在"));
    }

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

    /**
     * 切换子账号门店（类似登录接口，无需密码和验证码）
     */
    @ApiOperation(value = "切换子账号门店", notes = "切换子账号当前操作的门店，相当于无密码无验证码的登录接口，返回用户信息和token，包含角色id")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID（store_user.id）", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "目标门店ID", dataType = "Integer", paramType = "query", required = false),
            @ApiImplicitParam(name = "accountType", value = "主子账号类型", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/switchSubAccountStore")
    public R<StoreUserVo> switchSubAccountStore(
            @RequestParam("userId") Integer userId, 
            @RequestParam(value = "storeId", required = false) Integer storeId,
            @RequestParam("accountType") Integer accountType) {
        log.info("StoreUserController.switchSubAccountStore?userId={}, storeId={}, accountType={}", userId, storeId, accountType);
        return storeUserService.switchSubAccountStore(userId, storeId, accountType);
    }

}
