<template>
  <rx-layout>
    <div slot="center" style>
      <rx-fit>   
        <div slot="toolheader" border="false" foldbtn="false">
          <breadcrumb firstLevel="知识仓库管理" lastLevel="知识分类" />
          <div class="mainContent">
            <div class="body">
              <div class="content">
                <a-form ref="searchForm" layout="inline" style="display:flex;flex-wrap:wrap;">
                  <!-- <div style="width:80%;display:flex;flex-wrap:wrap;">
                    <a-form-item
                      style="width:300px;margin: 5px 40px 5px 0;"
                      label="分类名称"
                      name="name">
                      <a-input v-model="queryParam.name" placeholder="请输入"/>
                    </a-form-item>
                  </div> -->
                  <a-form-item
                      class="form-item-style"
                      label="分类名称"
                      name="name">
                      <a-input class="set-input" v-model="queryParam.name" placeholder="请输入"/>
                    </a-form-item>
                  <div style="display:flex;justify-content:flex-end;margin-top: 8px;">
                    <a-button @click="handleResetClick">重置</a-button>
                    <a-button type="primary" @click="handleSearchClick">查询</a-button>
                  </div>
                </a-form>
                <rx-button alias="classificationAdd" :butn-icon="'none'" @click="handleAddClassClick">新增分类</rx-button>
              </div>
            </div>
          </div>
        </div>
        <rx-grid
          ref="classifyRef"
          class="table-style"
          style="background: #fff"
          :columns="columns"
          :url="api.findAllKnowledgeCategory"
          :queryParam="queryParam"
          data-field="result.data"
          :defaultPageSize="10"
          :heightAuto="true"
          :pageSizeOptions="['10','20','30','40']"
          idField="pkId"
        >
          <template slot="name" slot-scope="{text}">
            <div style="white-space: pre-line">{{ text }}</div>
          </template>
          <template slot="action" slot-scope="{text,record,index}">
            <rx-button class="clearBtn" alias="classificationEdit" :butn-icon="'none'" v-if="record.isSys != 1" @click="handleUpdateClassifyClick(record)">编辑</rx-button>
            <rx-button class="clearBtn" alias="classificationLook" :butn-icon="'none'" @click="handleJumpKnowledgeManage(record)">查看知识</rx-button>
            <template v-if="isShowButton">
              <rx-button v-if="index != (getDataLength(record) - 1)" class="clearBtn" alias="classificationRise" :butn-icon="'none'"  @click="handleActionClick(record,false)">下降</rx-button>
              <rx-button v-if="index != 0" class="clearBtn" alias="classificationRise" :butn-icon="'none'" @click="handleActionClick(record,true)">上升</rx-button>
            </template>
            <rx-button class="clearBtn" alias="classificationDel" :butn-icon="'none'" v-if="record.isSys != 1" @click="handleDeleteClick(record)">删除</rx-button>
          </template>
        </rx-grid>
      </rx-fit>
      <a-modal v-model="knowledgeShow" 
               :title="title" 
               centered
               okText="保存"
               @ok="handleOk"
               :confirmLoading="saveLoading"
               @cancel="handleCancel">
        <a-form ref="classRef" :model="classForm" layout="inline" :label-col="{ span: 4 }">
          <a-form-item label="分类名称" prop="name">
            <a-input v-model="classForm.name" :maxLength="10" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="上级分类" prop="parent" v-if="chooseLevel != 1">
            <a-cascader v-model="classForm.parent" 
                        ref="cascader"
                        :options="classifyLevelList" 
                        :fieldNames="{ label: 'name', value: 'pkId', children: 'children' }"
                        placeholder="请选择上级分类，创建一级分类无需选择"
                        :changeOnSelect="changeOnSelect" />
          </a-form-item>
          <a-form-item label="排序" prop="sort">
            <div style="width:40%">
              <a-input-number v-model="classForm.sort" :min="0" />
            </div>
          </a-form-item>
        </a-form>
      </a-modal>
    </div> 
  </rx-layout>
</template>

