package com.fuyuanshen.customer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyuanshen.common.core.domain.model.LoginUser;
import com.fuyuanshen.common.core.enums.UserType;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.mybatis.core.page.TableDataInfo;
import com.fuyuanshen.common.satoken.utils.LoginHelper;
import com.fuyuanshen.customer.constant.ArrayConstants;
import com.fuyuanshen.customer.domain.Customer;
import com.fuyuanshen.customer.domain.query.UserQueryCriteria;
import com.fuyuanshen.customer.domain.vo.ConsumerVo;
import com.fuyuanshen.customer.mapper.CustomerMapper;
import com.fuyuanshen.customer.service.CustomerService;
import com.fuyuanshen.system.domain.SysUserRole;
import com.fuyuanshen.system.mapper.SysRoleMapper;
import com.fuyuanshen.system.mapper.SysUserRoleMapper;
import com.fuyuanshen.system.service.impl.SysUserServiceImpl;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * @author: 默苍璃
 * @date: 2025-07-0114:31
 */
@Service
@RequiredArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    private final CustomerMapper customerMapper;
    private final SysUserServiceImpl userService;
    private final SysRoleMapper roleMapper;
    private final SysUserRoleMapper userRoleMapper;


    /**
     * 分页查询客户
     *
     * @param criteria
     * @param page
     * @return
     */
    @Override
    public TableDataInfo<ConsumerVo> queryCustomers(UserQueryCriteria criteria, Page<Customer> page) {
        criteria.setOffset(page.offset());
        criteria.setPid(LoginHelper.getUserId());
        List<Customer> users = customerMapper.findCustomers(criteria);
        List<ConsumerVo> consumerVoList = BeanUtil.copyToList(users, ConsumerVo.class);
        Long total = customerMapper.countCustomers(criteria);
        // return PageUtil.toPage(consumerVoList, total);
        return new TableDataInfo<ConsumerVo>(consumerVoList, total);
    }


    /**
     * 查询所有客户
     *
     * @param criteria
     * @return
     */
    @Override
    public List<Customer> queryAllCustomers(UserQueryCriteria criteria) {
        criteria.setPid(LoginHelper.getUserId());
        List<Customer> users = customerMapper.queryAllCustomers(criteria);
        return users;
    }


    /**
     * 新增客户
     *
     * @param customer /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCustomer(Customer customer) throws BadRequestException {

        LoginUser loginUser = LoginHelper.getLoginUser();

        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        userQueryCriteria.setCustomerName(customer.getUserName());
        List<Customer> customers = customerMapper.queryCustomers(userQueryCriteria);
        if (!customers.isEmpty()) {
            throw new BadRequestException("用户名已存在！！！");
        }
        customer.setUserLevel((byte) (loginUser.getUserLevel() + 1));
        customer.setPid(loginUser.getUserId());
        customer.setStatus("0");
        customer.setUserType(UserType.SYS_USER.getUserType());
        save(customer);

        // 新增用户与角色管理
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(customer.getCustomerId());
        sysUserRole.setRoleId(ArrayConstants.DEFAULT_LONG);
        userRoleMapper.insert(sysUserRole);

    }


    /**
     * 修改客户
     * 不是因为寂寞才想你，只是因为想你才寂寞。
     *
     * @param customer /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustomer(Customer customer) throws Exception {

        // 获取当前会话账号id, 如果未登录，则抛出异常：`NotLoginException`
        Object loginId = StpUtil.getLoginId();

        UserQueryCriteria userQueryCriteria = new UserQueryCriteria();
        if (StringUtils.isNotEmpty(customer.getUserName())) {
            userQueryCriteria.setCustomerName(customer.getUserName());
            List<Customer> customers = customerMapper.queryCustomers(userQueryCriteria);
            if (!customers.isEmpty()) {
                throw new BadRequestException("用户名已存在！！！");
            }
        }

        if (customer.getEnabled()) {
            customer.setStatus("0");
        } else {
            // 强制下线
            // String tokenId = customer.getUserType() + ":" + customer.getCustomerId();
            String tokenId = UserType.SYS_USER.getUserType() + ":" + customer.getCustomerId();
            StpUtil.logout(tokenId);
            // StpUtil.kickout(customer.getCustomerId());
            customer.setStatus("1");
            // 检查目标用户是否有有效的登录状态
            // if (StpUtil.isLogin(customer.getCustomerId())) {
            //     // 用户已登录，可以执行踢出操作
            //     StpUtil.kickout(customer.getCustomerId());
            // } else {
            //     // 用户未登录，无法踢出
            //     System.out.println("目标用户未登录，无法执行踢出操作");
            // }
        }
        saveOrUpdate(customer);
    }


    /**
     * 删除客户
     *
     * @param ids /
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        customerMapper.deleteByIds(ids);
    }


}
