<template>
  <!-- 新建文件ByTemplate对话框（可以新增模板） -->
  <el-dialog
    :title="isShowTemplateRatio ? '新建文档' : '新建模板'"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="520px"
    @close="handleDialogClose"
  >
    <el-form
      class="add-file-form"
      :model="form"
      :rules="formRules"
      ref="addFileForm"
      label-width="100px"
      label-position="top"
    >
      <div class="file">
        <svg-icon icon-class="file_word" style="font-size: 120px"></svg-icon>
      </div>
      <el-form-item
        label="选择新建方式"
        prop="isTemplate"
        v-if="isShowTemplateRatio"
      >
        <el-radio-group v-model="form.isTemplate" size="mini">
          <el-radio :label="IS_NOT_TEMPLATE">新建空白文档</el-radio>
          <el-radio :label="IS_TEMPLATE">从模板导入</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="选择模板"
        prop="templateId"
        v-if="form.isTemplate == IS_TEMPLATE"
        style="width: 100%"
      >
        <el-cascader
          v-model="form.templateId"
          style="width: 100%"
          size="mini"
          v-if="templateList.length > 0"
          placeholder="请选择模板（可搜索）"
          :options="templateList"
          filterable
          :props="{
            value: 'nodeId',
            label: 'label',
          }"
        >
          <template slot-scope="{ node, data }">
            <svg-icon
              style="margin-right: 4px"
              icon-class="dir"
              v-if="data.isDir"
            ></svg-icon>
            <svg-icon
              style="margin-right: 4px"
              icon-class="file_word"
              v-if="!data.isDir"
            ></svg-icon>
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
        <div class="empty" v-else>暂无模板，如要添加请联系管理员</div>
      </el-form-item>
      <el-form-item
        :label="isShowTemplateRatio ? '文档名称' : '模板名称'"
        prop="fileName"
        size="mini"
      >
        <el-input
          v-model="form.fileName"
          placeholder="请输入文件名称"
          autosize
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleDialogClose">取 消</el-button>
      <el-button
        type="primary"
        :loading="sureBtnLoading"
        @click="handleDialogSure('addFileForm')"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { newfile } from "@/api/wps";
import { getTemplateFiletreeByPath } from "@/api/qwFile";
export default {
  name: "AddFileDialog",
  data() {
    return {
      visible: false, //  对话框是否可见
      form: {
        isTemplate: "0", //新建文件的方式，0-新建空白文件 1-从模板导入
        fileName: "",
        templateId: "", //模板ID
      },
      formRules: {
        fileName: [
          { required: true, message: "请输入文件名称", trigger: "blur" },
        ],
        isTemplate: [
          { required: true, message: "请选择新建方式", trigger: "blur" },
        ],
        templateId: [
          { required: true, message: "请选择模板", trigger: "blur" },
        ],
      },
      sureBtnLoading: false,
      templateList: [],
      IS_TEMPLATE: "1",
      IS_NOT_TEMPLATE: "0",
    };
  },
  watch: {
    "form.isTemplate"(value) {
      if (value == this.IS_TEMPLATE) {
        this.loadTemplateList();
      }
    },
  },
  methods: {
    /**
     * 新建文件对话框 | 对话框关闭的回调
     * @description 关闭对话框，重置表单
     */
    handleDialogClose() {
      this.$refs["addFileForm"].resetFields();
      this.visible = false;
      this.callback("cancel");
    },
    /**
     * 新建文件对话框 | 确定按钮点击事件
     * @description 校验表单，校验通过后调用新建文件接口
     * @param {string} formName 表单ref值
     */
    handleDialogSure(formName) {
      this.sureBtnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          let filetype = "w";
          const WORD = ["docx", "doc"]; //暂时只考虑新建word的情况
          // const PDF = ["pdf", "doc"];
          // const EXCEL = ["xlsx", "xls"];
          if (WORD.includes(this.extendName)) {
            filetype = "w";
          }
          const { extendName, filePath } = this;
          const { fileName, isTemplate, templateId } = this.form;
          const params = {
            filetype,
            extendName,
            filePath,
            fileName,
            isTemplate,
            templateId: templateId[0] || "",
          };
          newfile(params)
            .then((res) => {
              this.sureBtnLoading = false;
              if (res.code == 200) {
                this.$message.success("文件创建成功");
                this.$refs[formName].resetFields();
                this.visible = false;
                this.callback("confirm");
              } else {
                this.$message.warning(res.message);
              }
            })
            .catch(() => {
              this.sureBtnLoading = false;
            });
        } else {
          this.sureBtnLoading = false;
          return false;
        }
      });
    },

    async loadTemplateList() {
      // 如果已经加载过了不用再次加载
      if (this.templateList.length > 0) {
        return;
      }
      const params = {
        path: "/模板管理",
      };
      let res = await getTemplateFiletreeByPath(params);
      if (res.code == 200) {
        // 获取根目录下的模板管理下的所有
        this.templateList = res.data.children[0].children;
        this.templateList.forEach((item) => {
          if (!item.isDir && item.children && item.children.length == 0) {
            delete item.children; //刪除没有文件夹的
          }
        });
      }
    },
    // /**
    //  * 新建文件对话框 | 确定按钮点击事件(奇文-已弃用)
    //  * @description 校验表单，校验通过后调用新建文件接口
    //  * @param {string} formName 表单ref值
    //  */
    // handleDialogSure(formName) {
    //   this.sureBtnLoading = true;
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       createOfficeFile({
    //         extendName: this.extendName,
    //         filePath: this.filePath,
    //         fileName: this.form.fileName,
    //       })
    //         .then((res) => {
    //           this.sureBtnLoading = false;
    //           if (res.code == 200) {
    //             this.$message.success("文件创建成功");
    //             this.$refs[formName].resetFields();
    //             this.visible = false;
    //             this.callback("confirm");
    //           } else {
    //             this.$message.warning(res.message);
    //           }
    //         })
    //         .catch(() => {
    //           this.sureBtnLoading = false;
    //         });
    //     } else {
    //       this.sureBtnLoading = false;
    //       return false;
    //     }
    //   });
    // },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.empty {
  display: flex;
  justify-content: center;
  font-size: 14px;
  color: #999;
}
.file{
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
}
</style>
