<!-- 
    表格树形数据拖拽 本来使用el-table和sortablejs 但是奇怪的判断导致前端无法做跨级拖拽的限制。
  得由后端来限制，固使用drag-tree-table 但是这个插件构造比较简单，不是用table标签实现的
  如果产品要实现el-table上面的功能，需要自定义，有更好的方法，还请通知一声。
 -->
<template>
  <div class="doc-classifyMana-container">
    <div class="doc-classifyMana-top-zone">
      <el-button type="primary" @click="addClassify">添加分类</el-button>
      <el-input placeholder="分类名称" v-model="queryParams.KeyWord" @input="getclassifyData" clearable 
      style="width:500px;margin-left: 20px;">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <!-- <el-table style="border:1px solid #eaeaea;" ref="classifyTableRef"
    :data="classifyList" :row-class-name="tableRowClassName" row-key="id" :tree-props="{children:'child'}">
      <el-table-column prop="text" label="一级分类">
        <template slot-scope="scope">
          <span>{{scope.row.level==1?scope.row.text:''}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="text" label="二级分类">
        <template slot-scope="scope">
          <span>{{scope.row.level==2?scope.row.text:''}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="text" label="三级分类">
        <template slot-scope="scope">
          <span>{{scope.row.level==3?scope.row.text:''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div class="table-button">
            <span @click="configItem(scope.row)">权限配置</span>
            <span @click="edititem(scope.row)">编辑</span>
            <span @click="checkdeleteitem(scope.row)" style="margin-right: 0;color: #F56C6C;">删除</span>
          </div>
            </template>
      </el-table-column>
    </el-table> -->
    <dragTreeTable ref="dragTreeTableRef" :beforeDragOver="beforeDrag"
    :data="treeData" :onDrag="onTreeDataChange"
    hightRowChange resize border >
    <!-- onlySameLevelCanDrag -->
    </dragTreeTable>
    <!-- 添加分类弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="showAddClassifyDia" width="625px"
    append-to-body :close-on-click-modal="false" @close="resetForm">
      <div style="display: flex;flex-direction: column; align-items: center;margin-bottom: 35px;">
        <el-form :model="classifyForm" ref="classifyFormRef" label-width="80px">
          <el-form-item label="上级目录" prop="ParentId">
            <el-cascader v-model="classifyForm.ParentId" :options="noLevelThreeList" @change="selectParentId"
              placeholder="请选择上级目录（不选默认添加的是一级分类）" ref="parentIdCascaderRef"
              :props="{ value:'ClassifyId',label:'ClassifyName',children:'Children',checkStrictly:true,emitPath:false,disabled:'Disabled'}" 
              class="lastCatalogCascader" :disabled="this.dialogTitle.indexOf('编辑分类')!=-1" />
          </el-form-item>
          <el-form-item label="分类名称" prop="HelpDocClassifyName" :rules="{required:true,message:'分类名称不能为空',trigger:'blur'}">
            <el-input v-model="classifyForm.HelpDocClassifyName" placeholder="请输入分类名称" style="width: 337px;"
             maxlength="10"></el-input>
          </el-form-item>
        </el-form>
        <div style="margin-top: 40px;">
          <el-button type="primary" style="width:120px;margin-right:10px" @click="classifySave" size="medium">保存</el-button>
          <el-button  style="width:120px;" @click="showAddClassifyDia=false" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 设置权限弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="showPermissionDia" width="625px"
    append-to-body :close-on-click-modal="false" @close="resetPermissonForm">
      <div style="display: flex;flex-direction: column; align-items: center;margin-bottom: 35px;">
        <el-form :model="permissionForm" ref="permissionFormRef" label-width="80px">
          <el-form-item label="可见权限" prop="merchantIds">
            <el-select v-model="permissionForm.merchantIds" placeholder="请选择商家" 
            multiple style="width: 337px;" collapse-tags clearable filterable >
              <el-option :label="item.BusinessName" :value="item.EtaBusinessId" 
              v-for="item in merchantList" :key="item.merchantId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div style="margin-top: 40px;">
          <el-button type="primary" style="width:120px;margin-right:10px" @click="configSave" size="medium">保存</el-button>
          <el-button  style="width:120px;" @click="showPermissionDia=false" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import Sortable from "sortablejs";
import {assistanceDocInterence,businessCustomInterence} from "@/api/api.js"
import dragTreeTable from "drag-tree-table";
  export default {
    name:"docClassifyManage",
    components:{dragTreeTable},
    data() {
      // 表格头设置
      this.tableHeadList=[
        {
          type:"selection",
          title: '一级分类',
          field: 'ClassifyName',
          flex:1,
          align: 'center',
          formatter: (item) => {    
            return item.Level==1?item.ClassifyName:""
          }
        },
        {
          title: '二级分类',
          field: 'ClassifyName',
          // width: 200,
          flex:1,
          align: 'center',
          formatter: (item) => {
            return item.Level==2?item.ClassifyName:""
          }
        },
        {
          title: '三级分类',
          field: 'ClassifyName',
          // width: 200,
          flex:1,
          align: 'center',
          formatter: (item) => {
            return item.Level==3?item.ClassifyName:""
          }
        },
        {
          type: 'action',
          title: '操作',
          width: 260,
          // flex:1,
          align: 'center',
          actions:[
            {
              text: '权限配置',
              onclick: (item) => {
                // item是当前行的数据
                this.configClassify(item)
              },
              formatter: (item) => {
                return '<span class="table-button">权限配置</span>'
              }
            },
            {
              text: '编辑',
              onclick: (item) => {
                this.editClassify(item)
              },
              formatter: (item) => {
                return '<span class="table-button">编辑</span>'
              }
            },
            {
              text: '删除',
              onclick: (item) => {
                this.deleteClassify(item)
              },
              formatter: (item) => {
                return '<span class="table-button" style="margin-right: 0;color: #F56C6C;">删除</span>'
              }
            }
          ]
        }
      ]
      // 自定义字段替换
      this.custom_field={
        id: 'ClassifyId',
        order: 'Sort',
        lists: 'Children',
        parent_id: 'ParentId'
      }

      return {
        queryParams:{
          KeyWord:''
        },
        treeData:{
          columns:this.tableHeadList,
          lists:[],
          custom_field:this.custom_field
        },
        // 没有三级分类的分类数组，用于添加
        noLevelThreeList:[],
        // // 扁平化之后的数据
        // classifyListFlat:[],
        dialogTitle:"",
        showAddClassifyDia:false,
        classifyForm:{
          ParentId:0,
          HelpDocClassifyName:'',
          Level:0,
        },
        merchantList:[],
        showPermissionDia:false,
        permissionForm:{
          HelpDocClassifyId:0,
          merchantIds:[]
        },
      }
    },
    created(){
      this.getmerchantList()
      this.getclassifyData()
    },
    mounted(){
      this.$nextTick(()=>{
        // this.tableDropSet()
      })
    },
    methods: {
      getmerchantList(){
        businessCustomInterence.getBusinessList({PageSize:9999999,CurrentIndex:1}).then(res=>{
          if(res.Ret == 200){
            this.merchantList = res.Data.List||[]
          }
        })
      },
      getclassifyData(){
        assistanceDocInterence.getAssistanceClassifyList(this.queryParams).then(res=>{
          if(res.Ret == 200){
            this.treeData.lists = res.Data?res.Data.AllNodes||[]:[]
            this.noLevelThreeList = res.Data?res.Data.TwoLevelNodes||[]:[]
            this.treeData.lists.map(list=> {
              // 一级展开
              list.open=true
            })
            // console.log(this.treeData.lists);
          }
        })
      },
      // tableRowClassName({row,rowIndex}) {
      //   if( row.child && row.child.length>0 ){
      //     return 'has-child-row';
      //   }else{
      //     return '';
      //   }
      // },
      beforeDrag(dragItem,effectItem,type){
        if(type=='center'){
          // 放里面
          if((dragItem.Level-1)!=effectItem.Level) return false
        }else{
          //不放里面
          if(dragItem.Level!=effectItem.Level) return false
        }
        // return false
      },
      onTreeDataChange(list,dragItem){
        // console.log(list,dragItem,'arguments');
        // list - 拖拽后的数据 dragItem-拖拽的项
        let ClassifyId,PrevClassifyId,NextClassifyId,ParentClassifyId=0
        // 在拖拽后的数据中找到拖拽项对应的位置
        const findDraggedItem=(list)=>{
          let itemIndex = list.findIndex(it => it.ClassifyId == dragItem.ClassifyId)
          if(itemIndex!=-1){
            if(itemIndex==0){
              PrevClassifyId=0
            }else{
              PrevClassifyId = list[itemIndex-1].ClassifyId
            }
            if(itemIndex==(list.length-1)){
              NextClassifyId=0
            }else{
              NextClassifyId = list[itemIndex+1].ClassifyId
            }
            ClassifyId = dragItem.ClassifyId
            ParentClassifyId = dragItem.ParentId
            console.log({
              ClassifyId,ParentClassifyId,PrevClassifyId,NextClassifyId
            });
            assistanceDocInterence.moveAssistanceClassify({
              ClassifyId,ParentClassifyId,PrevClassifyId,NextClassifyId
            }).then(res=>{
              if(res.Ret == 200){
                this.$message.success("移动分类成功")
                this.getclassifyData()
              }
            })
          }else{
            list.map(li => {
              li.Children && li.Children.length>0 && findDraggedItem(li.Children)
            })
          }
        }
        findDraggedItem(list)
      },
      // tableDropSet(){
      //   const tbody = this.$refs.classifyTableRef.$el.querySelector(
      //     ".el-table__body-wrapper > table > tbody"
      //   );
      //   const _this = this;
      //   Sortable.create(tbody, {
      //     animation: 150, 
      //     onStart(evt){
      //       if(_this.classifyListFlat && _this.classifyListFlat.length>0){
      //         return 
      //       }else{
      //         _this.flatClassifyList(_this.classifyList,0)
      //       }
      //       console.log(_this.classifyListFlat);
      //     },
      //     onEnd({ newIndex, oldIndex }) {
      //       console.log({ newIndex, oldIndex });
      //       if(newIndex == oldIndex) return 
      //       const oldRow = _this.classifyListFlat[oldIndex]
      //       const newRow = _this.classifyListFlat[newIndex]
      //       console.log(oldRow,newRow);
      //       _this.$message.success("拖拽成功")
      //       _this.getclassifyData()
      //     },
      //     onMove({ dragged, related }){
      //       console.log(dragged.rowIndex, related.rowIndex);
      //       const oldRow = _this.classifyListFlat[dragged.rowIndex]
      //       const newRow = _this.classifyListFlat[related.rowIndex]
      //       console.log(oldRow.level,newRow.level);
      //       if (oldRow.level !== newRow.level) {
      //         return false // 不允许不同级的拖动
      //       }
      //     }
      //   });
      // },
      // flatClassifyList(list,parentId){
      //   for (let i = 0; i < list.length; i++) {
      //     const element = list[i];
      //     const lastElementId = i==0?0:list[i-1].id
      //     const nextElementId = i==(list.length-1)?0:list[i+1].id
      //     this.classifyListFlat.push({id:element.id,lastElementId,nextElementId,parentId,level:element.level})
      //     if(element.child && element.child.length>0){
      //       this.flatClassifyList(element.child,element.id)
      //     }
      //   }
      // },
      // 添加分类
      addClassify(){
        this.dialogTitle="添加分类"
        this.showAddClassifyDia=true
      },
      // 编辑分类
      editClassify(item){
        this.classifyForm={
          ParentId:item.ParentId,
          HelpDocClassifyId:item.ClassifyId,
          HelpDocClassifyName:item.ClassifyName
        }
        this.dialogTitle="编辑分类"
        this.showAddClassifyDia=true
      },
      selectParentId(value){
        this.classifyForm.Level = this.$refs.parentIdCascaderRef.getCheckedNodes()[0].data.Level
      },
      deleteClassify(item){
        this.$confirm('是否确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          assistanceDocInterence.deleteAssistanceClassify({ClassifyId:item.ClassifyId}).then(res=>{
            if(res.Ret == 200){
              this.$message.success("删除分类成功")
              this.getclassifyData()
            }
          })
        }).catch(()=>{})
      },
      // 保存
      classifySave(){
        this.$refs.classifyFormRef.validate(valid=>{
          if(valid){
            console.log(this.classifyForm);
            if(this.classifyForm.HelpDocClassifyId){
              //编辑
              assistanceDocInterence.editAssistanceClassify(this.classifyForm).then(res=>{
                if(res.Ret == 200){
                  this.$message.success(this.dialogTitle+"成功")
                  this.showAddClassifyDia=false
                  this.resetForm()
                  this.getclassifyData()
                }
              })
            }else{
              //新增
              assistanceDocInterence.addAssistanceClassify({...this.classifyForm}).then(res=>{
                if(res.Ret == 200){
                  this.$message.success(this.dialogTitle+"成功")
                  this.showAddClassifyDia=false
                  this.resetForm()
                  this.getclassifyData()
                }
              })
            }
          }
        })
      },
      resetForm(){
        this.classifyForm={
          ParentId:0,
          HelpDocClassifyName:'',
          Level:0
        }
        this.$refs.classifyFormRef.clearValidate()
      },
      //权限配置
      configClassify(row){
        this.permissionForm={
          HelpDocClassifyId:row.ClassifyId,
          merchantIds:row.VisibleBusinessIds?row.VisibleBusinessIds.split(',').map(element => {
            return parseInt(element)
          }):[]
        }
        // console.log(this.permissionForm.merchantIds);
        this.dialogTitle="设置权限"
        this.showPermissionDia=true
      },
      resetPermissonForm(){
        this.permissionForm={
          HelpDocClassifyId:0,
          merchantIds:[]
        }
        this.$refs.permissionFormRef.clearValidate()
      },
      configSave(){
        assistanceDocInterence.editAssistanceClassifyVisible({
          HelpDocClassifyId:this.permissionForm.HelpDocClassifyId,
          VisibleBusinessIds:this.permissionForm.merchantIds.join(',')
        }).then(res=>{
          if(res.Ret == 200){
            this.$message.success("设置成功")
            this.showPermissionDia=false
            this.resetPermissonForm()
            this.getclassifyData()
          }
        })
      }
    },
  }
</script>

<style lang="scss" scoped>
.doc-classifyMana-container{
  background-color: white;
  min-height: calc(100vh - 110px);
  padding: 30px;
  box-sizing: border-box;
  border: solid 1px #ECECEC;
  .doc-classifyMana-top-zone{
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
</style>
<style lang="scss">
.lastCatalogCascader{
  width: 337px;
  .el-input{
    width: 337px;
  }
}
.has-child-row {
    background-color: #f2f6fa!important;
}
.table-button{
    color:#4099ef; 
    cursor: pointer;
    margin-right: 10px;
  }
</style>