<template>
  <div class="contentBox">
    <el-card class="box-card-left">
      <div slot="header">
        <span>菜单列表</span>
      </div>
      <deepTree @nodeClick="treeClick" class="deepTree" :data="treeList"></deepTree>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="addcontents" icon="el-icon-plus">添加文章</el-button>
      </div>
      <div class="main">
        <filterList ref="filterList" :operation="operation" :tableData="contents" :filed="filed" @edit="filtereEdit" @delete="filterDelete" @query="filterQuery" :total="Total">
          <template v-slot:search="{ item, formInline }">
             <!-- 推荐 -->
            <el-switch v-if="item.name == 'recommend'" v-model="formInline[item.name]" active-color="#13ce66" inactive-color="#ff4949" :active-value="true" :inactive-value="false"></el-switch>
            <el-select v-model="formInline[item.name]" placeholder="请选择菜单" v-if="item.name == 'bind'">
              <el-option v-for="item in menus" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
            <el-input v-if="item.name == 'search'"  v-model="formInline[item.name]" placeholder="请输入关键字" clearable></el-input>
          </template>
        </filterList>
      </div>
    </el-card>
    <dialogAndDrawer :width="'70%'" :title="title" :visibleSync="visibleSync" v-if="visibleSync" @close="visibleSync = false, lookUser = false">
      <template v-slot:windowMain>
        <formData v-if="!lookUser" ref="formData" :filed="formfiled" :data="formdata" :rules="formrules" @save="formSave">
          <template v-slot:formItem="{ item, formdata }">
            <!-- 推荐 -->
            <el-switch v-if="item.name == 'recommend'" v-model="formdata[item.name]" active-color="#13ce66" inactive-color="#ff4949" :active-value="true" :inactive-value="false"></el-switch>
            <!-- 置顶 -->
            <el-switch v-if="item.name == 'istop'" v-model="formdata[item.name]" active-color="#13ce66" inactive-color="#ff4949" :active-value="true" :inactive-value="false"></el-switch>
            <!-- 缩略图 -->
            <el-upload
              v-if="item.name == 'thumbnail'"
              class="avatar-uploader"
              action="/api/files/avatar/upload"
              :show-file-list="false"
              :headers="myHeaders"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="formdata[item.name] && formdata[item.name] !== ''" :src="formdata[item.name]" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- 富文本 -->
            <editoritem v-if="item.name == 'content'" @change="editChage" :value="formdata[item.name]"></editoritem>
            <!-- 附件上传 -->
            <el-upload
              v-if="item.name == 'annex'"
              :headers="myHeaders"
              class="upload-demo"
              action="/api/files/annex/upload"
              :on-success="handleAnnexSuccess"
              :on-remove="handleRemove"
              :on-error="handleerr"
              :file-list="fileList">
              <el-button size="small" type="primary">附件上传</el-button>
            </el-upload>
            <!-- 来源输入带建议 -->
            <el-autocomplete value-key="name" v-if="item.name == 'source'" v-model="formdata[item.name]" :fetch-suggestions="querySearchAsync" placeholder="请输入内容" @select="handleSelect"></el-autocomplete>
            <!-- 作者输入带建议 -->
            <el-autocomplete value-key="name" v-if="item.name == 'author'" v-model="formdata[item.name]" :fetch-suggestions="authorSelect" placeholder="请输入内容" @select="handleAuthorSelect"></el-autocomplete>
          </template>
        </formData>
        <filterList v-else ref="filterList" :tableData="userList"  :filter="false" :readOnly="true" :filed="userfiled" @query="userfilterQuery" :total="userTotal"></filterList>
      </template>
    </dialogAndDrawer>
  </div>
