package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.common.entity.rest.RestResponse;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.exception.BusinessException;
import cn.hanghui.outapi.platform.common.utils.Preconditions;
import cn.hanghui.outapi.platform.tenant.entity.dto.blacklist.*;
import cn.hanghui.outapi.platform.tenant.entity.enums.DeviceTypeEnum;
import cn.hanghui.outapi.platform.tenant.entity.po.*;
import cn.hanghui.outapi.platform.tenant.mapper.DeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.HhLocalDeviceMapper;
import cn.hanghui.outapi.platform.tenant.mapper.UserBlacklistMapper;
import cn.hanghui.outapi.platform.tenant.mapper.UserBlacklistTaskMapper;
import cn.hanghui.outapi.platform.tenant.service.UserBlacklistService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class UserBlacklistServiceImpl
 * @date 2024/8/29 上午9:51
 * @description
 */
@Slf4j
@Service
public class UserBlacklistServiceImpl implements UserBlacklistService {


    @Resource
    private UserBlacklistTaskMapper userBlacklistTaskMapper;
    @Resource
    private HhLocalDeviceMapper hhLocalDeviceMapper;
    @Resource
    private UserBlacklistMapper userBlacklistMapper;

    @Resource
    private DeviceMapper deviceMapper;

    @Resource
    private CommonImpl commonImpl;

    @Override
    public RestResult<List<String>> importBlacklist(List<Object> datas, String taskName, Long purchaserId) {

        if (Preconditions.isBlank(taskName)) {
            throw new BusinessException("任务名称不能为空");
        }

        if (Preconditions.isBlank(purchaserId)) {
            throw new BusinessException("请选择购买方公司");
        }

        if (Preconditions.isBlank(datas)) {
            throw new BusinessException("请录入黑名单数据");
        }

        UserBlacklistTask task = addBlacklistTask(taskName, purchaserId);

        List<String> list = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            UserBlacklistBean bean = (UserBlacklistBean) datas.get(i);
            try {
                Boolean errorFlag = false;
                StringBuffer err = new StringBuffer("第" + (i + 2) + "行,");
                if (Preconditions.isBlank(bean.getCertName())) {
                    errorFlag = true;
                    err.append("姓名不能为空;");
                }
                if (Preconditions.isBlank(bean.getCertNo()) && Preconditions.isBlank(bean.getPhone())) {
                    errorFlag = true;
                    err.append("身份证和手机号二选一;");
                }
                try {
                    if (!errorFlag) {
                        addBlacklist(task, bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    errorFlag = true;
                    err.append(e.getMessage());
                }
                if (errorFlag) {
                    throw new BusinessException(err.toString());
                }
            } catch (BusinessException e) {
                list.add(e.getMessage());
                continue;
            }
        }
        return RestResponse.ok(list);
    }

    @Override
    public RestResult<IPage<UserBlacklistTaskVo>> page(UserBlacklistTaskSearch dto) {
        LambdaQueryWrapper<UserBlacklistTask> wrapper = this.getTaskWrapper(dto);
        Page<UserBlacklistTask> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<UserBlacklistTask> iPage = userBlacklistTaskMapper.selectPage(page, wrapper);
        Map<Long, Purchaser> purchaserMap = commonImpl.getPurchaserMap(iPage, UserBlacklistTask::getPurchaserId);
        IPage<UserBlacklistTaskVo> convert = iPage.convert(t -> {
            UserBlacklistTaskVo item = BeanUtil.copyProperties(t, UserBlacklistTaskVo.class);
            if (purchaserMap.containsKey(t.getPurchaserId())) {
                item.setPurchaserName(purchaserMap.get(t.getPurchaserId()).getCompanyName());
            }
            return item;
        });
        complete(convert);
        return RestResult.ok(convert);
    }

    @Override
    public RestResult<IPage<UserBlacklistBean>> upage(UserBlacklistSearch dto) {
        LambdaQueryWrapper<UserBlacklist> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.eq(ObjectUtil.isNotNull(dto.getTaskId()), UserBlacklist::getTaskId, dto.getTaskId());
        //基础条件
        wrapper.eq(UserBlacklist::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(UserBlacklist::getId);
        Page<UserBlacklist> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        IPage<UserBlacklist> iPage = userBlacklistMapper.selectPage(page, wrapper);
        IPage<UserBlacklistBean> convert = iPage.convert(t -> {
            UserBlacklistBean item = BeanUtil.copyProperties(t, UserBlacklistBean.class);
            return item;
        });
        return RestResult.ok(convert);
    }

    @Override
    public RestResult<List<UserBlacklistBean>> queryBlacklist(UserBlacklistOpenSearch dto) {
        List<Long> taskIds = getTaskId(dto);
        if (Preconditions.isBlank(taskIds)) {
            return RestResult.ok(null);
        }
        LambdaQueryWrapper<UserBlacklist> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.in(ObjectUtil.isNotNull(taskIds), UserBlacklist::getTaskId, taskIds);
        //基础条件
        wrapper.eq(UserBlacklist::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(UserBlacklist::getId);
        List<UserBlacklist> userBlacklists = userBlacklistMapper.selectList(wrapper);
        List<UserBlacklistBean> userBlacklistBeans = BeanUtil.copyToList(userBlacklists, UserBlacklistBean.class);
        return RestResult.ok(Preconditions.isNotBlank(userBlacklistBeans) ? userBlacklistBeans : ListUtil.empty());
    }

    private List<Long> getTaskId(UserBlacklistOpenSearch dto) {
        List<Long> taskIds = new ArrayList<>();
        int deviceType = Preconditions.isBlank(dto.getDeviceType()) ? DeviceTypeEnum.HH_FACE.getCode() : dto.getDeviceType().intValue();
        switch (deviceType) {
            case 0:
                //通用设备
                taskIds = queryTaskIdByHhFaceSn(dto.getSn());
                break;
            case 1:
                //TODO。。。HH_CULTURE
                break;
            case 2:
                //TODO。。。访客机
                break;
            case 3:
                //TODO。。。临时证明
                break;
            case 4:
                //HHlocal
                taskIds = queryTaskIdByHhLocalSn(dto.getSn());
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + deviceType);
        }
        return taskIds;
    }

    private List<Long> queryTaskIdByHhLocalSn(String sn) {
        HhLocalDevice device = hhLocalDeviceMapper.selectOne(Wrappers.lambdaQuery(HhLocalDevice.class).eq(HhLocalDevice::getSn, sn).eq(HhLocalDevice::getStatus, Boolean.TRUE).isNotNull(HhLocalDevice::getUserBlacklistOfflineTaskId));
        if (Preconditions.isBlank(device)) {
            return null;
        }
        return device.getUserBlacklistOfflineTaskId();
    }

    private List<Long> queryTaskIdByHhFaceSn(String sn) {
        Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getSn, sn).eq(Device::getStatus, Boolean.TRUE).isNotNull(Device::getUserBlacklistOfflineTaskId));
        if (Preconditions.isBlank(device)) {
            return null;
        }
        return device.getUserBlacklistOfflineTaskId();
    }

