package cn.iocoder.yudao.module.tkdata.service.employeehosts;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.tkdata.controller.admin.employeehosts.vo.CompletedRateVO;
import cn.iocoder.yudao.module.tkdata.controller.admin.employeehosts.vo.EmployeeHostsPageReqVO;
import cn.iocoder.yudao.module.tkdata.controller.admin.employeehosts.vo.EmployeeHostsSaveReqVO;
import cn.iocoder.yudao.module.tkdata.dal.dataobject.employeehosts.EmployeeHostsDO;
import cn.iocoder.yudao.module.tkdata.dal.dataobject.newhosts.NewHostsDO;
import cn.iocoder.yudao.module.tkdata.dal.mysql.employeehosts.EmployeeHostsMapper;
import cn.iocoder.yudao.module.tkdata.dal.mysql.newhosts.NewHostsMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.tkdata.enums.ErrorCodeConstants.EMPLOYEE_HOSTS_NOT_EXISTS;


/**
 * 员工分配主播表，结构和主播表相同，多了user_id 字段来区分所属员工 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class EmployeeHostsServiceImpl implements EmployeeHostsService {

    @Resource
    private EmployeeHostsMapper employeeHostsMapper;

    @Resource
    private NewHostsMapper newHostsMapper;

    @Override
    public Long createEmployeeHosts(EmployeeHostsSaveReqVO createReqVO) {
        // 插入
        EmployeeHostsDO employeeHosts = BeanUtils.toBean(createReqVO, EmployeeHostsDO.class);
        employeeHostsMapper.insert(employeeHosts);
        // 返回
        return employeeHosts.getId();
    }

    @Override
    public void updateEmployeeHosts(EmployeeHostsSaveReqVO updateReqVO) {
        // 校验存在
        validateEmployeeHostsExists(updateReqVO.getId());
        // 更新
        List<EmployeeHostsDO> employeeHostsDOS = employeeHostsMapper.selectList(new LambdaQueryWrapper<EmployeeHostsDO>()
                .eq(EmployeeHostsDO::getHostsId, updateReqVO.getHostsId())
                .eq(EmployeeHostsDO::getUserId, updateReqVO.getUserId()));
        for (EmployeeHostsDO hostsDO : employeeHostsDOS) {
            hostsDO.setOperationStatus(updateReqVO.getOperationStatus());
            hostsDO.setRemake(updateReqVO.getRemake());
            if (updateReqVO.getFlag() != null) {
                hostsDO.setFlag(updateReqVO.getFlag());
            }
        }
        employeeHostsMapper.updateById(employeeHostsDOS);
    }

    @Override
    public void deleteEmployeeHosts(Long id) {
        // 校验存在
        validateEmployeeHostsExists(id);
        // 删除
        employeeHostsMapper.deleteById(id);
    }

    @Override
    public void deleteEmployeeHostsListByIds(List<Long> ids) {
        // 校验存在
        validateEmployeeHostsExists(ids);
        // 删除
        employeeHostsMapper.deleteByIds(ids);
    }

    private void validateEmployeeHostsExists(List<Long> ids) {
        List<EmployeeHostsDO> list = employeeHostsMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(EMPLOYEE_HOSTS_NOT_EXISTS);
        }
    }

    private void validateEmployeeHostsExists(Long id) {
        if (employeeHostsMapper.selectById(id) == null) {
            throw exception(EMPLOYEE_HOSTS_NOT_EXISTS);
        }
    }

    @Override
    public EmployeeHostsDO getEmployeeHosts(Long id) {
        return employeeHostsMapper.selectById(id);
    }

    @Override
    public PageResult<EmployeeHostsDO> getEmployeeHostsPage(EmployeeHostsPageReqVO pageReqVO) {
        pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        IPage<EmployeeHostsDO> iPage = new Page<>(pageReqVO.getPageNo(),pageReqVO.getPageSize());
        IPage<EmployeeHostsDO> newHostsDOIPage = employeeHostsMapper.selectPageWithXML(iPage, pageReqVO);
        return new  PageResult<>(newHostsDOIPage.getRecords(),newHostsDOIPage.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer allocationHostsEmployee(List<EmployeeHostsSaveReqVO> hostsList) {
        ArrayList<EmployeeHostsDO> employeeHostsDOS = new ArrayList<>();
        ArrayList<NewHostsDO> newHostsDOArrayList = new ArrayList<>();
        for (EmployeeHostsSaveReqVO employeeHostsSaveReqVO : hostsList) {
            NewHostsDO newHostsDO = new NewHostsDO();
            newHostsDO.setId(employeeHostsSaveReqVO.getId());
            newHostsDO.setHostsId(employeeHostsSaveReqVO.getHostsId());
            newHostsDO.setUserId(employeeHostsSaveReqVO.getUserId());
            newHostsDO.setIsAssigned(1);
            newHostsDOArrayList.add(newHostsDO);
            EmployeeHostsDO employeeHostsDO = BeanUtils.toBean(employeeHostsSaveReqVO, EmployeeHostsDO.class);
            employeeHostsDO.setOperationStatus(0);
            employeeHostsDOS.add(employeeHostsDO);
        }
        Long tenantId = TenantContextHolder.getTenantId();
        int i = employeeHostsMapper.batchInsertIgnore(employeeHostsDOS);
        LambdaUpdateWrapper<NewHostsDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        List<String> hostsIds = newHostsDOArrayList.stream()
                .map(NewHostsDO::getHostsId)
                .collect(Collectors.toList());
        int update = newHostsMapper.update(lambdaUpdateWrapper
                .in(NewHostsDO::getHostsId, hostsIds)
                .eq(NewHostsDO::getTenantId, tenantId)
                .set(NewHostsDO::getIsAssigned, 1));
        log.info("修改租户:{}下 {} 个主播分配状态，共更新 {} 条记录", tenantId, hostsIds.size(), update);

//        newHostsMapper.updateBatch(newHostsDOArrayList);
        return i;
    }

    @Override
    public PageResult<EmployeeHostsDO> getEmployeeHostsPageWithSelf(EmployeeHostsPageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        pageReqVO.setTenantId(TenantContextHolder.getTenantId());
        if (loginUser != null) {
            pageReqVO.setUserId(loginUser.getId());
            IPage<EmployeeHostsDO> iPage = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
            IPage<EmployeeHostsDO> newHostsDOIPage = employeeHostsMapper.selectPageWithXMLWithSelf(iPage, pageReqVO);
            return new PageResult<>(newHostsDOIPage.getRecords(), newHostsDOIPage.getTotal());
        }
        return null;
    }

    @Override
    public void batchUpdateEmployeeHosts(List<EmployeeHostsSaveReqVO> updateReqVOList) {

        ArrayList<EmployeeHostsDO> employeeHostsDOS = new ArrayList<>();
        for (EmployeeHostsSaveReqVO employeeHostsSaveReqVO : updateReqVOList) {
            EmployeeHostsDO updateObj = BeanUtils.toBean(employeeHostsSaveReqVO, EmployeeHostsDO.class);
            employeeHostsDOS.add(updateObj);
        }
        employeeHostsMapper.batchUpdate(employeeHostsDOS);
    }

    @Override
    public CompletedRateVO getEmployeeHostsCompleteWithSelf(Long userId) {
        return employeeHostsMapper.selectEmployeeHostsWithOperationStatus(userId);
    }

    @Override
    public List<CompletedRateVO> getEmployeeHostsCompleteBarChart(List<Long> userIdList, Integer days) {

        List<CompletedRateVO> dbList = employeeHostsMapper.selectEmployeeHostsCompleteBarChart(userIdList,days);


        try {
            // 2. 转 Map，key 是 userId
            Map<Long, CompletedRateVO> dbMap = dbList.stream()
                    .collect(Collectors.toMap(
                            CompletedRateVO::getUserId,
                            Function.identity(),
                            (oldVal, newVal) -> newVal)); // 重复时保留新的
            // 3. 组装结果
            return userIdList.stream()
                    .map(userId -> dbMap.getOrDefault(userId, new CompletedRateVO(userId, 0))) // 缺数据补0
                    .collect(Collectors.toList());
        } catch (Exception e) {
            ArrayList<CompletedRateVO> nullData = new ArrayList<>();
            for (Long userId : userIdList) {
                nullData.add(new CompletedRateVO(userId, 0));
            }
            return nullData;
        }





    }


}