/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.customer.entity.BizCustomer;
import vip.xiaonuo.biz.modular.customer.enums.BizCustomerAccountEnum;
import vip.xiaonuo.biz.modular.customer.enums.BizCustomerEnum;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerAccountIdParam;
import vip.xiaonuo.biz.modular.goods.entity.BizGoods;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.enums.BizUserStatusEnum;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.customer.entity.BizCustomerAccount;
import vip.xiaonuo.biz.modular.customer.mapper.BizCustomerAccountMapper;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerAccountAddParam;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerAccountPageParam;
import vip.xiaonuo.biz.modular.customer.service.BizCustomerAccountService;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.List;

/**
 * 客户账号Service接口实现类
 *
 * @author sandy
 * @date  2025/04/09 17:00
 **/
@Service
public class BizCustomerAccountServiceImpl extends ServiceImpl<BizCustomerAccountMapper, BizCustomerAccount> implements BizCustomerAccountService {

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private BizUserMapper bizUserMapper;

    @Resource
    private SysUserApi sysUserApi;

    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = "SNOWY_SYS_DEFAULT_PASSWORD";

    @Override
    public Page<BizCustomerAccount> page(BizCustomerAccountPageParam bizCustomerAccountPageParam) {
        QueryWrapper<BizCustomerAccount> queryWrapper = new QueryWrapper<BizCustomerAccount>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCustomerAccountPageParam.getCustomerId())) {
            queryWrapper.lambda().like(BizCustomerAccount::getCustomerId, bizCustomerAccountPageParam.getCustomerId());
        }
        queryWrapper.lambda().eq(BizCustomerAccount::getDeleteFlag, BizCustomerAccountEnum.NOT_DELETE.getValue());
        if(ObjectUtil.isAllNotEmpty(bizCustomerAccountPageParam.getSortField(), bizCustomerAccountPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizCustomerAccountPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizCustomerAccountPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizCustomerAccountPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizCustomerAccount::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizCustomerAccountAddParam bizCustomerAccountAddParam) {
        QueryWrapper<BizCustomerAccount> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizCustomerAccountAddParam.getLoginAccount())){
            queryWrapper.lambda().eq(BizCustomerAccount::getLoginAccount,bizCustomerAccountAddParam.getLoginAccount());
        }
        queryWrapper.lambda().eq(BizCustomerAccount::getDeleteFlag, BizCustomerAccountEnum.NOT_DELETE.getValue());
        long count = this.count(queryWrapper);
        if(count>0){
            throw new CommonException("该客户账号已经存在！");
        }

        BizCustomerAccount bizCustomerAccount = BeanUtil.toBean(bizCustomerAccountAddParam, BizCustomerAccount.class);
        this.save(bizCustomerAccount);

        // 添加客户登录账号
        BizUser bizUser = new BizUser();
        bizUser.setCustomerId(bizCustomerAccountAddParam.getCustomerId());
        bizUser.setName(bizCustomerAccountAddParam.getLoginAccount());
        bizUser.setAccount(bizCustomerAccountAddParam.getLoginAccount());
        bizUser.setUserType("1");
        // 设置密码
        bizUser.setPassword(CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY)));
        // 设置状态
        bizUser.setUserStatus(BizUserStatusEnum.ENABLE.getValue());
        this.bizUserMapper.insert(bizUser);

        // 添加客户角色
        this.sysUserApi.grantRoleType(bizUser.getId(), "客户");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizCustomerAccountIdParam> bizCustomerAccountIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizCustomerAccountIdParamList, BizCustomerAccountIdParam::getId));
    }

    @Override
    public BizCustomerAccount queryEntity(String id) {
        BizCustomerAccount bizCustomerAccount = this.getById(id);
        if(ObjectUtil.isEmpty(bizCustomerAccount)) {
            throw new CommonException("客户账号不存在，id值为：{}", id);
        }
        return bizCustomerAccount;
    }
}
