<template>
  <!-- 新建文件ByTemplate对话框（可以新增模板） -->
  <el-dialog
    title="新建文档"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="550px"
    @close="handleDialogClose"
  >
    <el-form
      class="add-file-form"
      :model="form"
      :rules="formRules"
      ref="addFileForm"
      label-width="100px"
      label-position="top"
    >
      <el-form-item label="选择新建方式" prop="addNewFileWay">
        <el-radio-group v-model="form.addNewFileWay">
          <el-radio label="1">新建空白文档</el-radio>
          <el-radio label="2">从模板导入</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="选择模板"
        prop="template"
        v-if="form.addNewFileWay == 2"
        style="width: 100%"
      >
        <el-select
          v-model="templateId"
          placeholder="请选择"
          v-if="templateList.w_list && templateList.w_list.length > 0"
        >
          <el-option
            v-for="item in templateList.w_list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <div class="empty">暂无模板，如要添加请联系管理员</div>
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="form.fileName"
          placeholder="请输入文件名称"
          type="textarea"
          autosize
          maxlength="255"
          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, getTemplateList } from "@/api/wps";

export default {
  name: "AddFileDialog",
  data() {
    return {
      visible: false, //  对话框是否可见
      form: {
        addNewFileWay: "1", //新建文件的方式，1-新建空白文件 2-从模板导入
        fileName: "",
        templateId: "", //模板ID
      },
      templateList: {}, //模板文件对象，包含p_list（PPT模板）/s_list（表格模板）/w_list（文档模板）三个数组，暂时只用文档模板
      formRules: {
        fileName: [
          { required: true, message: "请输入文件名称", trigger: "blur" },
        ],
      },
      sureBtnLoading: false,
    };
  },
  watch: {
    "form.addNewFileWay"(value) {
      console.log("form.addNewFileWay", this.form.addNewFileWay);
      if (value == 2) {
        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";
          }
          formData.append("filetype", fileType);
          formData.append("extendName", this.extendName);
          formData.append("filePath", this.filePath);
          formData.append("fileName", this.form.fileName);
          newfile(formData)
            .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;
      }
      let res = await getTemplateList();
      if (res.code == 200) {
        this.templateList = res.data;
      }
    },
    // /**
    //  * 新建文件对话框 | 确定按钮点击事件(奇文-已弃用)
    //  * @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;
}
</style>
