<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="标题"
        style="width: 200px"
        class="filter-item"
      />
      <el-select
        v-model="listQuery.status"
        filterable
        placeholder="状态"
        class="filter-item"
        style="width: 120px"
      >
        <el-option key="" label="请选择" value="" />
        <el-option v-for="(v, k) in statusArr" :key="k" :label="v" :value="k" />
      </el-select>
      <el-button
        class="filter-item search"
        type="primary"
        icon="el-icon-search"
        @click="getList"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus"
        @click="onAdd"
        >添加</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%; padding-bottom: 60px !important"
    >
      <el-table-column align="center" label="ID" width="80" prop="id" />
      <el-table-column
        align="center"
        label="城市"
        width="80"
        prop="qaCitys.city_name"
      />
      <el-table-column
        align="center"
        label="标题"
        width="280"
        style="overflow: hidden"
      >
        <template slot-scope="scope">
          <div class="ellipsis-text">{{ scope.row.title }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="100">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="updateStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" width="220" label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="onAdd(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="onDel(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog
      v-if="dialogCreate"
      ref="dialog"
      :title="title"
      :visible.sync="dialogCreate"
    >
      <div
        style="display: flex; justify-content: flex-end; margin-bottom: 10px"
      >
        <el-button v-loading="loading" type="primary" @click="onSave"
          >保 存</el-button
        >
      </div>
      <el-scrollbar ref="scrollbar" class="scrollable-container">
        <el-form ref="addForm" label-width="120px" :model="anchors">
          <el-form-item label="城市" prop="city_id">
            <el-select v-model="anchors.city_id" placeholder="请选择">
              <el-form-item
                style="display: inline-flex; text-align: left; width: 770px"
              >
                <el-option
                  v-for="item in getQaCitys"
                  :key="item.city_id"
                  style="display: inline-flex; word-break: break-all"
                  :label="item.city_name"
                  :value="item.city_id"
                />
              </el-form-item>
            </el-select>
          </el-form-item>
          <el-form-item label="旅游路线" prop="title">
            <el-input
              v-model="anchors.title"
              type="text"
              placeholder="请输入旅游路线"
            />
          </el-form-item>
          <el-form-item label="QA内容">
            <div
              class="mistake-content"
              v-for="(item, index) in anchors.qaQuestions"
            >
              <div class="mistake-left">
                <div>副标题</div>
                <div class="qa-desc">
                  <el-input
                    style="width: 100px; margin-right: 10px"
                    v-model="item.sort"
                    type="text"
                    placeholder="序号"
                  />
                  <el-input
                    v-model="item.title"
                    type="text"
                    placeholder="请输入副标题"
                  />
                </div>
                <div>内容</div>
                <div style="border: 1px solid #ccc">
                  <myEditor v-model="item.content" />
                </div>
              </div>
              <div class="mistake-right">
                <el-button @click="handleDel(index)" type="danger"
                  >删除</el-button
                >
              </div>
            </div>
            <div class="mistake-btn">
              <el-button type="primary" @click="handleAdd">添加</el-button>
            </div>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="anchors.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <div
            style="
              display: flex;
              justify-content: flex-end;
              margin-bottom: 10px;
            "
          >
            <el-button type="primary" @click="onAddImg()">添加图片</el-button>
          </div>
          <el-form-item label="上传图片">
            <div class="upload-list">
              <div class="wu-yu" v-for="(item, index) in anchors.img_zip">
                <i
                  @click.stop="handleClose('img_zip', index)"
                  class="close el-icon-close"
                />
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :show-file-list="false"
                  :http-request="handlesAvatarSuccess"
                  :on-success="
                    (response, file, fileList) =>
                      handleAvatarSuccess(response, file, fileList, index)
                  "
                >
                  <div v-if="!!item.file" class="img-box">
                    <i
                      v-if="!checkIfUrlContainsImage(item.file)"
                      class="el-icon-folder"
                    />
                    <img
                      v-else
                      style="width: 100px; height: 100px"
                      :src="item.file"
                      class="avatar"
                      alt=""
                    />
                    <div class="desc">{{ handleRegex(item.file) }}</div>
                  </div>
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
                <el-input v-model="item.desc" placeholder="图片说明"></el-input>
              </div>
            </div>
            <div style="color: red">(请上传.jpg, png的图片)</div>
          </el-form-item>
          <div
            style="
              display: flex;
              justify-content: flex-end;
              margin-bottom: 10px;
            "
          >
            <el-button type="primary" @click="onAddtrip()">添加行程</el-button>
          </div>
          <el-form-item label="上传行程">
            <div class="upload-list">
              <div class="wu-yu" v-for="(item, index) in anchors.trip_zip">
                <i
                  @click.stop="handleClose('trip_zip', index)"
                  class="close el-icon-close"
                />
                <el-upload
                  class="avatar-uploader"
                  action=""
                  :http-request="handlesAvatarSuccess"
                  :show-file-list="false"
                  :on-success="
                    (response, file, fileList) =>
                      handleSuccess(response, file, fileList, index)
                  "
                >
                  <div v-if="!!item.file" class="img-box">
                    <i
                      v-if="!checkIfUrlContainsImage(item.file)"
                      class="el-icon-folder"
                    />
                    <img
                      v-else
                      style="width: 100px; height: 100px"
                      :src="item.file"
                      class="avatar"
                      alt=""
                    />
                    <div class="desc">{{ handleRegex(item.file) }}</div>
                  </div>
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
                <el-input v-model="item.desc" placeholder="行程说明"></el-input>
              </div>
            </div>
            <span style="color: red"
              >(本行程请上传,ppt,word,pdf格式的文件)</span
            >
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/PaginationFixed";
import myEditor from "@/components/Wangeditor/index.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "getQa",
  components: { Pagination, myEditor },
  data() {
    return {
      statusArr: { 0: "禁用", 1: "启用" },
      title: "",
      list: [],
      total: 0,
      loading: false,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        status: null,
        city_name: "",
        title: "",
        content: "",
        img_zip: [],
        trip_zip: [],
      },
      dialogCreate: false,
      dialogEdit: false,
      item: {},
      anchors: {
        qaQuestions: [],
        img_zip: [{ desc: "", file: "" }],
        trip_zip: [{ desc: "", file: "" }],
      },
      getQaCitys: {},
    };
  },
  created() {
    this.listQuery.status = this.$route.query.status || null;
    this.listQuery.content = this.$route.query.content || null;
    this.getList();
    this.getQaCity();
    // this.onChange()
  },
  methods: {
    checkIfUrlContainsImage(url = "") {
      const imageExtensions = [
        ".jpg",
        ".jpeg",
        ".png",
        ".gif",
        ".bmp",
        ".svg",
        ".webp",
      ];
      return imageExtensions.some((extension) =>
        url.toLowerCase().endsWith(extension)
      );
    },

    async handlesAvatarSuccess(file) {
      try {
        var formdata = new FormData();
        formdata.append("file", file.file);

        this.upLoading = true;
        const _this = this;
        const res = await this.$axios.post("/admin/upload/index", formdata, {
          headers: {
            "Content-type": "multipart/form-data",
            "X-Token": getToken(),
          },
        });
        // if (![200].includes(res.data.code)) {
        //   this.$message.error("上传失败");
        //   return;
        // }
        // 主动回调success方法
        file.onSuccess(res);
      } catch (error) {
        console.error(error);
      }
    },
    handleClose(val, i) {
      if (this.anchors[val].length == 1) {
        this.$message({
          message: "至少保留一条",
          type: "warning",
        });
        return;
      }
      console.log("i===", i);
      this.anchors[val].splice(i, 1);
    },
    handleAdd() {
      this.anchors.qaQuestions.push({
        sort:
          this.anchors.qaQuestions[this.anchors.qaQuestions.length - 1].sort +
          1,
        title: "",
        content: "",
      });
    },
    handleDel(id) {
      if (this.anchors.qaQuestions.length == 1) {
        this.$message({
          message: "至少保留一条",
          type: "warning",
        });
        return;
      }
      this.anchors.qaQuestions = this.anchors.qaQuestions.filter(
        (item, i) => i !== id
      );
    },
    getList() {
      this.listLoading = true;
      this.$axios
        .get("/admin/qa/getQa", { params: this.listQuery })
        .then((response) => {
          this.list = response.data.data;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    onAddImg() {
      this.anchors.img_zip.push({ desc: "", file: "" });
    },
    onAddtrip() {
      this.anchors.trip_zip.push({ desc: "", file: "" });
    },
    handleAvatarSuccess(res, file, fileList, index) {
      if (!res.data) return;
      this.anchors.img_zip[
        index
      ].file = `${window.location.protocol}//${window.location.host}${res.data}`;
      // this.anchors.img_zip.push(
      //   `${window.location.protocol}//${window.location.host}${res.data}`
      // );
    },
    handleSuccess(res, file, fileList, index) {
      console.log(res, file, fileList);
      if (!res.data) return;
      this.anchors.trip_zip[
        index
      ].file = `${window.location.protocol}//${window.location.host}${res.data}`;
    },
    handleRegex(val) {
      const regex = /\/([^\/]+)$/;
      const match = val.match(regex);
      return !!match ? match[1] : val;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    onAdd(item) {
      this.dialogCreate = true;
      if (!item.id) {
        this.title = "添加QA";
        this.anchors.qaQuestions = [
          {
            sort: 1,
            title: "",
            content: "",
          },
        ];
        // 初始化时默认排序值为0
        this.anchors.img_zip = [{ desc: "", file: "" }];
        this.anchors.trip_zip = [{ desc: "", file: "" }];
      } else {
        this.title = "编辑QA";
        if (!item.qaQuestions.length) {
          this.anchors = {
            ...item,
            qaQuestions: [
              {
                sort: 1,
                title: "",
                content: "",
              },
            ],
          };
        } else {
          this.anchors = { ...item };
        }
        this.anchors.img_zip = item.img_zip
          ? item.img_zip
          : [{ desc: "", file: "" }];
        this.anchors.trip_zip = item.trip_zip
          ? item.trip_zip
          : [{ desc: "", file: "" }];
      }
    },
    onSave() {
      if (this.loading) return;
      this.loading = true;
      const api =
        this.title == "添加QA" ? "/admin/qa/addQa" : "/admin/qa/editQa";
      this.$axios
        .post(api, this.anchors)
        .then(() => {
          this.dialogCreate = false;
          // this.dialogEdit = false;
          this.loading = false;
          this.getList();
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onDel(item) {
      this.$axios
        .post("/admin/qa/delQa", { id: item.id })
        .then(() => {
          this.getList();
        })
        .catch(() => {});
    },
    getQaCity() {
      this.$axios
        .post("/admin/qacity/getQaCity")
        .then((response) => {
          this.getQaCitys = response.data;
          this.getList();
        })
        .catch(() => {});
    },
    updateSort(item) {
      this.$axios
        .post("/admin/qa/editQa", { id: item.id, sort: item.sort })
        .then(() => {
          this.getList();
        })
        .catch(() => {});
    },
    updateStatus(item) {
      this.$axios
        .post("/admin/qa/editQa", { id: item.id, status: item.status })
        .then(() => {
          this.getList();
        })
        .catch(() => {});
    },
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    setTimeout(() => {
      this.html = "<p>模拟 Ajax 异步设置内容 HTML</p>";
    }, 1500);
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
};
</script>

<style lang="scss" scoped>
.scrollable-container {
  // position: relative;
  height: 500px; /* 可以根据实际情况调整高度 */
  // overflow-y: auto;
}
::v-deep.el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
}
.upload-list {
  display: flex;
  flex-wrap: wrap;
  .wu-yu {
    margin-bottom: 10px;
    position: relative;
    display: flex;
    width: 110px;
    flex-wrap: wrap;
    align-content: space-between;
    & + .wu-yu {
      margin-left: 5px;
    }
    ::v-deep.el-input {
      width: 100px;
      margin: 10px 0 10px 10px;
    }
  }
}
.filter-items {
  position: fixed;
  // right: 0;
  left: 70%;
  z-index: 66;
}
.img-box {
  position: relative;
  display: inline-block;
  width: 100px;
  margin-bottom: 10px;
  margin-left: 10px;
  & + .img-box {
    margin-left: 10px;
  }
  .desc {
    line-height: 16px;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 隐藏溢出 */
    text-overflow: ellipsis; /* 显示省略号 */
  }
}
.avatar-uploader ::v-deep.el-upload {
  display: flex;
  flex-wrap: wrap;
}
.el-icon-plus {
  display: inline-block;
  margin-left: 10px;
}
.el-icon-folder {
  color: #409eff !important;
  font-size: 100px;
}
.close {
  position: absolute;
  top: -10px;
  right: -15px;
  font-size: 18px;
  color: #409eff;
}
.qa-desc {
  display: flex;
}
.mistake-content {
  display: flex;
}
.mistake-left {
  width: 90%;
}
.mistake-right {
  padding-left: 20px;
  height: auto;
  display: flex;
  align-items: center;
}
.app-container {
  position: relative;
  padding-bottom: 60px; /* 分页条的高度 */
}
/* ::v-deep.el-table--fit{
  padding-bottom: 0px !important;
} */
.filter-container,
.el-table {
  padding-bottom: 52px; /* 分页条的高度，以避免内容重叠 */
}
.mistake-btn {
  display: flex;
  flex-direction: row-reverse;
  margin-top: 10px;
}
.search {
  margin-left: 10px;
}
.avatar-uploader .el-upload {
  border: 1px solid #131313;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px solid #979797;
  border-radius: 15px;
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  position: relative;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>
