<template>
  <div class="app-container">
    <el-alert
      title="将文本转换为类似C的文字，转义换行符，制表符，双引号和反斜杠。"
      type="success"
    ></el-alert>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <h5>请输入要转换的文本：</h5>
        <el-input
          type="textarea"
          :autosize="{ minRows: 30, maxRows: 50 }"
          resize="none"
          placeholder="请输入内容"
          v-model="inputString"
        ></el-input>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <h5>转换结果：</h5>
        <el-input
          type="textarea"
          :autosize="{ minRows: 30, maxRows: 50 }"
          resize="none"
          placeholder="转换结果"
          v-model="outputString"
        ></el-input>
      </el-col>
    </el-row>
    <div style="margin: 10px 0px">
      <el-form>
        <el-form-item>
          <el-button type="primary" @click="getConvertString">转换</el-button>
          <el-button type="success" @click="downloadFile">下载</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getConvertString } from "@/api/app-store";

export default {
  name: "AppTool",
  data() {
    return {
      inputString: null,
      outputString: null,
      filename: "app.js",
    };
  },
  methods: {
    createFile(content, filename) {
      const a = document.createElement("a");
      const blob = new Blob([content]);
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    },
    downloadFile() {
      if (!this.inputString) return this.$message.error("输入内容不能为空");

      this.$prompt("请输入文件名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: this.filename,
        inputErrorMessage: "文件名格式不正确",
      })
        .then(({ value }) => {
          if (value) this.filename = value;
          this.createFile(this.outputString, this.filename);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    getConvertString() {
      getConvertString({ string: this.inputString })
        .then((res) => {
          this.outputString = res.data;
          this.$message.success(res.message);
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
  },
  mounted() {},
  created() {},
};
</script>
<style lang="scss" scoped>
.app-container {
  & > div.page-wrapper {
    margin: 10px 0px;
  }
}
</style>
