<template>
  <div class="app-container" v-loading="mydata.loading">
    <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-dialog :title="mydata.dialogInfo.title" :visible.sync="mydata.dialogInfo.dialogVisible" :width="mydata.dialogInfo.width">
      <dynamicForm ref="dynamicForm" v-if="mydata.formFiled && mydata.dialogInfo.dialogVisible" :filed="mydata.formFiled" :data="mydata.formData" :selectFileList="mydata.selectFileList" @selectFileQuery="selectFileQuery" @selectChange="selectChange" @save="formSave">
        <template v-slot:ext="{ formdata }">
          <el-form-item label="地址" v-if="formdata['type'] == 'link'">
            <el-input v-model="formdata['link']"></el-input>
          </el-form-item>
          <el-form-item label="appId" v-if="formdata['type'] == 'appid'">
            <el-input v-model="formdata['meta.appId']"></el-input>
          </el-form-item>
          <el-form-item label="单页" v-if="formdata['type'] == 'page'">
            <el-select v-model="formdata['meta.page']">
              <el-option v-for="(item, i) in mydata.pages" :key="`option${i}`" :label="item.title" :value="String(item.postId)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="栏目" v-if="formdata['type'] == 'catalog'">
            <el-select v-model="formdata['meta.catalog']">
              <el-option v-for="(item, i) in mydata.catalog" :key="`option${i}`" :label="item.name" :value="String(item.termId)"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章扩展字段" v-if="mydata.type == 'catalog'">
            <el-button type="primary" size="mini" @click="addExtend">增加扩展字段</el-button>
            <el-row v-for="(item, index) in mydata.extendList" :key="index">
              <el-col :span="4">属性名称：</el-col>
              <el-col :span="6"><el-input v-model="item.label"></el-input></el-col>
              <el-col :span="4">属性键：</el-col>
              <el-col :span="6"><el-input  v-model="item.name"></el-input></el-col>
              <el-col :offset="1" :span="3"><el-button type="danger" size="mini" @click="delExtend(index)">删除</el-button></el-col>
            </el-row>
          </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', 'menu_type'],
  data() {
    return {
      mydata: {
        pagination: false,
        tableData: [],
        total: 0,
        listFileds: [],
        dialogInfo: {
          title: "",
          dialogVisible: false,
          width: "30%",
        },
        formFiled: [],
        formData: {},
        type: this.$route.query.type,
        classify: this.$route.query.classify,
        loading: false,
        operation: [],
        options: {},
        catalog: [],
        pages: [],
        keyValuePairs: [],
        selectFileList: [],
        extendList: []
      }
    };
  },
  async created() {
    const models = require(`./${this.$route.query.classify}config/${this.mydata.type}.js`);
    this.$data.mydata = { ...this.$data.mydata, ...models.default }
    this.query();
  },
  methods: {
    async setform(){
      for (const key in this.mydata.formData.meta) {
        this.mydata.formData[`meta.${key}`] = this.mydata.formData.meta[key]
      }
      if (this.mydata.formData.type == 'catalog') this.getCatalog();
      if (this.mydata.formData.type == 'page') this.pageQuery();
    },
    // 单页列表查询
    async pageQuery(e) {
      const res = await cmsQuery({ paging: false }, 'page');
      if (res.code == 200) this.mydata.pages = res.rows;
    },
    // 栏目查询
    async getCatalog() {
      const res = await cmsQuery({ paging: false }, 'catalog');
      if (res.code == 200) this.mydata.catalog = res.rows;
    },
    // 设置type 与禁用
    setType() {
      if (this.mydata.type == 'catalog') this.mydata.formData.type = 'article';
      // this.mydata.formFiled = this.mydata.formFiled.map(e => ({ ...e, disabled: e.name == 'type' }))
      this.mydata.formFiled = this.mydata.formFiled.map(e => ({ ...e }))
    },
    // 列表查询
    async query(e) {
      const res = await cmsQuery({ pageNum: 1, pageSize: 10, paging: this.mydata.pagination, ...e }, this.mydata.type);
      if (res.code == 200) {
        this.$set(this.mydata, 'tableData', res.rows)
        this.$set(this.mydata, 'total', res.total)
      }
    },
    // 列表添加
    async itemadd(e) {
      await this.selectFileQuery();
      this.mydata.formData = {};
      this.mydata.formFiled = this.mydata.formFiled.map(e => ({ ...e, disabled: false }))
      if (this.mydata.type == 'catalog') this.setType();
      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) {
      await this.selectFileQuery();
      this.setType();
      const res = await cmsFetch('_' + e[`${this.mydata.classify}Id`], this.mydata.type);
      if (res.code == 200) {
        this.mydata.formData = { ...res.data, url: res.data.image };
        if (this.mydata.type !== 'catalog') await this.setform();
        if (this.mydata.type == 'catalog') {
          this.mydata.extendList = [];
          for (const key in res.data.meta) {
            const obj = { name: key, label: res.data.meta[key] }
            this.mydata.extendList.push(obj)
          }
        }
        
        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 listDel(e) {
      const id = e[`${this.mydata.classify}Id`]
      const res = await cmsDel(this.mydata.type, id);
      if (res.code == 200) {
        this.$modal.msgSuccess('删除成功');
        this.query();
      }
    },
    // 添加
    async add() {
      await this.selectFileQuery();
      this.mydata.formData = {};
      this.mydata.formFiled = this.mydata.formFiled.map(e => ({ ...e, disabled: false }))
      if (this.mydata.type == 'catalog') this.setType();
      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;
    },
    // 选择改变
    selectChange(e) {
      const { item, formdata } = e;
      if (item.name == 'type') {
        if (formdata[item.name] == 'catalog') this.getCatalog();
        if (formdata[item.name] == 'page') this.pageQuery();
      }
    },
    // 保存
    async formSave(e) {
      this.mydata.loading = true;
      let res;
      const data = {
        ...e,
        meta: {}
      }
      this.mydata.extendList.forEach(e => {
        const key = e.name;
        const value = e.label;
        data.meta[key] = value;
      });
      try {
         // 修改
        if(e[`${this.mydata.classify}Id`]) res = await cmsUpdate(this.mydata.type == 'catalog' ? data : e, this.mydata.type);
          // 新增
        if(!e[`${this.mydata.classify}Id`]) res = await cmsAdd({ taxonomy: this.mydata.type, ...(this.mydata.type == 'catalog' ? data : e)  }, 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;
      } catch (error) {
        this.mydata.loading = false;
        this.mydata.dialogInfo.dialogVisible = false;
      }
    },
    // 文件选择
    async selectFileQuery(e) {
      const res = await openFiles({ path: e ?? '/' });
      this.mydata.selectFileList = res.data;
    },
    // 增加扩展字段
    addExtend() {
      this.mydata.extendList.push({ name: '', label: '' })
    },
    // 删除扩展属性
    delExtend(index) {
      const data = this.mydata.extendList[index];
      for (const key in this.mydata.formData.meta) {
        if (key == data.name) delete this.mydata.formData.meta[key];
      }
      this.mydata.extendList.splice(index, 1)
    }
  },
};
</script>