package org.springblade.modules.api.controller;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.AuditStatusEnum;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.api.request.AddChildAccountRequest;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserMerchant;
import org.springblade.modules.system.service.IUserMerchantService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserMerchantVO;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Author pangqijun
 * Date 2024/7/16
 * Description
 */
@RestController
@AllArgsConstructor
@RequestMapping(CommonConstant.API_URL)
@Api(value = "商家端", tags = "商家端用户接口")
public class ApiMerchantUserController {

    private final IUserMerchantService iUserMerchantService;
    private final IUserService iUserService;

    @GetMapping("/merchant/get")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取商家用户信息")
    public R<UserMerchantVO> getMerchantUserInfo() {
        User user = iUserService.getById(AuthUtil.getUserId());
        Assert.notNull(user, "未查询到用户信息");
        UserMerchantVO vo = iUserMerchantService.getByUserId(user.getId());
        vo.setAvatar(user.getAvatar());
        vo.setName(user.getName());
        vo.setRealName(vo.getRealName());
        vo.setPhone(user.getPhone());
        return R.data(vo);
    }

    @PostMapping("/merchant/update")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "更新用户信息")
    public R<Void> updateUserInfo(@RequestBody UserMerchantVO userMerchantVO) {
        User user = iUserService.getById(AuthUtil.getUserId());
        Assert.notNull(user, "未查询到用户信息");
//        UserMerchantVO vo = iUserMerchantService.getByUserId(AuthUtil.getUserId());
//        Assert.notNull(user, "未查询到商户信息");
        user.setAvatar(userMerchantVO.getAvatar());
        return R.status(iUserService.updateById(user));
    }

    @PostMapping("/addChildAccount")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "添加子账号", notes = "传入userMerchant")
    public R<Void> addChildAccount(@Valid @RequestBody AddChildAccountRequest request) {
        if (!request.getPassword().equals(request.getRePassword())) {
            return R.fail("密码不一致");
        }
        User query1 = iUserService.getOne(Wrappers.<User>query().lambda().eq(User::getAccount, request.getPhone()));
        if (query1 != null) {
            return R.fail("手机号已注册！");
        }
        String tenantId = WebUtil.getRequest().getHeader(TokenUtil.TENANT_HEADER_KEY);
        User user = new User();
        user.setAccount(request.getPhone());
        user.setPhone(request.getPhone());
        user.setTenantId(tenantId);
        user.setUserType(UserEnum.MERCHANT.getCategory());
        user.setPassword(DigestUtil.encrypt(request.getPassword()));
        user.setName(request.getNickname() == null ? DesensitizedUtil.mobilePhone(request.getPhone()) : request.getNickname());
        user.setRealName(request.getRealName());
        iUserService.save(user);

        UserMerchant userMerchant = new UserMerchant();
        userMerchant.setUserId(user.getId());
        userMerchant.setParentId(AuthUtil.getUserId());
        userMerchant.setAuditStatus(AuditStatusEnum.PASS.getValue());
        userMerchant.setAuthShop(request.getAuthShopIds());
        iUserMerchantService.save(userMerchant);

        return R.success("添加成功");
    }

    @Transactional
    @PostMapping("/deleteChildAccount")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "删除子账号", notes = "传入ids")
    public R<Void> deleteChildAccount(@ApiParam(value = "主键集合", required = true) @RequestParam Long childAccountId) {
        UserMerchant child = iUserMerchantService.getById(childAccountId);
        Assert.notNull(child, "未查询到子账号信息");
        iUserMerchantService.removeById(childAccountId);
        return R.status(iUserService.removeById(childAccountId));
    }

    /**
     * 自定义分页 商家用户表
     */
    @GetMapping("/childAccount/list")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "子账号列表", notes = "传入userMerchant")
    public R<IPage<UserMerchantVO>> page(UserMerchantVO userMerchant, Query query) {
        userMerchant.setParentId(AuthUtil.getUserId());
        IPage<UserMerchantVO> pages = iUserMerchantService.selectUserMerchantPage(Condition.getPage(query), userMerchant);
        return R.data(pages);
    }
}
