package cn.iocoder.foodnexus.module.operations.service.deliverystaff;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
import cn.iocoder.foodnexus.module.infra.api.config.ConfigApi;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.deliverystaffcustomer.DeliveryStaffCustomerDO;
import cn.iocoder.foodnexus.module.operations.dal.mysql.deliverystaffcustomer.DeliveryStaffCustomerMapper;
import cn.iocoder.foodnexus.module.order.api.DeliveryStaffApi;
import cn.iocoder.foodnexus.module.order.dto.DeliveryStaffSimpleInfo;
import cn.iocoder.foodnexus.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.foodnexus.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.foodnexus.module.system.dal.redis.RedisKeyConstants;
import cn.iocoder.foodnexus.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.foodnexus.module.operations.controller.admin.deliverystaff.vo.*;
import cn.iocoder.foodnexus.module.operations.dal.dataobject.deliverystaff.DeliveryStaffDO;
import cn.iocoder.foodnexus.framework.common.pojo.PageResult;
import cn.iocoder.foodnexus.framework.common.util.object.BeanUtils;

import cn.iocoder.foodnexus.module.operations.dal.mysql.deliverystaff.DeliveryStaffMapper;

import static cn.iocoder.foodnexus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.foodnexus.module.operations.enums.ErrorCodeConstants.*;
import static cn.iocoder.foodnexus.module.system.enums.ErrorCodeConstants.USER_IMPORT_INIT_PASSWORD;