    @Override
    public RestResult<Boolean> del(Long taskId) {
        UserBlacklistTask task = userBlacklistTaskMapper.selectById(taskId);
        if (Preconditions.isBlank(task) || task.getIsDeleted()) {
            throw new BusinessException("黑名单任务不存在或已删除");
        }
        userBlacklistTaskMapper.deleteById(task);
        List<UserBlacklist> userBlacklists = userBlacklistMapper.selectList(Wrappers.lambdaQuery(UserBlacklist.class).eq(UserBlacklist::getTaskId, taskId));
        if (Preconditions.isBlank(userBlacklists)) {
            return RestResult.ok(Boolean.TRUE);
        }
        List<Long> blacklistIds = userBlacklists.stream().map(UserBlacklist::getId).collect(Collectors.toList());
        userBlacklistMapper.deleteBatchIds(blacklistIds);
        return RestResult.ok(Boolean.TRUE);
    }



    private void complete(IPage<UserBlacklistTaskVo> convert) {
        List<UserBlacklistTaskVo> records = convert.getRecords();
        if (Preconditions.isBlank(records)) {
            return;
        }
        List<Long> taskIds = records.stream().map(UserBlacklistTaskVo::getId).collect(Collectors.toList());
        List<UserBlacklist> userBlacklists = userBlacklistMapper.selectList(Wrappers.lambdaQuery(UserBlacklist.class).in(UserBlacklist::getTaskId, taskIds));
        if (Preconditions.isBlank(userBlacklists)) {
            return;
        }
        Map<Long, List<UserBlacklist>> taskMapList = userBlacklists.stream().collect(Collectors.groupingBy(UserBlacklist::getTaskId));
        records.stream().forEach(item -> {
            if (taskMapList.containsKey(item.getId())) {
                item.setUserBlacklist(BeanUtil.copyToList(taskMapList.get(item.getId()), UserBlacklistBean.class));
            }
        });
        convert.setRecords(records);
    }

