<template>
  <div
    :class="['creadDocument', language_type == 'AR' ? 'text_right' : '']"
    v-loading="loading"
    v-if="isData"
  >
    <Header />
    <!-- 创建文档 -->
    <Nav :title="$t('Key551')" />
    <div class="title">
      <div>
        <!-- 创建文档 -->
        {{ $t("Key551") }}
      </div>
      <div class="btn">
        <!-- 完成 -->
        <el-button @click="submit('form')" style="width: 180px" type="primary">{{
          $t("Key82")
        }}</el-button>

        <el-button @click="preview" style="width: 180px" type="warning">
          <!-- 预览 -->{{ $t("Key144") }}
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="from">
        <!-- 基本信息的form表单 -->
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="180px"
          :show-message="false"
        >
          <!-- 文档 -->
          <el-form-item :label="$t('Key225')" prop="name">
            <!-- 请输入文档名称 -->
            <el-input
              v-model="form.name"
              style="width: 500px"
              :placeholder="$t('Key552')"
              @change="form.name = form.name.trim()"
              maxlength="50"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!-- 作者 -->
          <el-form-item :label="$t('Key227')" prop="author">
            <!-- 多个作者请用逗号隔开 -->
            <el-input
              v-model="form.author"
              style="width: 500px"
              :placeholder="$t('Key553')"
              @change="authorChange"
              maxlength="20"
              show-word-limit
            ></el-input>
          </el-form-item>
          <!-- 定价 -->
          <el-form-item :label="$t('Key135')" prop="price">
            <el-input
              v-model="form.price"
              style="width: 500px"
              :placeholder="$t('Key138')"
              @input="priceInput"
              @blur="priceBlur"
            >
              <template slot="prepend">¥</template>
            </el-input>
          </el-form-item>
          <!-- 所属机构 -->
          <el-form-item :label="$t('Key136')" prop="institutionID">
            <el-select
              v-model="form.institutionID"
              style="width: 500px"
              :placeholder="$t('Key139')"
            >
              <el-option
                v-for="item in institutionList"
                :key="item.id"
                :label="item.tenantName"
                :value="item.tenantId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 下载 -->
          <el-form-item :label="$t('Key242')" prop="download">
            <el-radio-group v-model="form.download">
              <el-radio label="downloadable"> <!-- 开启 -->{{ $t("Key245") }} </el-radio>
              <el-radio label="0"> <!-- 关闭 -->{{ $t("Key246") }} </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 分类 -->
          <el-form-item :label="$t('Key243')" prop="classify">
            <el-radio-group v-model="form.classify">
              <el-radio label="TEXTBOOK"> <!-- 教辅资料 -->{{ $t("Key554") }}</el-radio>
              <el-radio label="TEACHING"> <!-- 教研资料 -->{{ $t("Key214") }} </el-radio>
              <el-radio label="TOOLBOOK">
                <!-- 工具书 -->
                {{ $t("Key555") }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 文档 -->
          <el-form-item :label="$t('Key244')" prop="file">
            <Upload
              :accept="'.doc,.docx,.xls,.xlsx,.pdf,.ppt,.pptx'"
              :fileList="form.fileList"
              :changeFillId="changeFillId"
              :filleNumber="1"
            >
            </Upload>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header";
import Nav from "@/components/teacher-devEntering/Nav";
import Upload from "@/components/Upload";
import { mapGetters } from "vuex";
import { updateWordPack } from "@/utils/i18n";
import {
  materialdetail,
  attachmentinsert,
  materialinsert,
  materialupdate,
  usertenant,
} from "@/api/api";
export default {
  name: "creadDocument",
  components: {
    Header,
    Nav,
    Upload,
  },
  data() {
    return {
      isData: false,
      form: {
        name: "",
        author: "",
        price: "",
        download: "downloadable",
        classify: "TEXTBOOK",
        fileList: [],
        file: null,
        institutionID: null, //当前机构id
      },
      authorList: null,

      loading: false,
      rules: {
        name: [{ required: true }],
        price: [{ required: true }],
        author: [{ required: true }],
        institutionID: [{ required: true }],
      },
      isSubmit: false, //是更新还是插入
      materialId: null, //学习资料id
      institutionList: null, //机构列表
    };
  },
  computed: {
    ...mapGetters(["language_type"]),
  },
  methods: {
    priceInput(e) {
      this.form.price = this.form.price.match(/^\d*(\.?\d{0,2})/g)[0] || "";
    },
    // 处理教材价格 失去焦点保留两位小数
    priceBlur() {
      if (this.form.price) this.form.price = Number(this.form.price).toFixed(2);
    },

    // 预览
    preview() {
      if (!this.isSubmit) {
        this.$message.warning(this.$t("Key556")); //"请先保存再预览"
        return;
      }
      const { href } = this.$router.resolve({
        path: "Preview",
        query: {
          id: this.materialId,
          type: "preview",
        },
      });
      window.open(href, "_blank");
    },
    // 处理作者数据
    authorChange() {
      this.form.author = this.form.author.trim();
      let index1 = this.form.author.indexOf(",");
      let index2 = this.form.author.indexOf("，");
      let newauthorList = []; //处理之后的老师
      if (index1 != -1) {
        let arr = this.form.author.split(",");
        arr.forEach((item) => {
          newauthorList.push(item);
        });
      } else if (index2 != -1) {
        let arr = this.form.author.split("，");
        arr.forEach((item) => {
          newauthorList.push(item);
        });
      } else {
        newauthorList.push(this.form.author);
      }
      this.authorList = newauthorList;
    },
    changeFillId(file, fileList) {
      let fileList1 = JSON.parse(JSON.stringify(fileList));
      this.form.fileList = fileList1;
    },
    // 完成
    submit(formName) {
      this.loading = true;
      let flag = false;
      this.$refs[formName].validate((valid) => {
        if (valid) {
        } else {
          flag = true;
          return false;
        }
      });
      if (flag) {
        this.$message.warning(this.$t("Key605")); //"请填写完整"
        this.loading = false;
        return;
      }
      if ((this.form.price * 1).toString() == "NaN") {
        this.$message.warning(this.$t("Key557")); //"价格必须为数字"
        this.loading = false;
        return;
      }
      if (this.form.fileList.length == 0) {
        this.$message.warning(this.$t("Key558")); // "请上传文件"
        this.loading = false;
        return;
      }
      // 处理上传附件的数据
      let attachmentList = [];
      let fileType = "";
      this.form.fileList.forEach((item) => {
        let type = item.name.split(".")[1];
        if (item.response) {
          attachmentList.push({
            name: item.name,
            fileId: item.response.file_info_list[0].file_id,
            fileType: type,
          });
          fileType = type;
        } else {
          attachmentList.push({
            name: item.name,
            fileId: item.fileId,
            fileType: item.fileType,
          });
          fileType = item.fileType;
        }
      });
      let tag = null;
      if (this.form.download == "downloadable") {
        tag = ["downloadable", `${this.form.classify}`, fileType];
      } else {
        tag = [`${this.form.classify}`, fileType];
      }
      if (!this.isSubmit) {
        //  插入接口   北语机构id 2021052017-HFTZIRVKWOWPAUU
        // 首先上传附件获取文件对应id
        attachmentinsert({
          attachmentList: attachmentList,
          type: "3",
          tenantId: this.form.institutionID,
        })
          .then((res) => {
            console.log(res);
            // 保存
            materialinsert({
              name: this.form.name,
              price: this.form.price,
              teacherList: this.authorList,
              tenantId: this.form.institutionID,
              tagList: tag,
              attachmentIdList: res.data.attachmentIdList,
            })
              .then((ress) => {
                this.materialId = ress.data.materialId;
                this.isSubmit = true;
                this.loading = false;
                this.$message({
                  type: "success",
                  message: ress.msg,
                });
                this.$router.replace({
                  path: "/creadDocument",
                  query: {
                    materialId: this.materialId,
                  },
                });
              })
              .catch((res) => {
                this.loading = false;
              });
          })
          .catch((res) => {
            this.loading = false;
          });
      } else {
        console.log("走更新接口");
        attachmentinsert({
          attachmentList: attachmentList,
          type: "3",
          tenantId: this.form.institutionID,
        })
          .then((res) => {
            materialupdate({
              id: this.materialId,
              name: this.form.name,
              price: this.form.price,
              teacherList: this.authorList,
              tenantId: this.form.institutionID,
              tagList: tag,
              attachmentIdList: res.data.attachmentIdList,
            })
              .then((ress) => {
                this.loading = false;
                this.$message({
                  type: "success",
                  message: ress.msg,
                });
                this.getdetail();
              })
              .catch((res) => {
                this.loading = false;
              });
          })
          .catch((res) => {
            this.loading = false;
          });
      }
    },
    // 查询详情
    getdetail() {
      this.loading = true;
      materialdetail({
        materialId: this.materialId,
        isSelectForUpdate: true,
      })
        .then((res) => {
          if (res.data.result.status == 4) {
            this.$router.push("/teacherdevEntering");
            // "此课程处于上架状态不可以进行编辑"
            this.$message.warning(this.$t("Key559"));
            return;
          }
          for (let key in this.form) {
            this.form[key] = res.data.result[key];
          }
          this.loading = false;
          this.isSubmit = true;
          this.form.fileList = JSON.parse(res.data.result.attachment);
          this.form.author = "";
          this.form.institutionID = res.data.result.tenantId;
          res.data.result.teacher.forEach((item, i) => {
            if (i == res.data.result.teacher.length - 1) {
              this.form.author += item;
            } else {
              this.form.author += item + ",";
            }
          });
          let index = res.data.result.tag.indexOf("downloadable");
          if (index != -1) {
            this.form.download = res.data.result.tag[0];
            this.form.classify = res.data.result.tag[1];
          } else {
            this.form.download = "0";
            this.form.classify = res.data.result.tag[0];
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
  },
  async created() {
    await updateWordPack({
      word_key_list: [
        "Key5",
        "Key8",
        "Key9",
        "Key39",
        "Key83",
        "Key114",
        "Key135",
        "Key136",
        "Key138",
        "Key139",
        "Key144",
        "Key152",
        "Key214",
        "Key225",
        "Key227",
        "Key242",
        "Key243",
        "Key244",
        "Key245",
        "Key246",
        "Key82",
        "Key551",
        "Key552",
        "Key553",
        "Key554",
        "Key555",
        "Key556",
        "Key557",
        "Key558",
        "Key559",
        "Key605",
      ],
    });
    this.isData = true;
    this.loading = true;
    this.materialId = this.$route.query.materialId;
    if (this.materialId) {
      this.getdetail();
    }
    usertenant({})
      .then((res) => {
        if (res.status == 1) {
          this.institutionList = res.data.tenantIdAndNameListEditable;
          this.loading = false;
        }
      })
      .catch((res) => {
        this.loading = false;
      });
  },
  mounted() {},
};
</script>

<style lang="scss" scoped>
.creadDocument {
  height: 100%;
  .title {
    display: flex;
    justify-content: space-between;
    height: 100px;
    background: #f3f7fa;
    line-height: 80px;
    padding-left: 40px;
    padding-right: 40px;
    font-size: 32px;
  }
  .content {
    height: 100%;
    display: flex;
    .from {
      width: 100%;
      padding: 50px 20px;
      // max-width: 753px;
    }

    .addclass {
      width: 500px;
      height: 300px;
      border: 1px solid black;
      ul {
        list-style: none;
      }
      padding-left: 20px;
    }
  }
}
</style>
<style lang="scss">
.content {
  .el-form-item__label {
    font-size: 16px;
    color: #000000;
  }
  .el-upload-list__item-name {
    margin-left: 50px;
  }
  .el-form-item__error {
    margin-left: 50px;
  }
}
.text_right {
  .el-form-item {
    display: flex;
    .el-form-item__label {
      float: none;
    }
  }
}
</style>
