
package com.tmerclub.cloud.multishop.controller.multishop;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.auth.bo.UidInfoBO;
import com.tmerclub.cloud.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.vo.AuthAccountVO;
import com.tmerclub.cloud.api.biz.feign.NotifyFeignClient;
import com.tmerclub.cloud.api.multishop.vo.ShopDetailVO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.SendTypeEnum;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ResponseEnum;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.common.util.PrincipalUtil;
import com.tmerclub.cloud.multishop.dto.ShopUserDTO;
import com.tmerclub.cloud.multishop.service.ShopDetailService;
import com.tmerclub.cloud.multishop.service.ShopUserService;
import com.tmerclub.cloud.multishop.vo.ShopUserSimpleVO;
import com.tmerclub.cloud.multishop.vo.ShopUserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author tmerclub
 * @date 2020/09/02
 */
@RequestMapping("/m/shopUser")
@RestController
@Tag(name = "店铺用户信息")
public class ShopUserController {

    @Value("${tmerclub.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private ShopUserService shopUserService;

    @Autowired
    private ShopDetailService shopDetailService;

    @DubboReference
    private NotifyFeignClient notifyFeignClient;

    @DubboReference
    private AccountFeignClient accountFeignClient;

    @GetMapping("/info")
    @Operation(summary = "登陆店铺用户信息", description = "获取当前登陆店铺用户的用户信息")
    public ServerResponseEntity<ShopUserSimpleVO> info() {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        ShopUserSimpleVO shopUserSimple = new ShopUserSimpleVO();
        shopUserSimple.setIsAdmin(uidInfoBO.getIsAdmin());
        shopUserSimple.setUserName(uidInfoBO.getUsername());
        if (!Objects.equals(uidInfoBO.getTenantId(), Constant.DEFAULT_SHOP_ID)) {
            ShopDetailVO shopDetail = shopDetailService.getByShopId(uidInfoBO.getTenantId());
            shopUserSimple.setShopName(shopDetail.getShopName());
            shopUserSimple.setAvatar(shopDetail.getShopLogo());
        }
        return ServerResponseEntity.success(shopUserSimple);
    }

    @GetMapping("/page")
    @Operation(summary = "店铺用户列表", description = "获取店铺用户列表")
    public ServerResponseEntity<PageVO<ShopUserVO>> page(@Valid PageDTO pageDTO, ShopUserDTO shopUserDTO) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        shopUserDTO.setShopId(uidInfoBO.getTenantId());
        PageVO<ShopUserVO> shopUserPage = shopUserService.pageByShopId(pageDTO, shopUserDTO);
        return ServerResponseEntity.success(shopUserPage);
    }

    @GetMapping
    @Operation(summary = "获取店铺用户信息", description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<ShopUserVO> detail(@RequestParam Long shopUserId) {
        ShopUserVO shopUserVO = shopUserService.getByUserId(shopUserId);
        if (StrUtil.isNotBlank(shopUserVO.getPhone())) {
            shopUserVO.setPhone(PhoneUtil.hideBetween(shopUserVO.getPhone()).toString());
        }
        if (StrUtil.isNotBlank(shopUserVO.getPhoneNum())) {
            shopUserVO.setPhoneNum(PhoneUtil.hideBetween(shopUserVO.getPhoneNum()).toString());
        }
        return ServerResponseEntity.success(shopUserVO);
    }

    @PostMapping
    @Operation(summary = "保存店铺用户信息", description = "保存店铺用户信息")
    public ServerResponseEntity<Void> save(@Valid @RequestBody ShopUserDTO shopUserDTO) {
        if (!PrincipalUtil.isMobile(shopUserDTO.getPhone())) {
            throw new LuckException("请输入正确格式的手机号!");
        }
        if (StrUtil.isBlank(shopUserDTO.getValidCode())) {
            throw new LuckException("请输入验证码");
        }
        shopUserDTO.setShopId(AuthUserContext.get().getTenantId());
        checkCode(shopUserDTO);
        shopUserService.saveAccount(shopUserDTO);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @Operation(summary = "更新店铺用户信息", description = "更新店铺用户信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody ShopUserDTO shopUserDTO) {
        // 暂时的home账号id
        Long home = 109707L;
        if (Objects.equals(shopUserDTO.getShopUserId(), home) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户信息");
        }
        ShopUserVO dbShopUser = shopUserService.getByUserId(shopUserDTO.getShopUserId());
        if (!Objects.equals(dbShopUser.getShopId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (!PrincipalUtil.isDbPhone(shopUserDTO.getPhone(), dbShopUser.getPhone(), false)) {
            throw new LuckException("请输入正确的手机号");
        }
        if (shopUserDTO.getPhone().contains(Constant.ASTERISK)) {
            shopUserDTO.setPhone(dbShopUser.getPhone());
        }
        //TODO 去掉验证码校验
        // 如果修改了手机号码，就需要校验验证码
//        if (!StrUtil.equals(dbShopUser.getPhone(), shopUserDTO.getPhone())) {
//            if (StrUtil.isBlank(shopUserDTO.getValidCode())) {
//                throw new LuckException("修改了手机号，请输入验证码校验");
//            }
//            checkCode(shopUserDTO);
//        }
        shopUserDTO.setShopId(dbShopUser.getShopId());
        ServerResponseEntity<AuthAccountVO> authAccountEntity = accountFeignClient.getByUserIdAndType(dbShopUser.getShopUserId(), SysTypeEnum.MULTISHOP.value());
        if (!authAccountEntity.isSuccess()) {
            throw new LuckException(authAccountEntity.getMsg());
        }
        AuthAccountVO authAccountVO = authAccountEntity.getData();
        if (Objects.equals(authAccountVO.getIsAdmin(), 1) && !Objects.equals(dbShopUser.getShopUserId(), AuthUserContext.get().getUserId())) {
            return ServerResponseEntity.showFailMsg("您没有权限修改管理员信息");
        }
        shopUserService.updateAccount(shopUserDTO);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除店铺用户信息", description = "根据店铺用户id删除店铺用户信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long shopUserId) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        ShopUserVO dbShopUser = shopUserService.getByUserId(shopUserId);
        if (!Objects.equals(dbShopUser.getShopId(), uidInfoBO.getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        } else if (Objects.equals(uidInfoBO.getUserId(), shopUserId)) {
            throw new LuckException("您正在使用当前账号，无法进行删除操作");
        }
        shopUserService.deleteById(shopUserId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/verify_account")
    @Operation(summary = "验证店铺账号", description = "根据用户id获取店铺用户信息")
    public ServerResponseEntity<Boolean> verifyAccount(ShopUserDTO shopUserDTO) {
        // 验证手机号/邮箱/用户名在数据库中是否已经存在
        return shopUserService.verifyShopUserAccount(shopUserDTO);
    }

    /**
     * 校验验证码
     * @param shopUserDTO
     * @return
     */
    private void checkCode(ShopUserDTO shopUserDTO) {
        // 手机号验证码
        String phone = shopUserDTO.getPhone();
        if (StrUtil.isNotBlank(phone)) {
            ServerResponseEntity<Boolean> sendNotifyResponse = notifyFeignClient.checkValidCode(phone, shopUserDTO.getValidCode(), SendTypeEnum.VALID);
            Boolean data = sendNotifyResponse.getData();
            //TODO 去掉验证码校验
//            if (Objects.equals(sendNotifyResponse.getCode(), ResponseEnum.OK.value()) && Objects.nonNull(data) && !data) {
//                throw new LuckException("验证码有误或已过期!");
//            }
        }
        //邮箱验证码
    }
}
