package com.friday.custody.service.basicService.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.dao.TablePermissionDao;
import com.friday.custody.entity.TablePermissionEntity;
import com.friday.custody.service.basicService.TablePermissionService;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

@Service("tablePermissionService")
public class TablePermissionServiceImpl extends ServiceImpl<TablePermissionDao, TablePermissionEntity> implements TablePermissionService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TablePermissionEntity> page = this.page(
                new Query<TablePermissionEntity>().getPage(params),
                new QueryWrapper<TablePermissionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public String getServiceNameById(String type) {
        TablePermissionEntity entity = baseMapper.selectById(Integer.valueOf(type));
        if (!Objects.isNull(entity)) {
            return entity.getServiceName();
        }
        return null;
    }

    @Override
    public List<TablePermissionEntity> queryAll(){
        List<TablePermissionEntity> tablePermissionEntities = baseMapper.selectList(new QueryWrapper<>());
        if (!ObjectUtils.isEmpty(tablePermissionEntities)){
            return tablePermissionEntities;
        }
        return null;
    }


    @Override
    public R getDataBySql(String sql) {
        String sqlUpper = sql.toUpperCase(Locale.ROOT);

        //必须以select大小写开头
        int select1 = sqlUpper.indexOf("SELECT");
        if(select1!=0){
            return R.error("请以select开头");
        }

        if(sqlUpper.contains("UPDATE") || sqlUpper.contains("DELETE") || sqlUpper.contains("ALTER") || sqlUpper.contains("TRUNCATE") || sqlUpper.contains("DELIMETER")){
            return R.error("不能含有update,delete,alter,truncate,delimeter 关键字");
        }

        //不能包含update，delete关键字
        List<Map<String, String>> dataBySql = this.baseMapper.getDataBySql(sql);
        if(CollectionUtils.isNotEmpty(dataBySql)){
            String s = JSON.toJSONString(dataBySql);
            return R.ok(s);
        }
        return R.ok("查询数据为空！");

    }
}