<template>
  <el-container class="list category">

    <el-header class="content__header">
      <div class="content__box content__nav">
        <div class="content__add"
             @click="$refs.crud.rowAdd()">
          <img :src="`${$router.options.base}img/category.png`"
               height="40px"
               alt="">
          <div>
            <p>创建菜单</p>
            <span>组件菜单 自由管理</span>
          </div>
        </div>
        <div class="list-search">
          <el-input v-model="search.name"
                    @keyup.enter="getList"
                    placeholder="请输入名称">
            <template #suffix>

              <el-icon @click="getList"
                       class="el-input__icon">
                <el-icon-search></el-icon-search>
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </el-header>
    <el-main>
      <avue-crud ref="crud"
                 :option="option"
                 v-model="form"
                 @row-save="rowSave"
                 @row-update="rowUpdate"
                 @row-del="rowDel"
                 v-loading="loading"
                 v-bind="$loadingParams"
                 :before-open="beforeOpen"
                 :data="data">
        <template #menu-form="{}">
          <el-button icon="el-icon-search"
                     v-if="isParent"
                     @click="api.box=true"
                     type="primary">导入组件</el-button>
        </template>
        <template #options-form="{}">
          <monaco-editor v-model="form.options"
                         language="javascript"
                         height="100"></monaco-editor>
        </template>
        <template #defaults-form="{}">
          <monaco-editor v-model="form.defaults"
                         language="javascript"
                         height="100"></monaco-editor>
        </template>
        <template #component-form="{}">
          <monaco-editor v-model="form.component"
                         language="javascript"
                         height="100"></monaco-editor>
        </template>
        <template #src-form>
          <img :src="form.src"
               v-if="form.src"
               style="width:100px;"
               alt="">
          <el-upload :show-file-list="false"
                     multiple
                     :http-request="httpRequest"
                     list-type="picture">
            <el-button :loading="loading"
                       icon="el-icon-upload"
                       type="primary">点击上传</el-button>
          </el-upload>
        </template>
        <template #menu="{row,index,size}">
          <el-button type="primary"
                     text
                     v-if="validatenull(row.parentId)||row.parentId==0"
                     :size="size"
                     @click="handleLefAdd(row,index)"
                     icon="el-icon-plus">
            增加子级
          </el-button>
        </template>
      </avue-crud>
    </el-main>
    <el-dialog title="组件库"
               v-model="api.box"
               class="avue-dialog"
               width="70%">
      <component-list v-if="api.box"
                      tabs
                      @change="handleApiChange"
                      :menu="false"></component-list>
    </el-dialog>
  </el-container>
</template>

<script>

