<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['oa:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['oa:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['oa:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['oa:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="card-container" v-loading="loading">
      <el-row :gutter="20">
        <el-col
          v-for="(item, index) in articleList"
          :key="index"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
          class="mb20"
        >
          <el-card
            class="article-card"
            :body-style="{ padding: '16px', height: '100%', display: 'flex', flexDirection: 'column' }"
          >
            <div class="card-header">
              <span class="card-title">{{ item.articleTitle }}</span>
              <el-tag type="info" size="mini" class="category-tag">
                {{ item.category.categoryName }}
              </el-tag>
            </div>

            <div class="card-subtitle">{{ item.subhead }}</div>

            <div class="card-content">
              <div class="card-stat">
                <i class="el-icon-view"></i>
                <span>浏览 {{ item.checkNum }} 次</span>
              </div>
              <div class="card-meta">
                <div><i class="el-icon-user"></i> {{ item.createBy }}</div>
                <div><i class="el-icon-time"></i> {{ parseTime(item.createTime, '{y}-{m}-{d}') }}</div>
              </div>
            </div>

            <div class="card-footer">
              <el-button-group>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handlePreview(item)"
                >预览</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(item)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(item)"
                >删除</el-button>
              </el-button-group>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

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

    <!-- 添加或修改知识管理对话框 -->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="文章标题" prop="articleTitle">
              <el-input v-model="form.articleTitle" placeholder="请输入文章标题" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="8">
            <el-form-item label="文章分类" prop="categoryId">
              <el-input v-model="form.categoryId" placeholder="请输入文章分类" />
            </el-form-item>
          </el-col>-->

          <el-col :span="8">
            <el-form-item label="文章分类" prop="categoryId">
<!--              <el-input v-model="form.categoryId" placeholder="请输入文章分类" />-->
              <treeselect v-model="form.categoryId" :options="categoryList" :normalizer="normalizer" placeholder="选择分类" />
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="副标题" prop="subhead">
              <el-input v-model="form.subhead" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件" prop="accessory">
              <file-upload v-model="form.accessory"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看公告对话框 -->
    <el-dialog :title="title" v-model="openPreview" v-if="openPreview" width="65%" @close="closeDialog" append-to-body>
      <ArticlePreview :article="form"/>
    </el-dialog>

  </div>
</template>

<script>
import { addArticle, delArticle, getArticle, listArticle, updateArticle } from "@/api/oa/article";
import { listCategory } from "@/api/oa/category";
import Treeselect from 'vue3-treeselect'
import 'vue3-treeselect/dist/vue3-treeselect.css'
import ArticlePreview from "./components/ArticlePreview.vue";

export default {
  name: "Article",
  components: { Treeselect, ArticlePreview },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 知识管理表格数据
      articleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        articleTitle: undefined,
      },
      categoryList: [],
      //查看弹出层
      openPreview: false,
      categoryName: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        articleId: [
          { required: true, message: "文章id不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "文章分类不能为空", trigger: "blur" }
        ],
        articleTitle: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询知识管理列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: undefined,
        categoryId: undefined,
        articleTitle: undefined,
        subhead: undefined,
        source: undefined,
        content: undefined,
        checkNum: undefined,
        accessory: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加知识管理";
      listCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "categoryId", "parentId");
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const articleId = row.articleId || this.ids
      listCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "categoryId", "parentId");
      })
      getArticle(articleId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改知识管理";
      });
    },

    /** 查看按钮操作 */
    handlePreview(row){
      this.reset();
      this.openPreview = true;
      this.categoryName= row.category.categoryName;

      const articleId = row.articleId || this.ids
      listCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "categoryId", "parentId");
      })
      getArticle(articleId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.title = "文章预览";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          //删除project关联表属性
          delete this.form.category;
          if (this.form.articleId != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /**关闭预览弹出层**/
    closeDialog(){
      this.getList();
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children
      };
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除知识管理编号为"' + articleIds + '"的数据项？').then(() => {
        this.loading = true;
        return delArticle(articleIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/article/export', {
        ...this.queryParams
      }, `article_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .card-container {
    padding: 0 10px;
  }

  .article-card {
    height: 100%;
    transition: all 0.3s ease;
    border-radius: 8px;
    overflow: hidden;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;

      .card-title {
        font-weight: bold;
        font-size: 16px;
        color: #303133;
        flex: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .category-tag {
        margin-left: 8px;
        flex-shrink: 0;
      }
    }

    .card-subtitle {
      font-size: 13px;
      color: #606266;
      margin-bottom: 12px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      min-height: 36px;
    }

    .card-content {
      flex: 1;
      margin-bottom: 12px;

      .card-stat {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;

        i {
          margin-right: 4px;
        }
      }

      .card-meta {
        font-size: 12px;
        color: #909399;

        div {
          display: flex;
          align-items: center;
          margin-bottom: 4px;

          i {
            margin-right: 4px;
          }
        }
      }
    }

    .card-footer {
      border-top: 1px solid #f0f2f5;
      padding-top: 12px;
      text-align: center;

      .el-button-group {
        display: flex;
        justify-content: space-around;
      }
    }
  }
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .article-card {
    .card-header {
      flex-direction: column;

      .category-tag {
        align-self: flex-start;
        margin-top: 5px;
        margin-left: 0;
      }
    }
  }
}
</style>
