<template>
  <div id="problem-detail-body">
    <el-card>
      <template #header>
        <page-header>
          <template #actions>
            <el-button @click="download">
              下载
            </el-button>
            <el-button
                v-if="removeEnable"
              type="danger"
              @click="$store.commit('removeProblem', problem)"
            >移出试题清单
            </el-button
            >
            <el-button
                v-else-if="addEnable"
              type="primary"
              @click="$store.commit('addProblem', problem)"
            >加入试题清单
            </el-button
            >
            <el-button
              type="danger"
              @click="dialog.delete = true"
            >
              删除题目
            </el-button>
          </template>
          {{ problem.name }}
        </page-header>
      </template>

      <paper shadow="sm" style="margin-bottom: 20px">
        <el-descriptions>
          <el-descriptions-item
              label="题目名称:"
              label-class-name="label-bold"
          >
            {{ problem.name }}
          </el-descriptions-item>
          <el-descriptions-item
              label="题目类型:"
              label-class-name="label-bold"
          >
            {{ typeTagContent }}
          </el-descriptions-item>
          <el-descriptions-item
              label="上传者:"
              label-class-name="label-bold"
          >
            {{ problem.creator ? problem.creator.username : "系统" }}
          </el-descriptions-item>
          <el-descriptions-item
              label="上传时间:"
              label-class-name="label-bold"
          >
            {{ formatTimestamp(problem.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item
              :span="3"
              label="题目描述:"
              label-class-name="label-bold"
          >
            {{ problem.description }}
          </el-descriptions-item>
        </el-descriptions>
      </paper>

      <div class="fill-card top-divide">
        <el-table :data="files">
          <el-table-column label="文件列表">
            <template #default="scope">
              <span>{{ scope.row.path }}</span>
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="scope">
              <span>{{ scope.row.type }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button
                size="small"
                type="text"
                @click="onGetDetail(scope.row.path)"
              >
                查看详情
              </el-button>
              <el-button
                size="small"
                type="text"
                @click="onDialogUpdate(scope.row.path)"
              >
                更新文件
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-dialog v-model="dialog.delete" title="确认删除题目">
      <b>确认删除题目吗？</b>
      <p>题目ID：{{ problem.id }}</p>
      <p>题目名称：{{ problem.name }}</p>
      <template #footer>
        <span class="dialog-footer">
        <el-button @click="dialog.delete = false">取消</el-button>
        <el-button
            :loading="loading.delete"
            type="danger"
            @click="deleteProblem"
        >确定</el-button
        >
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialog.update" title="更新题目文件">
      <el-form label-width="40px">
        <el-form-item label="路径" prop="name">
          <div>{{ selectedFile }}</div>
        </el-form-item>
        <el-form-item label="文件" prop="file">
          <el-upload
              ref="file"
              :auto-upload="false"
              :limit="1"
              :on-change="onFileChange"
              :on-remove="onFileChange"
              action=""
          >
            <el-button size="small" type="primary"
            >选取
            </el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
          <el-button @click="cancelUpdate">取消</el-button>
          <el-button
              :disabled="!updateFiles.length"
              :loading="loading.update"
              type="primary"
              @click="onSubmit"
          >确定</el-button
          >
        </span>
      </template>

    </el-dialog>
    <el-dialog
        v-model="fileDetailDialogShow"
        :title="fileDetailName"
        width="80%"
    >
      <pre>{{ fileDetail }}</pre>
    </el-dialog>
  </div>
</template>

<script>
import PageHeader from "./components/PageHeader.vue";
import Paper from "./components/Paper.vue";
import {mapGetters} from "vuex";
import {errorMessage, formatTimestamp, problemTypeToTagContent} from "@/utils/coder-utils";
import {ElMessage} from "element-plus";

export default {
  name: "ProblemDetail",
  layout: "dashboard",
  components: {
    Paper,
    PageHeader,
  },
  data() {
    return {
      problem: {},
      files: [],
      selectedFile: "",
      updateFiles: [],
      dialog: {
        delete: false,
        update: false
      },
      loading: {
        delete: false,
        update: false
      },
      fileDetailDialogShow: false,
      fileDetailName: "",
      fileDetail: ""
    };
  },
  computed: {
    ...mapGetters(["isTeacherGroup"]),
    typeTagContent() {
      return problemTypeToTagContent(this.problem.type);
    },
    removeEnable() {
      return this.$store.state.problem.cart
          .map((item) => item.id)
          .includes(this.problem.id);
    },
    addEnable() {
      return this.isTeacherGroup && this.problem.modifiedAt;
    },
    updateEnable(){
      return true;
      // const user = this.$store.state.user;
      // const creator = this.problem.creator
      // return (
      //     this.problem.modifiedAt &&
      //     (this.isAdmin || (creator && creator.id === user.id))
      // )
    },
    deleteEnable() {
      return (
          this.isAdmin ||
          (this.problem.creator &&
              this.problem.creator.id === this.$store.state.user.id)
      );
    },
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    formatTimestamp,
    fetchData() {
      const { problemId } = this.$route.params;
      this.$apis.getCoderProblemById(problemId)
        .then((_res) => {
          this.problem = _res.data.res ?? {};

          if(!this.problem.id) { // 判断题目是否存在
            this.$message.error({
              message: "当前题目不存在！",
              center: true
            });
            this.$router.push("/manage");
          }

          this.listFiles();
        })
        .catch((_err) => {
          this.$message.error({
            message: "当前题目不存在！",
            center: true
          });
          this.$router.push("/manage");
        });
    },
    listFiles() {
      this.files = [
        ...(this.problem?.publicFiles?.map((item) => ({
          path: item,
          type: "Public"
        })) ?? []),
        ...(this.problem?.protectedFiles?.map((item) => ({
          path: item,
          type: "Protected"
        })) ?? []),
        ...(this.problem?.privateFiles?.map((item) => ({
          path: item,
          type: "Private"
        })) ?? [])
      ];
    },
    download() {
      //直接访问Coder后端获取文件
      const { problemId } = this.$route.params;
      window.open(`https://coder.seec.seecoder.cn/api/file/problem/${problemId}`);
    },

    // 删除Coder代码题
    deleteProblem() {
      this.$store.commit("removeProblem", this.problem); //先从题目购物车cart中移除
      this.loading.delete = true;
      const { problemId } = this.$route.params;

      this.$apis.deleteCoderProblem(problemId)
          .then(_res => {
            ElMessage.success({
              message: "删除代码题成功！",
              center: true
            });
            this.$router.push("/manage");
          }).catch(_err => {
            this.$message.error({
              message: "删除代码题失败！",
              center: true
            });
      });
    },
    onFileChange(
      _,
      fileList
    ) {
      this.updateFiles = fileList;
    },
    onGetDetail(filename) {
      this.fileDetail = "";
      this.fileDetailName = filename;
      this.fileDetailDialogShow = false;

      const { problemId } = this.$route.params;
      this.$apis.getProblemFile(problemId, filename)
        .then((_res) => {
          this.fileDetail = _res.data.res ?? "";
          this.fileDetailDialogShow = true;
        })
        .catch((_err) => {
          this.$message.error({
            message: _err,
            center: true
          });
        });
    },
    cancelUpdate() {
      const file = this.$refs.file;
      file.clearFiles();
      this.updateFiles = [];
      this.dialog.update = false;
    },
    onSubmit() {
      this.loading.update = true;
      const body = new FormData();
      body.append("path", this.selectedFile);
      body.append("file", this.updateFiles[0].raw);
      const { problemId } = this.$route.params;
      this.$apis.updateCoderProblem(problemId, body)
        .then(() => {
          this.$message.success({
            message: "更新成功！",
            center: true
          });
          this.loading.update = false;
          this.dialog.update = false;
        })
        .catch((err) => {
          this.$message.error({
            message: errorMessage(err),
            center: true
          });
          this.loading.update = false;
        });
    },
    onDialogUpdate(path) {
      this.selectedFile = path;
      this.dialog.update = true;
    }
  }
};
</script>

<style lang="scss">
#problem-detail-body {
  margin: 40px 10vw 80px 10vw;
  min-height: calc(100vh - 100px);
}
.label-bold {
  font-weight: bold;
  font-size: 15px;
}
</style>
