<template>
  <div class="app-container" v-loading="mydata.loading">
    <el-row :gutter="10">
      <el-col :span="4" class="tree" v-if="mydata.type !== 'page'">
        <div class="columnBox">
           <div class="is_node">栏目列表</div>
        </div>
        <el-tree class="filter-tree" highlight-current :data="mydata.treeData" :props="mydata.defaultProps" node-key="tremId" ref="myTree" @node-click="nodeClick"> </el-tree>
      </el-col>
      <el-col :span="mydata.type == 'page' ? 24 : 20" class="table">
        <FilterList v-if="mydata.tableData" :pagination="mydata.pagination" :options="mydata.options" :operation="mydata.operation" :filed="mydata.listFileds" :tableData="mydata.tableData" :total="mydata.total" @itemadd="itemadd" @query="query" @edit="listEdit" @delete="listDel" @add="add"></FilterList>
      </el-col>
    </el-row>
    <el-dialog :title="mydata.dialogInfo.title" :visible.sync="mydata.dialogInfo.dialogVisible" :width="mydata.dialogInfo.width">
      <dynamicForm ref="dynamicForm" v-if="mydata.formFiled && mydata.dialogInfo.dialogVisible" @switchtChange="switchtChange" :filed="mydata.formFiled" :data="mydata.formData" :selectFileList="mydata.selectFileList" @selectFileQuery="selectFileQuery" @save="formSave">
        <template v-slot:ext="{ formdata }">
            <el-form-item label="选择栏目" v-if="formdata['meta.islink'] == '0'">
              <el-select v-model="formdata['meta.catalog']" @change="getarticle">
                <el-option v-for="(item, i) in mydata.catalog" :key="`option${i}`" :label="item.name" :value="String(item.alias)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择文章" v-if="formdata['meta.islink'] == '0'">
              <FilterList @articleSelect="articleSelect" v-if="!formdata['meta.id'] || formdata['meta.id'] == ''" :operation="mydata.articleOperation" :useBtn="false" :filter="false" :filed="mydata.articleFileds" :tableData="mydata.articleList" :total="mydata.articleTotal" @query="getarticle"></FilterList>
              <span v-else>
                {{ formdata['meta.articleTitle'] }}
                <el-button type="primary" size="mini" @click="resetArticle">选择</el-button>
              </span>
            </el-form-item>
          </template>
      </dynamicForm>
    </el-dialog>
  </div>
</template>