    private LambdaQueryWrapper<UserBlacklistTask> getTaskWrapper(UserBlacklistTaskSearch dto) {
        LambdaQueryWrapper<UserBlacklistTask> wrapper = new LambdaQueryWrapper<>();
        //查询的传参条件
        wrapper.like(StrUtil.isNotBlank(dto.getTaskName()), UserBlacklistTask::getTaskName, dto.getTaskName());
        wrapper.eq(ObjectUtil.isNotNull(dto.getPurchaserId()), UserBlacklistTask::getPurchaserId, dto.getPurchaserId());
        wrapper.ge(ObjectUtil.isNotNull(dto.getStartTime()), UserBlacklistTask::getCreateTime, dto.getStartTime());
        wrapper.le(ObjectUtil.isNotNull(dto.getEndTime()), UserBlacklistTask::getCreateTime, dto.getEndTime());
        //基础条件
        wrapper.eq(UserBlacklistTask::getIsDeleted, Boolean.FALSE);
        wrapper.orderByDesc(UserBlacklistTask::getId);
        return wrapper;
    }

    private void addBlacklist(UserBlacklistTask task, UserBlacklistBean bean) {
//        UserBlacklist blacklist = null;
//        if (Preconditions.isNotBlank(bean.getCertNo())) {
//            blacklist = userBlacklistMapper.selectOne(Wrappers.lambdaQuery(UserBlacklist.class).eq(UserBlacklist::getTaskId, task.getId()).eq(UserBlacklist::getCertNo, bean.getCertNo()));
//        }
//        if (Preconditions.isBlank(blacklist) && Preconditions.isNotBlank(bean.getPhone())) {
//            blacklist = userBlacklistMapper.selectOne(Wrappers.lambdaQuery(UserBlacklist.class).eq(UserBlacklist::getTaskId, task.getId()).eq(UserBlacklist::getPhone, bean.getPhone()));
//        }
//        if (Preconditions.isNotBlank(blacklist)) {
//            blacklist.setCertName(bean.getCertName());
//            blacklist.setCertNo(bean.getCertNo());
//            blacklist.setPhone(bean.getPhone());
//            userBlacklistMapper.updateById(blacklist);
//            return;
//        }
        UserBlacklist blacklist = BeanUtil.copyProperties(bean, UserBlacklist.class);
        blacklist.setTaskId(task.getId());
        blacklist.setCreateTime(new Date());
        blacklist.setUpdateTime(new Date());
        blacklist.setIsDeleted(Boolean.FALSE);
        userBlacklistMapper.insert(blacklist);
    }

    private UserBlacklistTask addBlacklistTask(String taskName, Long purchaserId) {
        UserBlacklistTask userBlacklistTask = userBlacklistTaskMapper.selectOne(Wrappers.lambdaQuery(UserBlacklistTask.class).eq(UserBlacklistTask::getPurchaserId, purchaserId).eq(UserBlacklistTask::getTaskName, taskName));
        if (Preconditions.isNotBlank(userBlacklistTask)) {
            throw new BusinessException(String.format("%s任务已存在", taskName));
        }
        userBlacklistTask = new UserBlacklistTask();
        userBlacklistTask.setTaskName(taskName);
        userBlacklistTask.setPurchaserId(purchaserId);
        userBlacklistTask.setCreateTime(new Date());
        userBlacklistTask.setUpdateTime(new Date());
        userBlacklistTask.setIsDeleted(Boolean.FALSE);
        userBlacklistTaskMapper.insert(userBlacklistTask);
        return userBlacklistTask;
    }
    @Override
    public RestResult<List<UserBlacklistTaskLessVo>> list(UserBlacklistTaskListSearch dto) {
        List<UserBlacklistTask> userBlacklistTaskList = userBlacklistTaskMapper.selectList(Wrappers.lambdaQuery(UserBlacklistTask.class).eq(UserBlacklistTask::getPurchaserId, dto.getPurchaserId()));
        return RestResult.ok(userBlacklistTaskList.stream().map(p->new UserBlacklistTaskLessVo(p.getId(),p.getTaskName())).collect(Collectors.toList()));
    }

}
