
package com.tmerclub.cloud.supplier.controller.supplier;

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.biz.feign.NotifyFeignClient;
import com.tmerclub.cloud.api.supplier.vo.SupplierApiDetailVO;
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.supplier.dto.SupplierUserDTO;
import com.tmerclub.cloud.supplier.service.SupplierDetailService;
import com.tmerclub.cloud.supplier.service.SupplierUserService;
import com.tmerclub.cloud.supplier.vo.SupplierUserSimpleVO;
import com.tmerclub.cloud.supplier.vo.SupplierUserVO;
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("/s/supplier_user")
@RestController
@Tag(name = "供应商用户信息")
public class SupplierUserController {

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

    @Autowired
    private SupplierDetailService supplierDetailService;

    @DubboReference
    private NotifyFeignClient notifyFeignClient;

    @GetMapping("/info")
    @Operation(summary = "登陆供应商用户信息", description = "获取当前登陆供应商用户的用户信息")
    public ServerResponseEntity<SupplierUserSimpleVO> info() {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        SupplierUserSimpleVO supplierUserSimple = new SupplierUserSimpleVO();
        supplierUserSimple.setIsAdmin(uidInfoBO.getIsAdmin());
        supplierUserSimple.setUserName(uidInfoBO.getUsername());
        if (!Objects.equals(uidInfoBO.getTenantId(), Constant.DEFAULT_SHOP_ID)) {
            SupplierApiDetailVO supplierDetail = supplierDetailService.getBySupplierId(uidInfoBO.getTenantId());
            supplierUserSimple.setAvatar(supplierDetail.getSupplierLogo());
            supplierUserSimple.setSupplierName(supplierDetail.getSupplierName());
        }
        return ServerResponseEntity.success(supplierUserSimple);
    }

    @GetMapping("/page")
    @Operation(summary = "供应商用户列表", description = "获取供应商用户列表")
    public ServerResponseEntity<PageVO<SupplierUserVO>> page(@Valid PageDTO pageDTO, SupplierUserDTO supplierUserDTO) {
        UidInfoBO uidInfoBO = AuthUserContext.get();
        supplierUserDTO.setSupplierId(uidInfoBO.getTenantId());
        PageVO<SupplierUserVO> supplierUserPage = supplierUserService.pageBySupplierId(pageDTO, supplierUserDTO);
        return ServerResponseEntity.success(supplierUserPage);
    }

    @GetMapping
    @Operation(summary = "获取供应商用户信息", description = "根据用户id获取供应商用户信息")
    public ServerResponseEntity<SupplierUserVO> detail(@RequestParam Long supplierUserId) {
        SupplierUserVO supplierUserVO = supplierUserService.getByUserId(supplierUserId);
        if (StrUtil.isNotBlank(supplierUserVO.getPhone())) {
            supplierUserVO.setPhone(PhoneUtil.hideBetween(supplierUserVO.getPhone()).toString());
        }
        if (StrUtil.isNotBlank(supplierUserVO.getPhoneNum())) {
            supplierUserVO.setPhoneNum(PhoneUtil.hideBetween(supplierUserVO.getPhoneNum()).toString());
        }
        return ServerResponseEntity.success(supplierUserVO);
    }

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

    @PutMapping
    @Operation(summary = "更新供应商用户信息", description = "更新供应商用户信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody SupplierUserDTO supplierUserDTO) {
        // 线上的supplier账户资料不可修改
        String userName = "supplier";
        // 暂时的supplier账号id
        Long supplierId = 590099128320L;
        if (Objects.equals(supplierUserDTO.getUsername(), userName) && Objects.equals(supplierUserDTO.getSupplierUserId(), supplierId) && BooleanUtil.isFalse(permission)) {
            throw new LuckException("暂无权限修改该用户信息");
        }
        SupplierUserVO dbSupplierUser = supplierUserService.getByUserId(supplierUserDTO.getSupplierUserId());
        if (!Objects.equals(dbSupplierUser.getSupplierId(), AuthUserContext.get().getTenantId())) {
            return ServerResponseEntity.fail(ResponseEnum.UNAUTHORIZED);
        }
        if (!PrincipalUtil.isDbPhone(supplierUserDTO.getPhone(), dbSupplierUser.getPhone(), false)) {
            throw new LuckException("请输入正确的手机号");
        }
        if (supplierUserDTO.getPhone().contains(Constant.ASTERISK)) {
            supplierUserDTO.setPhone(dbSupplierUser.getPhone());
        }
        // 如果修改了手机号码，就需要校验验证码
        if (!StrUtil.equals(dbSupplierUser.getPhone(), supplierUserDTO.getPhone())) {
            if (StrUtil.isBlank(supplierUserDTO.getValidCode())) {
                throw new LuckException("修改了手机号，请输入验证码校验");
            }
            checkCode(supplierUserDTO);
        }
        supplierUserDTO.setSupplierId(dbSupplierUser.getSupplierId());
        supplierUserService.updateAccount(supplierUserDTO);
        return ServerResponseEntity.success();
    }

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

    @GetMapping("/verify_account")
    @Operation(summary = "验证供应商账号", description = "根据用户id获取供应商用户信息")
    public ServerResponseEntity<Boolean> verifyAccount(SupplierUserDTO supplierUserDTO) {
        // 验证手机号/邮箱/用户名在数据库中是否已经存在
        return supplierUserService.verifySupplierUserAccount(supplierUserDTO);
    }

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