<script>
import { openFiles } from "@/api/files/upload";
import { cmsAdd, cmsUpdate, cmsDel, cmsQuery, cmsFetch } from "@/api/cms/index";
export default {
  name: "Info",
  dicts: ['term_type'],
  data() {
    return {
      mydata: {
        pagination: true,
        tableData: [],
        total: 0,
        listFileds: [],
        dialogInfo: {
          title: "",
          dialogVisible: false,
          width: "50%",
        },
        formFiled: [],
        formData: {},
        type: this.$route.query.type,
        classify: this.$route.query.classify,
        loading: false,
        operation: [],
        options: {},
        // 树
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        alias: '',
        termId: '',
        selectFileList: [],
        models: {},
        catalog: [],
        articleList: [],
        articleTotal: 0,
        articleFileds: [{ label: "标题", name: "title", placeholder: "输入摘要" }],
        articleOperation: [{ name: 'articleSelect', label: '选择' }]
      }
    };
  },
  async created() {
    this.models = require(`./${this.$route.query.classify}config/${this.mydata.type}.js`);
    this.$data.mydata = { ...this.$data.mydata, ...this.models.default }
    if (this.mydata.type == 'page') {
      await this.query();
      return;
    }
    await this.getCatalog();
  },
  methods: {
    // 选择文章
    resetArticle() {
      this.$refs.dynamicForm.setForm('meta.id', '')
      this.$refs.dynamicForm.setForm('meta.articleTitle', '')
      this.getarticle();
    },
    // 文章选择
    articleSelect(e) {
      this.$refs.dynamicForm.setForm('meta.type', 'article')
      this.$refs.dynamicForm.setForm('meta.id', e.postId)
      this.$refs.dynamicForm.setForm('meta.articleTitle', e.title)
    },
    // 查询文章
    async getarticle(e) {
      const res = await cmsQuery({ pageNum: 1, pageSize: 10, ...e }, 'article', this.$refs.dynamicForm.formdata['meta.catalog']);
      console.log(res, 'res');
      if (res.code == 200) {
        this.$set(this.mydata, 'articleList', res.rows)
        this.$set(this.mydata, 'articleTotal', res.total)
      }
    },
    // 所有栏目查询
    async getCatalogs() {
      const res = await cmsQuery({ paging: false }, this.$route.query.taxonomy ?? 'catalog');
      if (res.code == 200) this.mydata.catalog = res.rows;
    },
    // 查询分类栏目
    async getCatalog() {
      this.mydata.loading = true;
      const res = await cmsQuery({ paging: false, type: this.mydata.type }, this.$route.query.taxonomy ?? 'catalog');
      if (res.code == 200) this.mydata.catalog = res.rows;
      if (res.code == 200 && res.rows.length > 0) {
        this.$set(this.mydata, 'treeData', this.handleTree(res.rows, 'termId'))
        if (this.mydata.treeData[0]) this.mydata.alias = this.mydata.treeData[0].alias;
        this.nodeClick(this.mydata.treeData[0]);
      }
      this.mydata.loading = false;
    },
    // 列表查询
    async query(e) {
      this.mydata.loading = true;
      const res = await cmsQuery({ ...e, pageNum: e?.pageNum ?? 1, pageSize: e?.pageSize ?? 10, paging: this.mydata.pagination }, this.mydata.type, this.mydata.alias);
      if (res.code == 200) {
        this.$set(this.mydata, 'tableData', res.rows)
        this.$set(this.mydata, 'total', res.total)
      }
      this.mydata.loading = false;
    },
    // 列表添加
    async itemadd(e) {
      await this.selectFileQuery();
      this.mydata.formData = {};
      this.mydata.formData.parentId = e[`${this.mydata.classify}Id`];
      const dict = this.dict.type.term_type.find(j => j.value == this.mydata.type);
      this.mydata.dialogInfo.title = `添加${dict?.label}`;
      this.mydata.dialogInfo.dialogVisible = true;
    },
    // 列表修改
    async listEdit(e) {
      this.mydata.loading = true;
      await this.selectFileQuery();
      const res = await cmsFetch('_' + e[`${this.mydata.classify}Id`], this.mydata.type);
      if (res.code == 200) {
        const urls = res.data.attachments.map(e => e.url)
        this.mydata.formData = { ...res.data, url: res.data.image, topStatus: String(res.data.topStatus), urls: String(urls) };
        for (const key in this.mydata.formData.meta) {
          this.mydata.formData[`meta.${key}`] = this.mydata.formData.meta[key]
        }
        const dict = this.dict.type.term_type.find(j => j.value == this.mydata.type);
        this.mydata.dialogInfo.title = `修改${dict.label}`;
        this.mydata.dialogInfo.dialogVisible = true;
        if (this.mydata.formData['meta.islink'] && this.mydata.formData['meta.islink'] == '0') this.switchtChange({ formdata: this.mydata.formData });
      }
      this.mydata.loading = false;
    },
    // 列表删除
    async listDel(e) {
      this.mydata.loading = true;
      const id = e[`${this.mydata.classify}Id`]
      const res = await cmsDel(this.mydata.type, id);
      if (res.code == 200) {
        this.$modal.msgSuccess('删除成功');
        this.query();
      }
      this.mydata.loading = false;
    },
    // 添加
    async add() {
      await this.selectFileQuery();
      this.mydata.formData = {};
      const dict = this.dict.type.term_type.find(j => j.value == this.mydata.type);
      this.mydata.dialogInfo.title = `添加${dict.label}`;
      this.mydata.dialogInfo.dialogVisible = true;
    },
    // 表单保存
    async formSave(e) {
      this.mydata.loading = true;
      let res;
      // 修改
      if(e[`${this.mydata.classify}Id`]) res = await cmsUpdate(e, this.mydata.type);
        // 新增
      if(!e[`${this.mydata.classify}Id`]) res = await cmsAdd({ ...e, contentType: this.mydata.type, catalogIds: this.mydata.termId ? [this.mydata.termId] : [] }, this.mydata.type);
      if (res.code == 200) {
        this.$modal.msgSuccess(`${e[`${this.mydata.classify}Id`] ? '修改' : '新增'}成功`);
        this.mydata.dialogInfo.dialogVisible = false;
        this.query();
      }
      this.mydata.loading = false;
    },
    // 节点点击
    async nodeClick(e) {
      // const models = require(`./${this.$route.query.classify}config/${this.mydata.type}.js`);
      this.mydata.formFiled = [ ...this.models.default.formFiled ];
      const extendList = [];
      for (const key in e.meta) {
        const obj = { name: `meta.${key}`, label: e.meta[key] }
        if (key == 'videoImg') obj.formater = "imageUpload";
        extendList.push(obj)
      }
      this.mydata.formFiled.splice(7, 0, ...extendList)
      this.mydata.alias = e.alias;
      this.mydata.termId = e.termId;
      this.query();
    },
    // 文件选择
    async selectFileQuery(e) {
      const res = await openFiles({ path: e ?? '/' });
      this.mydata.selectFileList = res.data;
    },
    switchtChange(e) {
        console.log(e)
        if (!e.formdata['meta.islink'] || (e.item && e.item.name !== 'meta.islink')) return;
        if (e.formdata['meta.islink'] == 0) {
          this.mydata.formFiled.splice(2, 7, ...[
            { label: "置顶", name: "topStatus", formater: 'switch', activeValue: '1', inactiveValue: '0' },
            { label: "隐藏/显示", name: "visible", formater: 'switch', activeValue: '1', inactiveValue: '0' },
          ])
          this.getCatalogs();
          if (this.$refs.dynamicForm) {
            this.$refs.dynamicForm.resetForm();
            this.$refs.dynamicForm.setForm('meta.islink', e.formdata['meta.islink']);
            this.$set(this.mydata, 'articleList', [])
            this.$set(this.mydata, 'articleTotal', 0)
          }
        } else {
          this.$refs.dynamicForm.resetForm();
          this.mydata.formFiled.push(
            { label: "标题", name: "title" },
            { label: "摘要", name: "summary" },
           
            { label: "状态", name: "status", formater: "dict:essay_type" },
            { label: "备注", name: "remark", placeholder: "输入备注", formater: "textarea" },
            { label: "内容", name: "content", formater: 'editor' },
          )
        }
        if (this.$refs.dynamicForm) {
          this.$refs.dynamicForm.setForm('topStatus', e.formdata['topStatus']);
          this.$refs.dynamicForm.setForm('visible', e.formdata['visible']);
          this.$refs.dynamicForm.setForm('image', e.formdata['image']);
          this.$refs.dynamicForm.setForm('postId', e.formdata['postId']);
          this.$refs.dynamicForm.setFileds()
        }
      }
  },
};
</script>