package com.pwt.web.controller.system;

import com.pwt.StationService;
import com.pwt.cloud.utils.CloudUtil;
import com.pwt.common.annotation.Log;
import com.pwt.common.config.Config;
import com.pwt.common.core.controller.BaseController;
import com.pwt.common.core.domain.AjaxResult;
import com.pwt.common.core.page.TableDataInfo;
import com.pwt.common.enums.BusinessType;
import com.pwt.common.utils.spring.SpringUtils;
import com.pwt.system.domain.PwtConfig;
import com.pwt.system.mapper.PwtConfigMapper;
import com.pwt.system.service.IPwtConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

/**
 * 系统配置Controller
 *
 * @author linyun
 * @date 2022-11-21
 */
@RestController
@RequestMapping("/system/pwtConfig")
public class PwtConfigController extends BaseController {
    @Value("${spring.datasource.druid.master.url}")
    private String url;

    @Value("${spring.datasource.druid.master.username}")
    private String username;

    @Value("${spring.datasource.druid.master.password}")
    private String password;

    @Autowired
    private IPwtConfigService pwtConfigService;

    /**
     * 数据库备份
     *
     * @return
     * @throws FileNotFoundException
     */
    @GetMapping("/dbBackup")
    public AjaxResult dbBackup() throws InterruptedException, IOException {
        String[] split = url.split(":");
        String[] split1 = split[3].split("/");
        String[] split2 = split1[1].split("\\?");
        String dbName = split2[0];
        String fileName = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + ".sql";
        String filePath = Config.getDownloadPath();
        // mysqldump.exe默认安装路径C:\Program Files\MySQL\MySQL Server 8.0\bin
        // 由于Program Files包含空格,导致导出的sql文件为空文件,此处将mysqldump.exe复制到downlod文件夹下
        // dump时加上该路径
        String cmd = filePath + "\\mysqldump -u" + username + " -p" + password + " " + dbName + " > " + filePath + fileName;
        String[] command = {"cmd", "/c", cmd};
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
        String nowTime = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH点mm分ss秒").format(LocalDateTime.now());
        PwtConfigMapper pwtConfigMapper = SpringUtils.getBean(PwtConfigMapper.class);
        PwtConfig pwtConfig = pwtConfigMapper.selectPwtConfigById(1L);
        pwtConfig.setLastBackupTime(nowTime);
        pwtConfigMapper.updatePwtConfig(pwtConfig);
        if (process.exitValue() == 0) {
            return AjaxResult.success(fileName);
        }
        return AjaxResult.error("数据备份失败,请联系管理员");
    }

    /**
     * 查询系统配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:pwtConfig:list')")
    @GetMapping("/list")
    public TableDataInfo list(PwtConfig pwtConfig) {
        startPage();
        List<PwtConfig> list = pwtConfigService.selectPwtConfigList(pwtConfig);
        return getDataTable(list);
    }

    /**
     * 获取系统配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:pwtConfig:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(pwtConfigService.selectPwtConfigById(id));
    }

    @GetMapping(value = "/soc")
    public AjaxResult getMinSOC() {
        PwtConfig pwtConfig = pwtConfigService.selectPwtConfigById(1L);
        PwtConfig newConfig = new PwtConfig();
        newConfig.setChargeSoc(pwtConfig.getChargeSoc());
        return success(newConfig);
    }

    /**
     * 修改系统配置
     */
    @PreAuthorize("@ss.hasPermi('system:pwtConfig:edit')")
    @Log(title = "系统配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PwtConfig pwtConfig) {
        PwtConfig config = pwtConfigService.updatePwtConfig(pwtConfig);
        if (Objects.nonNull(config)) {
            StationService.GET_SOC = config.getChargeSoc().intValue();
            CloudUtil.initPwtConfig();
        }
        return success();
    }

    @PreAuthorize("@ss.hasPermi('system:pwtConfig:changeAutoChangeWarehouse')")
    @Log(title = "系统配置", businessType = BusinessType.UPDATE)
    @PutMapping("changeAutoChangeWarehouse/{id}")
    public AjaxResult changeAutoChangeWarehouse(@Validated @NotNull(message = "id不能为空") @PathVariable("id") Long id, boolean isAutoChangeWarehouse) {
        pwtConfigService.changeAutoChangeWarehouse(id, isAutoChangeWarehouse);
        return success();
    }

}
