package com.hs.admin.controller;

import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.PageResult;
import com.hs.admin.base.RabbitMqConstant;
import com.hs.admin.base.Result;
import com.hs.admin.bean.AuthToken;
import com.hs.admin.bean.DataBase;
import com.hs.admin.bean.Jcb;
import com.hs.admin.bean.TableLog;
import com.hs.admin.dao.AuthTokenDao;
import com.hs.admin.dto.JcbDto;
import com.hs.admin.listener.RabbitMqListener;
import com.hs.admin.service.JcbService;
import com.hs.admin.util.DbUtil;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LogUtil;
import com.hs.admin.util.LoginUserUtil;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author xieheng
 */
@RestController
public class JcbController {
    @Resource
    LoginUserUtil loginUserUtil;
    @Resource
    JcbService jcbService;
    @Resource
    RabbitMqListener rabbitMqListener;
    @Resource
    private ApplicationContext applicationContext;

    /**
     * @description: 添加租户/修改
     * @param: jcbDto
     * @return: String
     * @author: XieHeng
     * @date: 2021/5/10 8:49 上午
     */
    @PutMapping(value = "/api/admin/saveJcb")
    public String saveJcb(@RequestBody @Validated JcbDto jcbDto) {
        Result result;
        try {
            loginUserUtil.getLoginUser();
            Jcb jcb = jcbService.saveJcb(jcbDto);
            new Thread(() -> {
                createAndListener(jcbDto.getJcbId());
                //创建table_log
                createTable(jcb);
            }).start();
            result = Result.returnSuccess(null);
        } catch (HsRuntimeException e) {
            LogUtil.error("\n>>>>>saveJcb错误日志:" + e);
            result = Result.returnHsException(e);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("\n>>>>>saveJcb错误日志:" + e);
            result = Result.returnError();
        }
        return JsonUtils.beanToJson(result);
    }

    private void createTable(Jcb jcb) {
        JdbcTemplate jdbcTemplate = DbUtil.getJdbcTemplate(DbUtil.getDataBase(jcb));
        String sql = "if not exists(select null from sysobjects where xtype='u'and name ='table_log')  " +
                "CREATE TABLE  table_log (id INTEGER identity(1,1) NOT NULL PRIMARY KEY, table_name varchar(64) NOT NULL UNIQUE, hs_cloud_last_time DATETIME NOT NULL );";

        jdbcTemplate.execute(sql);
    }

    /**
     * @description:添加队列并监听
     * @author: XieHeng
     * @param: jcbId
     * @return: void
     * @date: 2021/5/30 10:14 上午
     */
    private void createAndListener(String jcbId) {
        String queueName = RabbitMqConstant.JOB_QUEUE + jcbId;
        //创建新的队列
        rabbitMqListener.newQueue(queueName);
        SimpleMessageListenerContainer container = applicationContext.getBean(SimpleMessageListenerContainer.class);
        //将新队列进行监听
        container.addQueueNames(queueName);
    }

    /**
     * @description: 删除租户
     * @param: jcbId
     * @return: String
     * @author: XieHeng
     * @date: 2021/5/10 9:02 上午
     */
    @GetMapping(value = "/api/admin/deleteJcb")
    public String delJcb(String jcbId) {
        Result result;
        try {
            loginUserUtil.getLoginUser();
            jcbService.delJcb(jcbId);
            result = Result.returnSuccess();
        } catch (HsRuntimeException e) {
            LogUtil.error("\n>>>>>deleteJcb错误日志:" + e);
            result = Result.returnHsException(e);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("\n>>>>>deleteJcb错误日志:" + e);
            result = Result.returnError();
        }
        return JsonUtils.beanToJson(result);
    }

    /**
     * @description: 获取租户列表
     * @param: pageNum
     * @param: pageSize
     * @return: String
     * @author: XieHeng
     * @date: 2021/5/10 9:04 上午
     */

    @GetMapping(value = "/api/admin/getJcbList")
    public String getJcbList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
        Result result;
        try {
            loginUserUtil.getLoginUser();
            PageResult<Jcb> pageResult = jcbService.getJcbList(pageNum, pageSize);
            result = Result.returnSuccess(pageResult);
        } catch (HsRuntimeException e) {
            LogUtil.error("\n>>>>>getJcbList错误日志:" + e);
            result = Result.returnHsException(e);
        } catch (Exception e) {e.printStackTrace();
            LogUtil.error("\n>>>>>getJcbList错误日志:" + e);
            result = Result.returnError();
        }
        return JsonUtils.beanToJson(result);
    }

    /**
     * @description: 数据库连接校验
     * @author: XieHeng
     * @param: dataBase
     * @return: String
     * @date: 2021/5/17 2:32 下午
     */
    @PostMapping(value = "/api/admin/checkDataBase")
    public String checkDb(@RequestBody DataBase dataBase) {
        Result result;
        try {
            loginUserUtil.getLoginUser();
            jcbService.checkDb(dataBase);
            result = Result.returnSuccess(null);
        } catch (HsRuntimeException e) {
            LogUtil.error("\n>>>>>checkDb错误日志:" + e);
            result = Result.returnHsException(e);
        } catch (Exception e) {
            LogUtil.error("\n>>>>>checkDb错误日志:" + e);
            result = Result.returnError();
        }
        return JsonUtils.beanToJson(result);
    }
}
