<template>
  <div id="manger-wrap">
    <div class="left-tree">
      <h2>主数据分类</h2>
      <div class="title">
        <a-input-search
          placeholder="请输入类别名称/代码"
          style="width: 200px"
          @change="onSearch" />
        <div class="action">
          <!-- <div @click="onExpandOpenAll">全部展开</div> -->
          <div @click="onExpandClose">全部收起</div>
        </div>
      </div>
      <a-tree
        v-if="treeData.length>0"
        :replaceFields="{
          title:'catalogName',
          key: 'catalogCode',
          children:'children',
          value:'catalogCode'
        }"
        show-line
        :defaultExpandAll="true"
        :expandedKeys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        :tree-data="treeData"
        @expand="onExpand"
        @select="onClassSelect">
        <template slot="catalogName" slot-scope="{ catalogName }">
          <span v-if="catalogName.indexOf(searchValue) > -1">
            {{ catalogName.substr(0, catalogName.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ catalogName.substr(catalogName.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ catalogName }}</span>
        </template>
        <a-icon slot="switcherIcon" type="down" />
      </a-tree>
    </div>
    <div class="right-table">
      <h2>主数据分类管理 </h2>
      <div class="button-wrap">
        <a-button type="add" @click="addForm">新增</a-button>
        <a-button type="edit" @click="editForm" :disabled="$refs.table&&$refs.table.selectedRows.length!==1">编辑</a-button>
        <a-button type="delete" @click="deleteForm" :disabled="$refs.table&&$refs.table.selectedRows.length===0">删除</a-button>
      </div>
      <div class="table-content">
        <FilterTable
          ref="table"
          :columns="columns"
          :dataSource="dataSource"
          :total="total"
          @changeParams="changeParams"
        />
      </div>
    </div>
    <a-modal
      v-model="modalVisible"
      :destroyOnClose="true"
      title="新建分类"
      :footer="null"
      @ok="handleOk">
      <FormModalAdd ref="model" :treeData="treeData" @handleOk="handleOk" :parentCode="parentCode"/>
    </a-modal>
  </div>
</template>

<script type="text/ecmascript-6">
import FilterTable from '@/components/filterTable'
import FormModalAdd from './components/FormModalAdd.vue'
import { getClassTreeApi, getClassListApi, deleteKindModel } from '@/api/model/kindManger'
const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.catalogCode === key)) {
        parentKey = node.catalogCode
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
const dataList = []
const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const catalogCode = node.catalogCode
    const catalogName = node.catalogName
    dataList.push({ catalogCode, catalogName: catalogName })
    if (node.children) {
      generateList(node.children)
    }
  }
}
	export default {
    components: {
      FilterTable,
      FormModalAdd
    },
    data() {
      return {
        treeData: [],
        searchValue: '',
        autoExpandParent: true,
        expandedKeys: [],
        columns: [
          {
            title: '序号',
            dataIndex: 'orderNum',
            key: 'sort',
            width: 150,
            customRender: (text, record, index) => {
              return (<span>{++index}</span>)
            },
            scopedSlots: { customRender: 'sort' }
          },
          {
            title: '分类名称',
            dataIndex: 'catalogName',
            key: 'sortName',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            },
            ellipsis: true
          },
          {
            title: '分类代码',
            dataIndex: 'catalogCode',
            key: 'sortCode',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            }
          },
          {
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            }
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createDate',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'customRender'
            }
          }
        ],
        dataSource: [],
        total: 0,
        modalVisible: false,
        params: {
          pageSize: 10,
          pageNum: 1
        },
        parentCode: ''
      }
    },
    computed: {

    },
    mounted() {
      this.getClassTree()
    },
    methods: {
      addAttr(data) {
        data.map((item) => {
          item.scopedSlots = { title: 'catalogName' }
          if (item.children) this.addAttr(item.children)
        })
        return data
      },
      getClassTree() {
        getClassTreeApi().then((res) => {
          if (res.code === 200) {
            this.treeData = this.addAttr(res.data.rows)
            generateList(this.treeData)
          }
        })
      },
      getClassList() {
        const { parentCode } = this
        getClassListApi({ parentCode, ...this.params }).then((res) => {
          if (res.code === 200) {
              this.dataSource = res.rows
              this.total = res.total
          }
        })
      },
      onSearch(e) {
        const value = e.target.value
        const expandedKeys = dataList
        .map(item => {
          if (item.catalogName.indexOf(value) > -1) {
            return getParentKey(item.catalogCode, this.treeData)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true
        })
      },
      onClassSelect(selectedKeys, info) {
        // console.log(`info`, info.node.$vnode.data.props.catalogName)
        this.parentCode = selectedKeys[0]
        // this.catalogName = info.node.$vnode.data.props.catalogName
        selectedKeys[0] && this.getClassList()
        info.node.onExpand()
      },
      onExpand(selectedKeys) {
        this.expandedKeys = selectedKeys
      },
      onExpandClose() {
        this.expandedKeys = []
      },
      onExpandOpenAll() {
        this.expandedKeys = []
      },
      addForm() {
        this.modalVisible = true
        setTimeout(() => {
          this.$refs.model.submitType = 'add'
        }, 300)
      },
      editForm() {
        this.modalVisible = true
        setTimeout(() => {
          this.$refs.model.submitType = 'edit'
          this.$refs.model.dataId = this.$refs.table.selectedRows[0].id
          this.$refs.model.form = Object.assign({}, this.$refs.table.selectedRows[0])
        }, 300)
      },
      changeParams(key, value) {
        this.$set(this.params, key, value)
      },
      handleOk() {
        this.modalVisible = false
        this.getClassList()
        this.getClassTree()
      },
      deleteForm() {
        const selectIdMap = []
        this.$refs.table.selectedRows.map((item) => {
          selectIdMap.push(item.catalogCode)
        })
        this.removeKindModel(selectIdMap)
      },
      removeKindModel(selectIdMap) {
        deleteKindModel(selectIdMap).then((res) => {
          this.$message.info(res.msg)
          this.getClassList(0)
          this.getClassTree()
        })
      }
    },
    watch: {
      params: {
        deep: true,
        immediate: true,
        handler(val) {
          this.getClassList(0)
        }
      }
    }
	}
</script>

<style lang="less">
@import url('../_style/index.less');
</style>