</template>
<script>
import filterList from '@components/filterList/index.vue';
import dialogAndDrawer from '@components/dialogAndDrawer.vue';
import formData from '@components/formData/index.vue';
import editoritem from '@components/editoritem2.vue';
import deepTree from '@components/deepTree.vue';
import { mapState, mapActions } from 'vuex';
const token = sessionStorage.getItem('token');
export default {
  components: {
    filterList,
    dialogAndDrawer,
    formData,
    editoritem,
    deepTree
  },
  data() {
    return {
      handleAuthor: false,
      types: null,
      info: {},
      lookUser: false,
      fileList: [],
      myHeaders: { Authorization: token },
      title: '',
      visibleSync: false,
      filed: [
        { name: 'title', label: '标题' },
        { name: 'search', label: '关键字查询', formater: 'slot', filter: true, isshow: false },
        { name: 'recommend', label: '是否查询推荐', formater: 'slot', filter: true, isshow: false },
        { name: 'visit', label: '访问量', width: '150' }
      ],
      formdata: {},
      userfiled: [
        { name: 'name', label: '名称' },
        { name: 'phone', label: '手机号' }
      ],
      formfiled: [
        { name: 'thumbnail', label: '缩略图', formater: 'slot' },
        { name: 'twoTitle', label: '二级标题' },
        { name: 'title', label: '标题' },
        { name: 'curtTitle', label: '副标题' },
        { name: 'source', label: '来源', formater: 'slot' },
        { name: 'recommend', label: '推荐', formater: 'slot' },
        { name: 'author', label: '作者', formater: 'slot' },
        { name: 'bind', label: '绑定菜单', formater: 'dict:menus' },
        { name: 'date', label: '时间', formater: 'date:datetime' },
        { name: 'istop', label: '置顶', formater: 'slot' },
        { name: 'content', label: '内容', formater: 'slot' },
        { name: 'annex', label: '附件', formater: 'slot' }
      ],
      formrules: {
        // thumbnail: [
        //   { required: true, message: '请上传缩略图', trigger: 'chage' }
        // ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        // describe: [
        //   { required: true, message: '请输入描述', trigger: 'blur' }
        // ],
        bind: [
          { required: true, message: '请绑定菜单', trigger: 'chage' }
        ],
        date: [
          { required: true, message: '请输入时间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      operation: [
        { name: 'edit', label: '修改', icon: 'el-icon-edit' },
        { name: 'delete', label: '删除', icon: 'el-icon-delete' }
      ]
    };
  },
  computed: {
    ...mapState(['contentsList', 'Total', 'menusList', 'userList', 'userTotal', 'dict']),
    contents() {
      this.contentsList.map(p => {
        const findName = this.menusList.find(e => e.code == p.bind);
        if (findName) p.bind = findName?.name;
        return p;
      });
      return this.contentsList;
    },
    menus() {
      const menus = this.menusList.filter(e => e.parentCode !== 'null' && e.type == 1);
      return menus;
    },
    treeList() {
      const menusall = this.menusList.filter(e => (e.type !== 2 && e.type !== '2'));
      return this.$tree(menusall);
    }
  },
  async created() {
    await this.filterQuery();
    await this.menusQuery();
    await this.sourceQuery();
  },
  methods: {
    ...mapActions(['contentsQuery', 'contentsCreate', 'contentsUpdate', 'contentsDelete', 'contentsFetch', 'menusQuery', 'userQuery', 'sourceQuery', 'search']),
    // 查询字典函数
    async querySearchAsync(queryString, cb) {
      await this.sourceQuery();
      cb(this.dict.source);
    },
    // 作者查询函数
    async authorSelect(queryString, cb) {
      const authorList = localStorage.getItem('author');
      if (authorList && authorList !== null && authorList !== '') {
        let list = authorList.split(',');
        list = list.map(e => ({ name: e }));
        cb(list);
        return;
      }
      // eslint-disable-next-line standard/no-callback-literal
      cb([]);
    },
    // 选择建议
    handleSelect(item) {
      console.log(item);
    },
    // 作者选择建议
    handleAuthorSelect(e) {
      this.handleAuthor = true;
    },
    // 添加
    addcontents () {
      this.formdata = {};
      this.title = '添加文章';
      this.visibleSync = true;
      if (this.types !== null) this.$set(this.formdata, 'bind', this.types);
    },
    // 修改
    async filtereEdit (e) {
      const res = await this.contentsFetch({ id: e._id });
      this.formdata = res.data;
      this.title = '修改文章';
      this.visibleSync = true;
      this.fileList = [];
      if (e.annex) this.fileList = e.annex.filter(e => e !== '');
    },
    // 删除
    async filterDelete (e) {
      const res = await this.contentsDelete({ id: e?._id });
      this.$resChange(res, '删除成功');
      this.filterQuery();
    },
    // 查询
    async filterQuery ({ filter = {}, paging = { page: 0, size: 10 } } = {}) {
      this.page = paging.page;
      if (filter.search) {
        await this.search({ ...filter, paging });
        return;
      }
      if (this.types !== null) filter.bind = this.types;
      await this.contentsQuery({ filter, paging });
    },
    // 表单保存
    async formSave (e) {
      if (e.isRevise && e?.isRevise == false) {
        this.$message.warning('未作修改');
        return;
      }
      this.$delete(e, 'isRevise');
      let res, msg;
      e.annex = this.fileList;
      // 修改
      if (e._id) {
        delete e.svip;
        delete e.isShow;
        res = await this.contentsUpdate(e);
        msg = '文章修改成功';
      } else {
        res = await this.contentsCreate(e);
        msg = '文章添加成功';
      }
      if (e._id) {
        // paging.page = this.page + 1;
        this.$refs.filterList.handleCurrentChange(this.page + 1);
      } else {
        this.$refs.filterList.resetPage(-1);
      }
      const author = localStorage.getItem('author');
      if (!this.handleAuthor) {
        if (author) {
          if (!author.includes(e.author)) localStorage.setItem('author', `${author}, ${e.author}`);
        } else {
          localStorage.setItem('author', e.author);
        }
      }
      this.$resChange(res, msg);
      this.visibleSync = false;
      this.fileList = [];
      this.handleAuthor = false;
    },
    // 富文本改变
    editChage (e) {
      this.$refs.formData.setForm('content', e);
    },
    // 附件上传
    handleAnnexSuccess(res, file) {
      this.fileList.push({ name: res.data.name, url: res.data.filePath });
    },
    // 附件上传失败
    handleerr(err, file, fileList) {
      console.log(err);
    },
    // 删除附件列表
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 缩略图上传
    handleAvatarSuccess(res, file) {
      this.$refs.formData.setForm('thumbnail', res.data.filePath);
    },
    // 缩略图上传限制
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
    },
    async treeClick({ data, node }) {
      if (data.children) return;
      this.types = data.code;
      const filter = { bind: data.code };
      await this.filterQuery({ filter });
      this.$refs.filterList.resetPage(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.contentBox {
  width: 100%;
  height: 100%;
  display: flex;
  .box-card {
    width: 78%;
    height: 100%;
    ::v-deep .el-card__header {
      // background-color: #f5f5f5;
      background-image: linear-gradient(to right, #53b2ff, #fff);
    }
    .el-card__body {
      height: 100%;
    }
  }
  .box-card-left {
    width: 20%;
    height: 100%;
    ::v-deep .el-card__header {
      // background-color: #e6e6e6;
      background-image: linear-gradient(to left, #53b2ff, #ffffff);
    }
    ::v-deep .el-card__body {
      height: 88%;
      // background-color: #e6e6e6;
      .deepTree {
        width: 100%;
        height: 100%;
        overflow-y: auto;
      }
      .deepTree::-webkit-scrollbar {
        width: 0px;
        height: 0px;
      }
    }
  }
}
.el-dialog, .el-drawer {
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
</style>
<style>
.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409EFF;
}
</style>