/**
 * 配送员信息 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class DeliveryStaffServiceImpl implements DeliveryStaffService, DeliveryStaffApi {

    @Resource
    private DeliveryStaffMapper deliveryStaffMapper;

    @Resource
    private DeliveryStaffCustomerMapper deliveryStaffCustomerMapper;

    @Autowired
    private AdminUserService userService;

    @Autowired
    private ConfigApi configApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDeliveryStaff(DeliveryStaffSaveReqVO createReqVO) {
        validStaff(createReqVO);
        // 插入
        DeliveryStaffDO deliveryStaff = BeanUtils.toBean(createReqVO, DeliveryStaffDO.class);
        String userName = validStaffName(createReqVO.getName(), 1);
        // 新建一个账号
        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        userSaveReqVO.setUsername(userName);
        userSaveReqVO.setNickname(userName);
        userSaveReqVO.setRemark(createReqVO.getRemark());
        // TODO 待定
        userSaveReqVO.setDeptId(100L);
        userSaveReqVO.setMobile(createReqVO.getContact());
        userSaveReqVO.setUserSystem(UserSystemEnum.DELIVERY.getKey());
        String initPassword = configApi.getConfigValueByKey(USER_INIT_PASSWORD_KEY);
        if (StrUtil.isEmpty(initPassword)) {
            throw exception(USER_IMPORT_INIT_PASSWORD);
        }
        userSaveReqVO.setPassword(initPassword);
        Long userId = userService.createUser(userSaveReqVO);

        deliveryStaff.setUserId(userId);
        deliveryStaffMapper.insert(deliveryStaff);

        // 返回
        return deliveryStaff.getId();
    }

    private void validStaff(DeliveryStaffSaveReqVO createReqVO) {
        if (deliveryStaffMapper.exists(Wrappers.<DeliveryStaffDO>lambdaQuery()
                .eq(DeliveryStaffDO::getIdNumber, createReqVO.getIdNumber()))) {
            throw exception(DELIVERY_STAFF_ID_NUMBER_EXISTS);

        }
    }

    private String validStaffName(String name, int suffix) {
        AdminUserDO user = userService.getUserByUsername(name);
        if (CommonUtil.isNotEmpty(user)) {
            return validStaffName(name + suffix, suffix + 1);
        }
        return name;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeliveryStaff(DeliveryStaffSaveReqVO updateReqVO) {
        // 校验存在
        DeliveryStaffDO deliveryStaffDO = validateDeliveryStaffExists(updateReqVO.getId());
        // 更新
        DeliveryStaffDO updateObj = BeanUtils.toBean(updateReqVO, DeliveryStaffDO.class);
        deliveryStaffMapper.updateById(updateObj);

        UserSaveReqVO updateUser = new UserSaveReqVO();
        updateUser.setId(deliveryStaffDO.getUserId());
        // updateUser.setUsername(updateReqVO.getName());
        updateUser.setNickname(updateReqVO.getName());
        updateUser.setRemark(updateReqVO.getRemark());
        updateUser.setMobile(updateReqVO.getContact());
        userService.updateUser(updateUser);
    }

    @Override
    public void deleteDeliveryStaff(Long id) {
        // 校验存在
        validateDeliveryStaffExists(id);
        // 删除
        deliveryStaffMapper.deleteById(id);
    }

    @Override
        public void deleteDeliveryStaffListByIds(List<Long> ids) {
        // 删除
        deliveryStaffMapper.deleteByIds(ids);
        }


    private DeliveryStaffDO validateDeliveryStaffExists(Long id) {
        DeliveryStaffDO deliveryStaffDO = deliveryStaffMapper.selectById(id);
        if (deliveryStaffDO == null) {
            throw exception(DELIVERY_STAFF_NOT_EXISTS);
        }
        return deliveryStaffDO;
    }

    @Override
    public DeliveryStaffDO getDeliveryStaff(Long id) {
        return deliveryStaffMapper.selectById(id);
    }

    @Override
    public PageResult<DeliveryStaffDO> getDeliveryStaffPage(DeliveryStaffPageReqVO pageReqVO) {
        return deliveryStaffMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindCustomer(DeliveryStaffBindCustomerReqVO updateReqVO) {
        validateDeliveryStaffExists(updateReqVO.getStaffId());
        deliveryStaffCustomerMapper.delete(Wrappers.<DeliveryStaffCustomerDO>lambdaQuery()
                .eq(DeliveryStaffCustomerDO::getDeliveryStaffId, updateReqVO.getStaffId())
                .eq(DeliveryStaffCustomerDO::getIsDept, Boolean.FALSE));
        if (CommonUtil.isNotEmpty(updateReqVO.getCustomerIdList())) {
            List<DeliveryStaffCustomerDO> deliveryStaffCustomerDOS = CommonUtil.listConvert(updateReqVO.getCustomerIdList(), customer -> {
                DeliveryStaffCustomerDO deliveryStaffCustomerDO = new DeliveryStaffCustomerDO();
                deliveryStaffCustomerDO.setTargetId(customer);
                deliveryStaffCustomerDO.setIsDept(Boolean.FALSE);
                deliveryStaffCustomerDO.setDeliveryStaffId(updateReqVO.getStaffId());
                return deliveryStaffCustomerDO;
            });
            deliveryStaffCustomerMapper.insertBatch(deliveryStaffCustomerDOS);
        }
    }

    @Override
    public void bindCustomerRelease(DeliveryStaffBindCustomerReqVO updateReqVO) {
        validateDeliveryStaffExists(updateReqVO.getStaffId());
        deliveryStaffCustomerMapper.delete(Wrappers.<DeliveryStaffCustomerDO>lambdaQuery()
                .eq(DeliveryStaffCustomerDO::getDeliveryStaffId, updateReqVO.getStaffId())
                .eq(DeliveryStaffCustomerDO::getIsDept, Boolean.FALSE)
                .in(DeliveryStaffCustomerDO::getTargetId, updateReqVO.getCustomerIdList()));
    }

    @Override
    public DeliveryStaffDO getDeliveryStaffByUserId(Long loginUserId) {
        return deliveryStaffMapper.selectOne(DeliveryStaffDO::getUserId, loginUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void bindDept(DeliveryStaffBindDeptReqVO updateReqVO) {
        validateDeliveryStaffExists(updateReqVO.getStaffId());
        deliveryStaffCustomerMapper.delete(Wrappers.<DeliveryStaffCustomerDO>lambdaQuery()
                .eq(DeliveryStaffCustomerDO::getDeliveryStaffId, updateReqVO.getStaffId())
                .eq(DeliveryStaffCustomerDO::getIsDept, Boolean.TRUE));
        if (CommonUtil.isNotEmpty(updateReqVO.getDeptIdList())) {
            List<DeliveryStaffCustomerDO> deliveryStaffCustomerDOS = CommonUtil.listConvert(updateReqVO.getDeptIdList(), deptId -> {
                DeliveryStaffCustomerDO deliveryStaffCustomerDO = new DeliveryStaffCustomerDO();
                deliveryStaffCustomerDO.setTargetId(deptId);
                deliveryStaffCustomerDO.setIsDept(Boolean.TRUE);
                deliveryStaffCustomerDO.setDeliveryStaffId(updateReqVO.getStaffId());
                return deliveryStaffCustomerDO;
            });
            deliveryStaffCustomerMapper.insertBatch(deliveryStaffCustomerDOS);
        }
    }

    @Override
    public void bindDeptRelease(DeliveryStaffBindDeptReqVO updateReqVO) {
        validateDeliveryStaffExists(updateReqVO.getStaffId());
        deliveryStaffCustomerMapper.delete(Wrappers.<DeliveryStaffCustomerDO>lambdaQuery()
                .eq(DeliveryStaffCustomerDO::getDeliveryStaffId, updateReqVO.getStaffId())
                .eq(DeliveryStaffCustomerDO::getIsDept, Boolean.TRUE)
                .in(DeliveryStaffCustomerDO::getTargetId, updateReqVO.getDeptIdList()));
    }

    @Override
    public String queryNameByStaffId(Long staffId) {
        return Optional.ofNullable(deliveryStaffMapper.selectById(staffId)).map(DeliveryStaffDO::getName).orElse("");
    }

    @Override
    @Cacheable(cacheNames = RedisKeyConstants.USER_ID_TO_DELIVERY_STAFF_ID, key = "#loginUserId")
    public Long queryStaffIdByUserId(Long loginUserId) {
        return Optional.ofNullable(deliveryStaffMapper.selectOne(DeliveryStaffDO::getUserId, loginUserId))
                .map(DeliveryStaffDO::getId).orElse(null);
    }

    @Override
    public DeliveryStaffSimpleInfo querybyStaffId(Long staffId) {
        return BeanUtils.toBean(deliveryStaffMapper.selectById(staffId), DeliveryStaffSimpleInfo.class);
    }

    @Override
    public Map<Long, DeliveryStaffSimpleInfo> getMap(Set<Long> ids) {
        if (CommonUtil.isEmpty(ids)) {
            return new HashMap<>();
        }
        List<DeliveryStaffDO> deliveryStaffDOS = deliveryStaffMapper.selectByIds(ids);
        return CommonUtil.listConvertMap(deliveryStaffDOS, DeliveryStaffDO::getId, staff ->
                new DeliveryStaffSimpleInfo(staff.getId(), staff.getName(), staff.getContact(), staff.getUserId()));
    }
}