package com.testor.ddd.safetyControl.infrastructure.repository.space.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.constant.StatusEnum;
import com.testor.ddd.safetyControl.domain.space.entity.TSafeSpaceRepo;
import com.testor.ddd.safetyControl.infrastructure.repository.space.dao.TSafeSpaceDao;
import com.testor.ddd.safetyControl.infrastructure.repository.space.entity.TSafeSpaceDO;
import com.testor.ddd.safetyControl.infrastructure.uitls.SpaceLevelEnum;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.space.TSafeSpaceVO;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 空间场所Service业务层处理
 *
 * @author testor-framework
 * @date 2022-06-27 16:56:21
 */
@Service
public class TSafeSpaceServiceImpl extends SuperServiceImpl<TSafeSpaceDao, TSafeSpaceDO>
        implements TSafeSpaceRepo {
    @Autowired(required = false)
    private TSafeSpaceDao tSafeSpaceDao;

    @Override
    public List<TSafeSpaceDTO> checkUniqueness(String id, String bizId, Integer level, String name, String code) {
        String orgId = ContextUtils.getLoginUser().getOrgId();
        LambdaQueryWrapper<TSafeSpaceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSafeSpaceDO::getLevel, level)
                .eq(TSafeSpaceDO::getStatus, BizConstants.STATUS_ENABLE)
                .and(wq -> wq
                        .eq(TSafeSpaceDO::getName, name)
                        .or()
                        .eq(TSafeSpaceDO::getCode, code))
                .eq(TSafeSpaceDO :: getOrgId,orgId);
        if (level == SpaceLevelEnum.workshop.getCode().intValue()) {
            queryWrapper.eq(TSafeSpaceDO::getSpaceTypeId, bizId);
        } else {
            queryWrapper.eq(TSafeSpaceDO::getSpaceId, bizId);
        }
        if (!StrUtil.isBlank(id)) {
            queryWrapper.ne(TSafeSpaceDO::getId, id);
        }
        List<TSafeSpaceDO> spaceDOList = tSafeSpaceDao.selectList(queryWrapper);
        List<TSafeSpaceDTO> spaceDTOList = BeanHelper.listToList(spaceDOList, TSafeSpaceDTO.class);
        return spaceDTOList;
    }

    public int insert(TSafeSpaceDTO spaceDTO) {
        TSafeSpaceDO data = BeanHelper.beanToBean(spaceDTO, TSafeSpaceDO.class);
        return tSafeSpaceDao.insert(data);
    }

    public int updateById(TSafeSpaceDTO spaceDTO) {
        TSafeSpaceDO data = BeanHelper.beanToBean(spaceDTO, TSafeSpaceDO.class);
        return tSafeSpaceDao.updateById(data);
    }

    /**
     * 车间场所分页查询
     *
     * @param param
     * @return
     */
    public BaseResponseList<TSafeSpaceVO> listPageByWorkshop(TSafeSpaceDTOParam param) {
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSafeSpaceVO> resultPage = new Page<>(page, limit);
        IPage<TSafeSpaceVO> iPage = tSafeSpaceDao.listPageByWorkshop(resultPage, param);

        BaseResponseList<TSafeSpaceVO> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(iPage.getRecords());
        baseResponseList.setTotal(iPage.getTotal());
        return baseResponseList;
    }


    /**
     * 作业区域分页查询
     *
     * @param param
     * @return
     */
    public BaseResponseList<TSafeSpaceVO> listPageByWorkArea(TSafeSpaceDTOParam param) {
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSafeSpaceVO> resultPage = new Page<>(page, limit);
        IPage<TSafeSpaceVO> iPage = tSafeSpaceDao.listPageByWorkArea(resultPage, param);

        BaseResponseList<TSafeSpaceVO> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(iPage.getRecords());
        baseResponseList.setTotal(iPage.getTotal());
        return baseResponseList;
    }

    /**
     * 根据编码查询
     *
     * @param code
     * @return
     */
    public List<TSafeSpaceVO> listByCode(String code) {
        if (StrUtil.isBlank(code)) {
            return null;
        }
        List<TSafeSpaceVO> list = tSafeSpaceDao.listByCode(code);
        return list;
    }

    public TSafeSpaceDTO findById(String id) {
        if (StrUtil.isBlank(id)) {
            return null;
        }
        TSafeSpaceDO spaceDo = tSafeSpaceDao.selectById(id);
        if (spaceDo == null) {
            return null;
        }
        TSafeSpaceDTO spaceDTO = BeanHelper.beanToBean(spaceDo, TSafeSpaceDTO.class);
        return spaceDTO;
    }

    public boolean deleteById(String id) {
        UpdateWrapper<TSafeSpaceDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(TSafeSpaceDO::getStatus, BizConstants.STATUS_DELETE)
                .ne(TSafeSpaceDO::getStatus, BizConstants.STATUS_DELETE)
                .and(wq -> wq
                        .eq(TSafeSpaceDO::getId, id)
                        .or()
                        .eq(TSafeSpaceDO::getSpaceId, id));
        return update(updateWrapper);
    }

    public boolean deleteBySpaceTypeId(String spaceTypeId) {
        UpdateWrapper<TSafeSpaceDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(TSafeSpaceDO::getStatus, BizConstants.STATUS_DELETE)
                .ne(TSafeSpaceDO::getStatus, BizConstants.STATUS_DELETE)
                .eq(TSafeSpaceDO::getSpaceTypeId, spaceTypeId);
        return update(updateWrapper);
    }

    public List<TSafeSpaceDTO> listAllEntity(TSafeSpaceDTOParam param) {
        param.setStatus("0");
        QueryWrapper<TSafeSpaceDO> queryWrapper = this.createQuery(param);
        List<TSafeSpaceDO> resultList = list(queryWrapper);
        List<TSafeSpaceDTO> resultDTOList = BeanHelper.listToList(resultList, TSafeSpaceDTO.class);
        return resultDTOList;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSafeSpaceDO> createQuery(TSafeSpaceDTOParam queryParam) {
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TSafeSpaceDO.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getSpaceTypeId())) {
            queryWrapper.eq(TSafeSpaceDO.SPACE_TYPE_ID, queryParam.getSpaceTypeId());
        }
        if (StringHelper.isNotEmpty(queryParam.getSpaceId())) {
            queryWrapper.eq(TSafeSpaceDO.SPACE_ID, queryParam.getSpaceId());
        }
        if (StringHelper.isNotEmpty(queryParam.getName())) {
            queryWrapper.like(TSafeSpaceDO.NAME, queryParam.getName());
        }
        if (StringHelper.isNotEmpty(queryParam.getCode())) {
            queryWrapper.eq(TSafeSpaceDO.CODE, queryParam.getCode());
        }
        if (ObjectHelper.isNotEmpty(queryParam.getLevel())) {
            queryWrapper.eq(TSafeSpaceDO.LEVEL, queryParam.getLevel());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSafeSpaceDO.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSafeSpaceDO.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSafeSpaceDO.UPDATE_DATE);
        }
        return queryWrapper;
    }

    public Integer replaceCode(String spaceTypeId, String oldCode, String newCode) {
        return tSafeSpaceDao.replaceCode(spaceTypeId, oldCode, newCode);
    }

    public boolean saveBatch(List<TSafeSpaceDTO> spaceDTOList) {
        List<TSafeSpaceDO> spaceDOList = BeanHelper.listToList(spaceDTOList, TSafeSpaceDO.class);
        return saveBatch(spaceDOList);
    }

    @Override
    public List<TSafeSpaceDTO> findBySpaceTypeId(String id) {
        if (StrUtil.isBlank(id)) {
            return null;
        }
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("space_type_id", id);
        List<TSafeSpaceDO> spaceDo = tSafeSpaceDao.selectList(queryWrapper);
        List<TSafeSpaceDTO> spaceDTO = new ArrayList<>();
        if (!CollectionUtils.isEmpty(spaceDo)) {
            for (TSafeSpaceDO tSafeSpaceDO : spaceDo) {
                TSafeSpaceDTO tSafeSpaceDTO = BeanHelper.beanToBean(tSafeSpaceDO, TSafeSpaceDTO.class);
                spaceDTO.add(tSafeSpaceDTO);
            }
        }
        return spaceDTO;
    }

    @Override
    public List<TSafeSpaceDO> findSpaceListByTypeIdAndOrgId(String typeId,String orgId){
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("space_type_id", typeId);
        queryWrapper.eq("\"level\"", 1);
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        List<TSafeSpaceDO> spaceDo = tSafeSpaceDao.selectList(queryWrapper);
        return spaceDo;
    }

    @Override
    public List<String> getSpaceTypeIdsByOrgId(String orgId) {
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("space_type_id");
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("\"level\"", 1);
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        queryWrapper.groupBy("space_type_id");
        List<String> spaceTypeIds = tSafeSpaceDao.selectObjs(queryWrapper)
                .stream()
                .filter(obj -> obj != null)
                .map(Object::toString)
                .collect(Collectors.toList());
        return spaceTypeIds;
    }

    @Override
    public List<TSafeSpaceDO> findRegionalListByTypeIdAndOrgId(String spaceId, String orgId) {
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("space_id", spaceId);
        queryWrapper.eq("\"level\"", 2);
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        List<TSafeSpaceDO> spaceDo = tSafeSpaceDao.selectList(queryWrapper);
        return spaceDo;
    }

    @Override
    public TSafeSpaceDTO findBySpaceName(String name, String orgId) {
        if (StrUtil.isBlank(name)) {
            return null;
        }
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", name);
        queryWrapper.eq("\"level\"", 2);
        queryWrapper.eq("org_id", orgId);
        TSafeSpaceDO spaceDo = tSafeSpaceDao.selectOne(queryWrapper);
        TSafeSpaceDTO tSafeSpaceDTO = BeanHelper.beanToBean(spaceDo, TSafeSpaceDTO.class);
        return tSafeSpaceDTO;
    }

    @Override
    public List<TSafeSpaceDO> findAllSpacesByTypeIdsAndOrgId(List<String> spaceTypeIdsByOrgId, String orgId) {
        QueryWrapper<TSafeSpaceDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("space_type_id", spaceTypeIdsByOrgId);
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", StatusEnum.USE.getCode());
        List<TSafeSpaceDO> spaceDo = tSafeSpaceDao.selectList(queryWrapper);
        return spaceDo;
    }

    @Override
    public List<TSafeSpaceVO> listSafeSpaceAll(TSafeSpaceDTOParam param) {
        return tSafeSpaceDao.listSafeSpaceAll(param);
    }
}