import { uploadImg } from '@/api/visual'
import MonacoEditor from '@/page/components/monaco-editor'
import { getList, getObj, addObj, delObj, updateObj } from '@/api/nav'
import iconList from '@/page/list/utils/icon'
import componentList from '../../page/list/components.vue'
import { getObj as getComponentObj } from '@/api/components'
const tempList = {
  0: {
    defaults: {
      "name": "vue",
      "title": "vue",
      "icon": "icon-vue",
      "img": "/img/assets/text4.png",
      "dataType": 0,
      "dataFormatter": "",
      "dataHeader": "",
      "dataQuery": "",
      "stylesFormatter": ""
    },
    options: {
      "content": ''
    },
    component: {
      "width": 800,
      "height": 300,
      "name": "vue",
      "prop": "vue"
    }
  },
  1: {
    defaults: {
      name: "自定义echart",
      title: "自定义echart",
      icon: 'icon-echart',
      img: '/img/assets/text5.png',
      dataType: 1,
      "dataMethod": 'get',
      data: {
        "categories": [
          "苹果",
          "三星",
          "小米",
          "oppo",
          "vivo"
        ],
        "series": [{
          name: "手机品牌",
          data: [
            1000879,
            3400879,
            2300879,
            5400879,
            3400879
          ]
        }]
      },
      echartFormatter: "",
      dataFormatter: "",
      dataHeader: "",
      dataQuery: "",
      stylesFormatter: "",
      url: ""
    },
    options: {
      remote: false,
      src: '/echart-remote-temp.js'
    },
    component: {
      width: 660,
      height: 560,
      name: "common",
      prop: "common",
      remoteContent: ''
    }
  },
  2: {
    defaults: {
      name: "html自定义",
      title: "html自定义",
      icon: 'icon-html',
      img: '/img/assets/html.png',
      dataType: 0,
      data: [],
      dataFormatter: "",
      dataHeader: "",
      dataQuery: "",
      stylesFormatter: ""
    },
    component: {
      width: 500,
      height: 500,
      name: "html",
      prop: "html",
      remoteContent: ''
    },
    options: {
      content: '',
      remote: false,
      src: '/html-remote-temp.js'
    }
  },
  3: {},
  4: {
    defaults: {
      name: "3d模型",
      title: "3d模型",
      icon: 'icon-d',
      img: '/img/assets/text7.png',
      dataType: 0,
      dataFormatter: "",
      dataHeader: "",
      dataQuery: "",
      stylesFormatter: ""
    },
    component: {
      width: 400,
      height: 400,
      name: "3dmodel",
      prop: "3dmodel"
    },
    options: {
      id: '',
      x: 1,
      y: 2,
      z: 3,
      position: 'y',
      scale: 0.8,
      rotate: true,
      type: 'ModelObj',
      src: '/test.obj'
    }
  }
}
export default {
  components: {
    MonacoEditor,
    componentList
  },
  data () {
    return {
      api: {
        box: false,
        item: {}
      },
      search: {},
      loading: false,
      form: {},
      data: []
    }
  },
  created () {
    this.getList()
  },
  computed: {
    isParent () {
      return !this.validatenull(this.form.parentId) && this.form.parentId != 0
    },
    option () {
      let list = iconList.map(ele => 'iconfont ' + ele);
      return {
        dialogWidth: '600',
        dialogMenuPosition: 'center',
        menuWidth: 300,
        menuAlign: "left",
        header: false,
        column: [
          {
            label: '父类',
            prop: 'parentId',
            span: 24,
            hide: true,
            type: 'select',
            dataType: 'string',
            dicFlag: true,
            dicUrl: this.$website.url + '/nav/list',
            dicFormatter:(list)=>{
              return [...[{id:'0',name:'顶级菜单'},...list.data]]
            },
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '名称',
            prop: 'name',
            span: 24,
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }]
          },
          {
            label: '图片',
            prop: 'src',
            width: 200,
            type: 'img',
            limit: 1,
            dataType: 'string',
            alone: true,
            display: this.isParent,
            span: 24,
            rules: [{
              required: true,
              message: "请输入图片",
              trigger: "change"
            }]
          },
          {
            label: '图标',
            prop: 'icon',
            width: 200,
            align: 'center',
            headerAlign: 'center',
            type: 'icon',
            iconList: [{
              label: '阿里云',
              list: list
            }],
            span: 24,
            rules: [{
              required: true,
              message: "请选择图标",
              trigger: "change"
            }]
          }, {
            label: '显示',
            prop: 'hidden',
            type: 'radio',
            hideen: true,
            dicData: [{
              label: '显示',
              value: 0
            }, {
              label: '隐藏',
              value: 1
            }],
            span: 24,
            rules: [{
              required: true,
              message: "请选择是否显示",
              trigger: "change"
            }]

          },
          {
            label: '组件',
            hide: true,
            display: this.isParent,
            prop: 'component',
            span: 24,
            rules: [{
              required: true,
              message: "请输入组件配置",
              trigger: "change"
            }]
          },
          {
            label: '属性',
            hide: true,
            display: this.isParent,
            prop: 'options',
            span: 24,
            rules: [{
              required: true,
              message: "请输入属性配置",
              trigger: "change"
            }]
          },
          {
            label: '其它',
            hide: true,
            display: this.isParent,
            prop: 'defaults',
            span: 24,
            rules: [{
              required: true,
              message: "请输入其它配置",
              trigger: "change"
            }]
          },
        ]
      }
    }
  },
  methods: {
    handleApiChange (val) {
      this.api.item = val
      getComponentObj(this.api.item.id).then(res => {
        const data = res.data.data;
        let content = data.content;
        const type = data.type
        const id = data.id;
        let temp = {}
        temp = this.deepClone(tempList[type])
        if (type == 0) { //vue
          temp.options.content = content
        } else if (type == 1) {//ecahrt
          temp.defaults.echartFormatter = content
        } else if (type == 2) {//html
          temp.options.content = content
        } else if (type == 3) {//收藏
          content = JSON.parse(content)[0] || {}
          temp.options = content.option
          temp.component = content.component
          delete content.component
          delete content.option
          temp.defaults = content
        } else if (type == 4) {//3D
          temp.options.id = id
        }
        this.api.box = false;
        this.api.item = {}
        this.form = {
          ...this.form,
          ...temp
        }
        this.$message.success('导入成功')
      })
    },
    httpRequest (config) {
      this.loading = true;
      var formdata = new FormData();
      formdata.append('file', config.file)
      uploadImg(formdata).then(res => {
        const url = res.data.data.fileUrl;
        this.loading = false;
        this.form.src = url
      })
    },
    validData (id) {
      return true
    },
    beforeOpen (done, type) {
      if (type == 'edit') {
        getObj(this.form.id).then(res => {
          const data = res.data.data;
          this.form = data
          done()
        })
      } else {
        this.form.src = ''
        done()
      }
    },
    rowDel (row, index) {
      if (this.validData(index) && this.$website.isDemo) {
        this.$message.error(this.$website.isDemoTip)
        return false;
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.id).then(() => {
          this.$message.success('删除成功');
          this.getList()
        })
      }).catch(() => {

      });

    },

    handleLefAdd (row, index) {
      this.form.parentId = row.id;
      this.$refs.crud.rowAdd()
    },
    rowUpdate (row, index, done, loading) {
      if (this.validData(index) && this.$website.isDemo) {
        done();
        this.$message.error(this.$website.isDemoTip)
        return false;
      }
      row.parentId = row.parentId || 0
      updateObj(row).then(() => {
        done();
        this.$message.success('修改成功');
        this.getList()
      }).catch(err => {
        loading()
      })
    },

    handleEdit (row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    rowSave (row, done, loading) {
      row.parentId = row.parentId || 0
      addObj(row).then(() => {
        this.$message.success('新增成功');
        this.getList()
        done();
      }).catch(err => {
        loading()
      })
    },
    getList () {
      this.loading = true
      getList().then(res => {
        this.loading = false
        const data = res.data.data;
        let records = data
        this.data = records;
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.category {
  .content {
    &__info {
      height: auto;
    }
    &__item {
      margin-right: 0;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 100%;
    }
    &__logo {
      margin-right: 10px;
      img {
        object-fit: cover;
        width: 40px !important;
      }
    }
    &__main {
      flex: 1;
      justify-content: flex-start;
    }
    &__menu {
      margin-right: 10px;
      position: relative;
      width: 100px;
      height: inherit;
      right: 0;
      display: inline-block;
    }
    &__name {
      width: 300px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>