package com.dcsoft.system.service.impl;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;

import com.dcsoft.system.utils.BackupConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dcsoft.common.core.constant.CacheConstants;
import com.dcsoft.common.core.constant.UserConstants;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.text.Convert;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.redis.service.RedisService;
import com.dcsoft.system.domain.SysConfig;
import com.dcsoft.system.mapper.SysConfigMapper;
import com.dcsoft.system.service.ISysConfigService;

/**
 * 参数配置 服务层实现
 *
 * @author dcsoft
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService
{
    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private BackupConfig backupConfig;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Long configId)
    {
        SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey)
    {
        String configValue = Convert.toStr(redisService.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            redisService.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config)
    {
        return configMapper.selectConfigList(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config)
    {
        int row = configMapper.insertConfig(config);
        if (row > 0)
        {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config)
    {
        SysConfig temp = configMapper.selectConfigById(config.getConfigId());
        if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey()))
        {
            redisService.deleteObject(getCacheKey(temp.getConfigKey()));
        }

        int row = configMapper.updateConfig(config);
        if (row > 0)
        {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds)
    {
        for (Long configId : configIds)
        {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
            {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            configMapper.deleteConfigById(configId);
            redisService.deleteObject(getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        List<SysConfig> configsList = configMapper.selectConfigList(new SysConfig());
        for (SysConfig config : configsList)
        {
            redisService.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache()
    {
        Collection<String> keys = redisService.keys(CacheConstants.SYS_CONFIG_KEY + "*");
        redisService.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache()
    {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config)
    {
        Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey());
        if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

    /**
     * 备份数据库数据数据
     */
    @Override
    public void backUp()
    {
        File file = new File(backupConfig.getBackupPath());
        if (!file.exists()) {
            file.mkdirs();
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = backupConfig.getBackupPath() + "/"  + sdf.format(new Date()) + ".sql";
        /** 默认使用linux*/
        String c1 = "/bin/sh";
        String c2 = "-c";
        String os_name = System.getProperty("os.name");
        // 判断是否是windows系统
        if (os_name.toLowerCase().startsWith("win")){
            c1 = "cmd";
            c2 = "/c";
        }
        //参考示例：# /usr/local/mysql/bin/mysqldump -uroot -p123456 -P3306 shuju > shuju.sql
        String cmd = backupConfig.getMysqldumpPath()  // mysqldump的绝对路径，配置环境变量，直接写mysqldump即可
                + " -u" + backupConfig.getUsername()  // 数据库用户名
                + " -p" + backupConfig.getPassword()  // 数据库密码
                + " -P" + backupConfig.getPort()      // 数据库端口号
                + " " + backupConfig.getDbName()      // 数据库名
                + " > " + fileName;                   // 最终写入的文件路径
        try {
            System.out.println("第一个参数 " + c1);
            System.out.println("第二个参数 " + c2);
            System.out.println("具体命令 " + cmd);

            System.out.println("数据库备份START" + LocalDateTime.now());
            /**
             * exec重载方法有一个参数的，window下执行正常，linux下无法完成备份。
             * 使用多参数重载方法都可以正常备份
             */
            Process process = Runtime.getRuntime().exec(new String[]{c1, c2, cmd});
            process.waitFor();
            System.out.println("数据库备份END" + LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库备份失败:{}"+ e.getMessage());
        }

    }

    /**
     * @param filepath 数据库备份的脚本路径
     * @return
     */
    public  boolean recover(String filepath) {

        /** 默认使用linux*/
        String c1 = "/bin/sh";
        String c2 = "-c";
        String os_name = System.getProperty("os.name");
        // 判断是否是windows系统
        if (os_name.toLowerCase().startsWith("win")){
            c1 = "cmd";
            c2 = "/c";
        }

        String fileName = backupConfig.getBackupPath() + "/"  + filepath;
        String stmt2 =
                backupConfig.getMysqlPath()
                +" -u "+backupConfig.getUsername()
                +" -p" + backupConfig.getPassword()  // 数据库密码
                +" -P" + backupConfig.getPort()      // 数据库端口号
                +" "+backupConfig.getDbName()
                +" < " + fileName;
        String[] cmd = { c1, c2, stmt2 };
        System.out.println("具体命令 " + stmt2);
        System.out.println("数据库还原START" + LocalDateTime.now());
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            process.waitFor();
            System.out.println("数据已从 " + filepath + " 导入到数据库中");
            System.out.println("数据库还原END" + LocalDateTime.now());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }

    @Override
    public List<String> listFile() {
        List<String> list=new ArrayList<>();
        String path=backupConfig.getBackupPath();
        File file1 = new File(path);
        if (file1.exists()) {
            File[] files = file1.listFiles();
            for (File file2:files){
                String sql= String.valueOf(file2.toPath());
                String resultImage =sql.substring(sql.length()-18,sql.length());
                list.add(resultImage);
            }
        }
        return list;
    }


}
