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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.iocoder.foodnexus.framework.common.enums.UserSystemEnum;
import cn.iocoder.foodnexus.framework.common.util.CommonUtil;
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.service.dept.DeptService;
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.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.pojo.PageParam;
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.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.foodnexus.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.foodnexus.module.operations.enums.ErrorCodeConstants.*;

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

    @Resource
    private DeliveryStaffMapper deliveryStaffMapper;

    @Resource
    private DeliveryStaffCustomerMapper deliveryStaffCustomerMapper;

    @Autowired
    private AdminUserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createDeliveryStaff(DeliveryStaffSaveReqVO createReqVO) {
        // 插入
        DeliveryStaffDO deliveryStaff = BeanUtils.toBean(createReqVO, DeliveryStaffDO.class);
        // 新建一个账号
        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        userSaveReqVO.setUsername(createReqVO.getName());
        userSaveReqVO.setNickname(createReqVO.getName());
        userSaveReqVO.setRemark(createReqVO.getRemark());
        // TODO 待定
        userSaveReqVO.setDeptId(100L);
        userSaveReqVO.setMobile(createReqVO.getContact());
        userSaveReqVO.setUserSystem(UserSystemEnum.DELIVERY.getKey());
        userSaveReqVO.setPassword("123456");
        Long userId = userService.createUser(userSaveReqVO);

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


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

    @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
    public void bindCustomer(DeliveryStaffBindCustomerReqVO updateReqVO) {
        validateDeliveryStaffExists(updateReqVO.getStaffId());
        deliveryStaffCustomerMapper.delete(DeliveryStaffCustomerDO::getDeliveryStaffId, updateReqVO.getStaffId());
        if (CommonUtil.isNotEmpty(updateReqVO.getCustomerIdList())) {
            List<DeliveryStaffCustomerDO> deliveryStaffCustomerDOS = CommonUtil.listConvert(updateReqVO.getCustomerIdList(), customer -> {
                DeliveryStaffCustomerDO deliveryStaffCustomerDO = new DeliveryStaffCustomerDO();
                deliveryStaffCustomerDO.setCustomerId(customer);
                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())
                .in(DeliveryStaffCustomerDO::getCustomerId, updateReqVO.getCustomerIdList()));
    }

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

    @Override
    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);
    }
}