package com.jumeirah.api.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumeirah.api.merchant.entity.param.MerchantUserAddParam;
import com.jumeirah.api.merchant.entity.param.MerchantUserUpdateParam;
import com.jumeirah.common.entity.MerchantUser;
import com.jumeirah.common.service.MerchantUserService;
import com.jumeirah.common.vo.MerchantUserQueryVo;
import io.geekidea.springbootplus.config.properties.SpringBootPlusProperties;
import io.geekidea.springbootplus.framework.common.api.ApiResult;
import io.geekidea.springbootplus.framework.common.controller.BaseController;
import io.geekidea.springbootplus.framework.core.validator.groups.Add;
import io.geekidea.springbootplus.framework.core.validator.groups.Update;
import io.geekidea.springbootplus.framework.log.annotation.Module;
import io.geekidea.springbootplus.framework.log.annotation.OperationLog;
import io.geekidea.springbootplus.framework.log.enums.OperationLogType;
import io.geekidea.springbootplus.framework.shiro.jwt.JwtToken;
import io.geekidea.springbootplus.framework.shiro.util.SaltUtil;
import io.geekidea.springbootplus.framework.util.PasswordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 商家用户 控制器
 *
 * @author wei
 * @since 2020-09-27
 */
@Slf4j
@RestController
@RequestMapping("/merchant/user/manager")
@Module("${cfg.module}")
@Api(value = "商家账户管理API", tags = {"商家账户管理"})
public class MerchantUserManagerController extends BaseController {

    @Autowired
    private MerchantUserService merchantUserService;
    @Autowired
    private SpringBootPlusProperties springBootPlusProperties;

    /**
     * 添加商家用户
     */
    @PostMapping("/add")
    @OperationLog(name = "添加商家用户", type = OperationLogType.ADD)
    @ApiOperation(value = "添加商家用户", response = ApiResult.class)
    public ApiResult<Boolean> addMerchantUser(@Validated(Add.class) @RequestBody MerchantUserAddParam merchantUserAddParam) throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();

        MerchantUser merchantUser = new MerchantUser();
        BeanUtils.copyProperties(merchantUserAddParam, merchantUser);
        merchantUser.setMcId(jwtToken.getMcId());

        // 生成盐值
        String salt = null;
        String password = merchantUserAddParam.getPassword();
        // 如果密码为空，则设置默认密码
        if (StringUtils.isBlank(password)) {
            salt = springBootPlusProperties.getLoginInitSalt();
            password = springBootPlusProperties.getLoginInitPassword();
        } else {
            salt = SaltUtil.generateSalt();
        }
        // 密码加密
        merchantUser.setSalt(salt);
        merchantUser.setPassword(PasswordUtil.encrypt(password, salt));
        merchantUser.setIsAdmin(0);

        boolean flag = merchantUserService.saveMerchantUser(merchantUser);
        return ApiResult.result(flag);
    }

    /**
     * 修改商家用户
     */
    @PostMapping("/update")
    @OperationLog(name = "修改商家用户", type = OperationLogType.UPDATE)
    @ApiOperation(value = "修改商家用户", response = ApiResult.class)
    public ApiResult<Boolean> updateMerchantUser(@Validated(Update.class) @RequestBody MerchantUserUpdateParam merchantUserUpdateParam) throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();

        MerchantUser sysUser = new MerchantUser().setUsername(merchantUserUpdateParam.getUsername());
        MerchantUser one = merchantUserService.getOne(new QueryWrapper<MerchantUser>(sysUser));

        MerchantUser merchantUser = new MerchantUser();
        BeanUtils.copyProperties(merchantUserUpdateParam, merchantUser);
        merchantUser.setMcId(jwtToken.getMcId());
        merchantUser.setId(one.getId());
        // 生成盐值
        String salt = null;
        String password = merchantUserUpdateParam.getPassword();
        // 如果密码为空，则设置默认密码
        if (StringUtils.isBlank(password)) {
            salt = springBootPlusProperties.getLoginInitSalt();
            password = springBootPlusProperties.getLoginInitPassword();
        } else {
            salt = SaltUtil.generateSalt();
        }
        // 密码加密
        merchantUser.setSalt(salt);
        merchantUser.setPassword(PasswordUtil.encrypt(password, salt));
        boolean flag = merchantUserService.updateMerchantUser(merchantUser);
        return ApiResult.result(flag);
    }

    /**
     * 删除商家用户
     */
    @PostMapping("/delete/{id}")
    @OperationLog(name = "删除商家用户", type = OperationLogType.DELETE)
    @ApiOperation(value = "删除商家用户", response = ApiResult.class)
    public ApiResult<Boolean> deleteMerchantUser(@PathVariable("id") Long id) throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        boolean flag = merchantUserService.deleteMerchantUser(id);
        return ApiResult.result(flag);
    }

    /**
     * 获取商家用户详情
     */
    @GetMapping("/info/{id}")
    @OperationLog(name = "商家用户详情", type = OperationLogType.INFO)
    @ApiOperation(value = "商家用户详情", response = MerchantUserQueryVo.class)
    public ApiResult<MerchantUserQueryVo> getMerchantUser(@PathVariable("id") Long id) throws Exception {
        MerchantUserQueryVo merchantUserQueryVo = merchantUserService.getMerchantUserById(id);
        return ApiResult.ok(merchantUserQueryVo);
    }

    /**
     * 商家用户分页列表
     */
    @PostMapping("/getPageList")
    @OperationLog(name = "商家用户分页列表", type = OperationLogType.PAGE)
    @ApiOperation(value = "商家用户分页列表")
    public ApiResult<List<MerchantUserQueryVo>> getMerchantUserPageList() throws Exception {
        JwtToken jwtToken = (JwtToken) SecurityUtils.getSubject().getPrincipal();
        List<MerchantUserQueryVo> merchantUserListByMcId = merchantUserService.getMerchantUserListByMcId(jwtToken.getMcId());
        return ApiResult.ok(merchantUserListByMcId);
    }

}

