package com.zhiqiyun.open.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhiqiyun.open.core.mapper.place.PlaceBaseInfoExtendMapper;
import com.zhiqiyun.open.core.mapper.place.PlaceBaseInfoMapper;
import com.zhiqiyun.open.core.models.place.PlaceBaseInfo;
import com.zhiqiyun.open.core.models.place.PlaceBaseInfoExtend;
import com.zhiqiyun.open.core.service.PlaceBaseInfoService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

@Service
public class PlaceBaseInfoServiceImpl extends ServiceImpl<PlaceBaseInfoMapper, PlaceBaseInfo> implements PlaceBaseInfoService {

    @Autowired
    private PlaceBaseInfoExtendMapper placeBaseInfoExtendMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(PlaceBaseInfo entity, List<PlaceBaseInfoExtend> listExtends) {
        this.baseMapper.insert(entity);
        for (PlaceBaseInfoExtend extend : listExtends) {
            extend.setBaseInfoId(entity.getId());
            extend.setId(DigestUtils.md5Hex(String.format("%s@%s", extend.getBaseInfoId(), extend.getExtendColumnId())));
            this.placeBaseInfoExtendMapper.insert(extend);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlaceBaseInfo entity, List<PlaceBaseInfoExtend> listExtends) {
        this.baseMapper.updateById(entity);

        QueryWrapper<PlaceBaseInfoExtend> wrapper = new QueryWrapper<>();
        wrapper.eq("base_info_id", entity.getId());
        this.placeBaseInfoExtendMapper.delete(wrapper);

        for (PlaceBaseInfoExtend extend : listExtends) {
            extend.setBaseInfoId(entity.getId());
            extend.setId(DigestUtils.md5Hex(String.format("%s@%s", extend.getBaseInfoId(), extend.getExtendColumnId())));
            this.placeBaseInfoExtendMapper.insert(extend);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIds(Collection<? extends Serializable> idList) {

        QueryWrapper<PlaceBaseInfoExtend> wrapper = new QueryWrapper<>();
        wrapper.in("base_info_id", idList);
        this.placeBaseInfoExtendMapper.delete(wrapper);

        return super.removeByIds(idList);
    }
}
