<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="分类id" prop="cateId">
            <el-input v-model="form.cateId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="名称" prop="cateName">
            <el-input v-model="form.cateName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              :on-success="handleSuccess"
              :on-error="handleError"
              :headers="headers"
              :file-list="fileList"
              :action="imagesUploadApi"
              :limit="1"
              list-type="picture-card"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="上级类目" prop="pid">
            <treeselect
              v-model="form.pid"
              :options="foodCate"
              :load-options="loadFoodCate"
              style="width: 370px;"
              placeholder="选择上级类目"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        lazy
        :load="getFoodCate"
        :data="crud.data"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        row-key="id"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="cateId" label="分类id" />
        <el-table-column prop="pid" label="分类上级id" />
        <el-table-column prop="cateName" label="名称" />
        <el-table-column prop="picture" label="图片">
          <template slot-scope="{row}">
            <el-image
              :src="row.url && row.url.url"
              :preview-src-list="[row.url && row.url.url]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-picture" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPer(['admin','dmOrderItem:edit','dmOrderItem:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
              msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDmFoodCate from '@/api/dmFoodCate'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'

const defaultForm = { id: null, cateId: null, pid: 0, cateName: null, picture: null, url: { id: null }, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'DmFoodCate',
  components: { Treeselect, pagination, crudOperation, udOperation }, // rrOperation,
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '菜品分类', url: 'api/dmFoodCate', crudMethod: { ...crudDmFoodCate }, optShow: { del: true, edit: true, add: true, download: false, reset: false }})//, idField: 'id', sort: 'id,desc'
  },
  data() {
    return {
      headers: {
        'Authorization': getToken()
      },
      foodCate: [],
      fileList: [],
      permission: {
        add: ['admin', 'dmFood:add'],
        edit: ['admin', 'dmFood:edit'],
        del: ['admin', 'dmFood:del']
      },
      rules: {
        code: [
          { required: true, message: '编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' }
        ]
      },
      ids: [],
      id: null
    }
  },
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi'
    ])
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.foodCate = []
      console.log('form.id===' + form.id)
      console.log('form.cateId===' + form.cateId)
      this.id = form.cateId
      if (this.id != null) { // form.id
        if (form.pid === null) {
          form.pid = 0
        }
        this.getSupFoodCates(this.id)
      } else {
        this.foodCate.push({ id: 0, label: '顶级类目', children: null })
      }
    },
    // 初始化页面
    getFoodCate(tree, treeNode, resolve) {
      this.id = tree.cateId
      const params = { pid: this.id } // tree.id
      setTimeout(() => {
        crudDmFoodCate.getFoodCate(params).then(res => {
          resolve(res.content)
        })
      }, 100)
    },
    getSupFoodCates(id) {
      // this.ids.push(id)
      crudDmFoodCate.getFoodCateSuperior([id]).then(res => {
        const children = res.map(function(obj) {
          obj.label = obj.cateName
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        console.log('getSupFoodCates', children)
        this.foodCate = [{ id: 0, label: '顶级类目', children: children }]
      })
    },
    loadFoodCate({ action, parentNode, callback }) {
      if (parentNode.cateId === undefined) {
        parentNode.cateId = 0
      }
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDmFoodCate.getFoodCateTree(parentNode.cateId).then(res => {
          parentNode.children = res.map(function(obj) {
            obj.label = obj.cateName
            if (!obj.leaf) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    handleSuccess(jsonData, field) {
      console.log(jsonData)
      this.form.url.id = jsonData.id
      this.form.picture = jsonData.type + '/' + jsonData.realName
    },
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 0
      })
    }
  }
}
</script>

<style scoped>

</style>