<script>
import breadcrumb from '../components/breadcrumb.vue'
import api from '@/api/knowledge/classify'
import classApi from '@/api/knowledge/classify'
import { getCategoryId } from '../aJs/getClassifyTree'
import mixin from "../aMixin/mixin"
const classifyMixin = new mixin('classify')
export default {
  components: {
    breadcrumb
  },
  mixins: [ classifyMixin ],
  data() {
    return {
      api,
      saveLoading: false,
      title: '',
      knowledgeShow: false,
      queryParam: {
        name: ''
      },
      columns:[
        {
          title: 'ID',
          dataIndex: 'pkId',
          align: 'center'
        },
        {
          title: '分类名称',
          dataIndex: 'name',
          // align: 'center',
          scopedSlots: {customRender: 'name'}
        },
        {
          title: '操作人',
          dataIndex: 'operatorName',
          align: 'center'
        },
        {
          title: '操作时间',
          dataIndex: 'updateTime',
          align: 'center'
        },
        { 
          title: '操作',
          dataIndex: 'action', 
          // align: 'center',
          scopedSlots: {customRender: 'action'},
          width: 250
        }
      ],
      classForm: {
        pkId: '',
        name: '',
        parent: [],
        sort: 0
      },
      // 所有分类数据
      classifyList: [],
      // 编辑时不同等级的分类数据
      classifyLevelList: [],
      // 显示上升下降按钮
      isShowButton: true,
      // 选中的分类等级
      chooseLevel: 0,
      changeOnSelect: true
    }
  },
  computed: {
    getDataLength() {
      return function(record) {
        if(record.level == 1) {
          return this.$refs.classifyRef.getData().length
        } else if(record.level == 2) {
          let levelTwo = this.$refs.classifyRef.getData().find(item => item.pkId == record.parent)
          if(levelTwo.children) {
            return levelTwo.children.length
          } else {
            return 0
          }
        } else {
          for(let i of this.$refs.classifyRef.getData()) {
            if(i.children) {
              for(let j of i.children) { 
                if(j.pkId == record.parent) {
                  if(j.children) {
                    return j.children.length
                  } else {
                    return 0
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      let res = await classApi.getAllByCategoryId()
      this.classifyList = this.getData(res.data.children)
      this.classifyLevelList = JSON.parse(JSON.stringify(this.classifyList))
    },
    // 格式化数据 disabled 编辑三分类时,只有一级分类没有二级分类,则不可选一级分类
    getData(data,disabled = false) {
      data.forEach((element) => {
        if(element.children && element.children.length > 0 && element.level == 2) {
          this.getData(element.children)
        } else {
          if(disabled && element.level == 2) {
            element.disabled = true
          } 
          delete element.children
        }
      })
      return data
    },
    // 搜索
    handleSearchClick() {
      this.isShowButton = this.queryParam.name ? false : true
      this.reloadTable()
    },
    handleAddClassClick() {
      this.title ='新增分类'
      this.chooseLevel = 0
      this.changeOnSelect = true
      this.init()
      this.knowledgeShow = true
    },
    // 编辑页面显示
    async handleUpdateClassifyClick(record) {
      this.title = '编辑分类'
      this.chooseLevel = record.level
      this.changeOnSelect = false
      if(record.level == 2) {
        this.classifyLevelList = JSON.parse(JSON.stringify(this.classifyList))
        this.classifyLevelList.forEach(element => {
          if(element.level == 2) {
            delete element.children
          }
        })
      }
      if(record.level == 3) {
        this.classifyLevelList = this.getData(JSON.parse(JSON.stringify(this.classifyList)), true)
      }
      let res = await this.api.findAllParentByCategoryId(record.pkId)
      let gategoryId 
      if(!res.data.parents) {
        gategoryId = []
      } else {
        gategoryId = getCategoryId(res.data.parents)
      }
      this.classForm = {
        pkId: record.pkId,
        name: record.name,
        parent: gategoryId,
        sort: record.sort
      }
      this.knowledgeShow = true
    },
    async handleOk() {
      if(!this.classForm.name) {
        this.$message.error("请输入分类名称");
        return
      }
      if((this.chooseLevel == 2 || this.chooseLevel == 3) && !this.classForm.parent.length) {
        this.$message.error("请选择上级分类");
        return
      }
      this.saveLoading = true
      let parentId = this.classForm.parent
      let res = await this.api.save({...this.classForm, parent: parentId.length ? parentId.reverse()[0] : null})
      if(res.code == 200) {
        this.reloadTable()
        this.handleCancel()
        this.saveLoading = false
      }
    },
    handleCancel() {
      this.knowledgeShow = false
      this.classForm = Object.assign({},this.$options.data().classForm)
    },
    handleJumpKnowledgeManage(record) {
      this.$router.push({
        path: '/knowledge/knowledgeManageList',
        query: {pkId: record.pkId}
      })
    },
     // 重新加载表格
    reloadTable() {
      this.$refs.classifyRef.loadData()
    }
  }
}
</script>

<style lang="less" scoped>
@gary:  #f8f8f8;
@white: #fff;
.rx-fit {
  padding: 40px!important;
  background: @gary;
  overflow-y: auto!important;
  display: block!important;
  .fit-header {
    .mainContent {
      width: 100%;
      .body {
        background: @white;
        padding: 10px 20px;
        .content {
          background: @white;

          button:first-child {
            margin-right: 20px;
          }

          >button {
            margin: 10px;
            margin-left: 0;
          }
        }
      }
    }
  }
  .table-style {
    padding: 20px;
    min-height: 400px;
    .clearBtn {
      background: none;
      color: #3294F7;
      text-shadow: none;
      padding: 0px 6px;
      border: none;
      box-shadow: none;
    }
  }

}
.show-other{
	width: 100%;
	animation:show-other-search 0.8s;
}
.form-item-style {
  margin: 5px 20px 5px 0;
}
.set-input {
  width:180px;
}
@keyframes show-other-search{
	0%{opacity:0;}
  50%{opacity:0.8;}
	100%{opacity: 1;}
}

</style>
<style scoped>
/deep/   .divdefault {
  position: inherit!important;
}
/deep/ .ant-table-row-expand-icon{
  position: relative;
    z-index: 100;
}
/deep/.ant-btn > .anticon + span {
  margin-left: 0;
}
 /deep/.ant-table-thead > tr > th {
  text-align: center; 
  height: 54px;
}
/deep/ .ant-table-tbody > tr > td {
  height: 54px;
}
/deep/ .ant-form{
  padding: 0;
}
/deep/ .gridContent{
  border: none;
}
/deep/ .gridContent .ant-table-content .ant-table-tbody>tr>td:nth-child(2) {
  padding-left: 60px!important;
}
</style>