/*
 * 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.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.customer.enums.BizCustomerEnum;
import vip.xiaonuo.biz.modular.goodsConf.entity.BizGoodsConf;
import vip.xiaonuo.biz.modular.goodsConf.enums.BizGoodsConfEnum;
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.BizCustomer;
import vip.xiaonuo.biz.modular.customer.mapper.BizCustomerMapper;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerAddParam;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerEditParam;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerIdParam;
import vip.xiaonuo.biz.modular.customer.param.BizCustomerPageParam;
import vip.xiaonuo.biz.modular.customer.service.BizCustomerService;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.List;

/**
 * 客户Service接口实现类
 *
 * @author fanzherong
 * @date  2025/03/21 11:44
 **/
@Service
public class BizCustomerServiceImpl extends ServiceImpl<BizCustomerMapper, BizCustomer> implements BizCustomerService {

    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = "SNOWY_SYS_DEFAULT_PASSWORD";

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private BizUserMapper bizUserMapper;

    @Resource
    private SysUserApi sysUserApi;

    @Override
    public Page<BizCustomer> page(BizCustomerPageParam bizCustomerPageParam) {
        QueryWrapper<BizCustomer> queryWrapper = new QueryWrapper<BizCustomer>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getLoginAccount())) {
            queryWrapper.lambda().like(BizCustomer::getLoginAccount, bizCustomerPageParam.getLoginAccount());
        }
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getName())) {
            queryWrapper.lambda().like(BizCustomer::getName, bizCustomerPageParam.getName());
        }
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getPhone())) {
            queryWrapper.lambda().like(BizCustomer::getPhone, bizCustomerPageParam.getPhone());
        }
        queryWrapper.lambda().eq(BizCustomer::getDeleteFlag, BizCustomerEnum.NOT_DELETE.getValue());
        if(ObjectUtil.isAllNotEmpty(bizCustomerPageParam.getSortField(), bizCustomerPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizCustomerPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizCustomerPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizCustomerPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizCustomer::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<BizCustomer> getList(BizCustomerPageParam bizCustomerPageParam) {
        QueryWrapper<BizCustomer> queryWrapper = new QueryWrapper<BizCustomer>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getLoginAccount())) {
            queryWrapper.lambda().like(BizCustomer::getLoginAccount, bizCustomerPageParam.getLoginAccount());
        }
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getName())) {
            queryWrapper.lambda().like(BizCustomer::getName, bizCustomerPageParam.getName());
        }
        if(ObjectUtil.isNotEmpty(bizCustomerPageParam.getPhone())) {
            queryWrapper.lambda().like(BizCustomer::getPhone, bizCustomerPageParam.getPhone());
        }
        queryWrapper.lambda().eq(BizCustomer::getDeleteFlag, BizCustomerEnum.NOT_DELETE.getValue());
        queryWrapper.lambda().orderByAsc(BizCustomer::getId);
        return this.list(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizCustomerAddParam bizCustomerAddParam) {
        //校验手机号格式
        if(ObjectUtil.isNotEmpty(bizCustomerAddParam.getPhone())){
            if(!PhoneUtil.isMobile(bizCustomerAddParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", bizCustomerAddParam.getPhone());
            }
        }
        //查询用友平台ID是否添加过
        long countYong = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getYongId, bizCustomerAddParam.getYongId()));
        if(countYong>0){
            throw new CommonException("客户关联的用友平台ID已存在！");
        }
        //查询客户账号是否添加过
        long countLogin = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getLoginAccount, bizCustomerAddParam.getLoginAccount()));
        if(countLogin>0){
            throw new CommonException("客户账号已存在！");
        }
        //查询客户名称是否添加过
        long countName = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getName, bizCustomerAddParam.getName()));
        if(countName>0){
            throw new CommonException("客户名称已存在！");
        }
        BizCustomer bizCustomer = BeanUtil.toBean(bizCustomerAddParam, BizCustomer.class);
        this.save(bizCustomer);

        // 添加客户登录账号
        BizUser bizUser = new BizUser();
        bizUser.setCustomerId(bizCustomer.getId());
        bizUser.setAccount(bizCustomer.getLoginAccount());
        bizUser.setName(bizCustomer.getName());
        bizUser.setPhone(bizCustomer.getPhone());
        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 edit(BizCustomerEditParam bizCustomerEditParam) {
        //校验手机号格式
        if(ObjectUtil.isNotEmpty(bizCustomerEditParam.getPhone())){
            if(!PhoneUtil.isMobile(bizCustomerEditParam.getPhone())) {
                throw new CommonException("手机号码：{}格式错误", bizCustomerEditParam.getPhone());
            }
        }
        BizCustomer bizCustomer = this.queryEntity(bizCustomerEditParam.getId());
        if(!StringUtils.equals(bizCustomer.getYongId(),bizCustomerEditParam.getYongId())){
            //查询用友平台ID是否添加过
            long countYong = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getYongId, bizCustomerEditParam.getYongId()));
            if(countYong>0){
                throw new CommonException("客户关联的用友平台ID已存在！");
            }
        }
        if(!StringUtils.equals(bizCustomer.getLoginAccount(),bizCustomerEditParam.getLoginAccount())){
            //查询客户账号是否添加过
            long countLogin = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getLoginAccount, bizCustomerEditParam.getLoginAccount()));
            if(countLogin>0){
                throw new CommonException("客户账号已存在！");
            }
        }
        if(!StringUtils.equals(bizCustomer.getName(),bizCustomerEditParam.getName())){
            //查询客户名称是否添加过
            long count = this.count(new QueryWrapper<BizCustomer>().lambda().eq(BizCustomer::getName, bizCustomerEditParam.getName()));
            if(count>0){
                throw new CommonException("客户名称已存在！");
            }
        }
        BeanUtil.copyProperties(bizCustomerEditParam, bizCustomer);
        this.updateById(bizCustomer);

        // 检查是否存在账号
        long count = this.bizUserMapper.selectCount(new QueryWrapper<BizUser>().lambda().eq(BizUser::getCustomerId, bizCustomer.getId()));
        if(count == 0){
            BizUser bizUser = new BizUser();
            bizUser.setCustomerId(bizCustomer.getId());
            bizUser.setAccount(bizCustomer.getLoginAccount());
            bizUser.setName(bizCustomer.getName());
            bizUser.setPhone(bizCustomer.getPhone());
            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<BizCustomerIdParam> bizCustomerIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizCustomerIdParamList, BizCustomerIdParam::getId));
    }

    @Override
    public BizCustomer detail(BizCustomerIdParam bizCustomerIdParam) {
        return this.queryEntity(bizCustomerIdParam.getId());
    }

    @Override
    public void resetPassword(BizCustomerIdParam bizCustomerIdParam) {
        this.bizUserMapper.update(new LambdaUpdateWrapper<BizUser>().eq(BizUser::getCustomerId,
                bizCustomerIdParam.getId()).set(BizUser::getPassword,
                CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY))));
    }

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