<template>
  <!-- 架构主页面 -->
  <div class="framework height_100">
    <el-container>
      <el-header>
        <div style="display: flex;justify-content: space-between;align-items:center;width:100%;padding:0 10px;">
          <div>
            <p>{{ row.type == 1 ? '产品类别名称：' : '产品名称：' }}{{ row.name }}</p>
          </div>
          <div>
            <el-button type="primary" size="small" @click="handleImport">导 入</el-button>
          </div>
        </div>
      </el-header>
      <el-container>
        <el-aside width="400px" style="height: 100%;padding: 10px;">
          <div style="display:flex;margin-bottom:10px;">
            <el-input v-model="productName" size="small" placeholder="请输入名称" style="margin-right:10px;"></el-input>
            <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
            <el-button v-if="row.type == '1'" type="primary" size="small" @click="handleAppend">新增分类节点</el-button>
            <el-dropdown v-else split-button type="primary" size="small" @click="handleAppend">
              <span>新增分类节点</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleCopy">复制分类架构节点</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div>
            <el-tree ref="tree" :data="treeData" :props="defaultProps" @node-click="handleNodeClick"
              :default-expanded-keys="expandedKeys">
              <!-- <el-tree ref="tree" :data="treeData" :props="treeProps" :current-node-key="parentId" @node-click="handleNodeClick" node-key="id" :default-checked-keys="expandedKeys" :highlight-current="true" :default-expanded-keys="expandedKeys" :expand-on-click-node="false"> -->
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span style="padding-left: 10px;">
                  <el-button type="text" size="mini" @click.stop.native="nodeEvent(data, node,'append')">
                    <el-tooltip class="item" effect="dark" content="添加子级分类节点" placement="bottom-start">
                      <i class="el-icon-plus" style="font-size: 16px;"></i>
                    </el-tooltip>
                  </el-button>
                </span>
                <span style="padding-left: 10px;">
                  <el-button type="text" size="mini" @click.stop.native="nodeEvent(data, node,'edit')">
                    <el-tooltip class="item" effect="dark" content="编辑分类节点" placement="bottom-start">
                      <i class="el-icon-edit-outline" style="font-size: 16px;"></i>
                    </el-tooltip>
                  </el-button>
                </span>
                <span style="padding-left: 10px;">
                  <el-button type="text" size="mini" @click.stop.native="nodeEvent(data, node,'remove')">
                    <el-tooltip class="item" effect="dark" content="删除分类节点" placement="bottom-start">
                      <i class="el-icon-delete" style="font-size: 16px;"></i>
                    </el-tooltip>
                  </el-button>
                </span>
                <span style="padding-left: 10px;">
                  <el-button type="text" size="mini" @click.stop.native="nodeEvent(data, node,'copy')">
                    <el-tooltip class="item" effect="dark" content="复制分类架构节点" placement="bottom-start">
                      <i class="el-icon-document-copy" style="font-size: 16px;"></i>
                    </el-tooltip>
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-aside>
        <el-container>
          <el-main>
            <div v-if="getPathName()">
              <p>所属架构：{{ getPathName() }}</p>
            </div>
            <component :is="componentType" :tableData="tableData" :queryParams="queryParams" @option="handleOption"
              @on-sort="handleSort">
            </component>
          </el-main>
          <el-footer class="pagination">
            <el-pagination background layout="total, prev, pager, next, jumper" :current-page.sync="queryParams.current"
              :page-size.sync="queryParams.size" @current-change="handleCurrentChange" :total="total">
            </el-pagination>
          </el-footer>
        </el-container>
      </el-container>
    </el-container>

    <classifyNode ref="classifyNode" :treeDataPath="treeDataPath" @isSuccess="handleSuccess"></classifyNode>
    <myImageViewer v-if="showImg" :on-close="closeViewer" :src="imgSrc"></myImageViewer>
    <node-Copy ref="nodeCopy" @submit="submitNode"></node-Copy>
  </div>
</template> 

<script>
import frameworkTable from './view/table.vue'
import classifyNode from '../dialog/classifyNode.vue';
import nodeCopy from '@/views/components/dialog/nodeCopy.vue';
export default {
  props: {
    name: {
      type: String
    },//产品名称或者是产品类别名称
    id: {},//产品id或者是产品类别id
    categoryId: {},//产品类别Id
    type: {},//类型1是产品类别，2是产品
    projectId:{
      default:null
    }
  },
  components: {
    frameworkTable,
    classifyNode,
    nodeCopy
  },
  data() {
    return {
      // 控制显示哪一种视图
      searchOption: {},
      // 父级id
      parentId: '0',
      // 显示视图
      componentType: 'frameworkTable',
      // 查询产品名称数据
      productName: '',
      // 树形组件的数据源
      treeData: [],
      // 树形组件的显示及其子级
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      // 架构路径数组
      treeDataPath: [],
      // 查询架构表格数据字段
      queryParams: {
        current: 1,
        size: 10,
      },
      // 架构表格数据总条数
      total: 0,
      // 架构表格数据源
      tableData: [

      ],
      // 节点的展开
      expandedKeys: [],
      // 排序
      sort: [],
      //展示图片
      showImg: false,
      //图片地址
      imgSrc: '',
      // 当前节点的id
      nodeId: null,
    }
  },
  computed: {
    row() {
      return {
        name: this.name,
        categoryId: this.categoryId,
        id: this.id,
        type: this.type
      }
    }
  },
  async mounted() {
    // 请求架构路径
    this.getPath()
    // 请求数据（左侧tree）
    await this.getList(true)
    // 请求列表的数据（右侧table）
    this.getTableList()

  },
  methods: {
    //获取排序字段// 子组件table排序
    handleSort({ column, prop, order, }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 1
      //1表示展开行2表示基础表格
      this.getTableList()
    },
    // 专利导入
    handleImport() { },
    // 子组件传来的消息,新增成功、编辑成功
    handleSuccess(val) {
      this.getList()
      this.getTableList()
      this.getPath()
    },
    //请求新数据后保持刷新前所点击的节点高亮并展开
    handleNode() {
      this.expandedKeys = []
      if (sessionStorage.getItem('parentId')) {
        this.parentId = JSON.parse(sessionStorage.getItem('parentId'))
        this.expandedKeys.push(this.parentId)
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.parentId)
          this.queryParams.structureId = this.parentId
          this.getList()
        })
      }
    },
    // 子组件传来的值
    async handleOption({ val, row }) {
      if(!(await this.$permission.producePermission(this.id,this.type))){
        this.$showPermissionDialog()
        return false
      }
      // console.log(val, row);
      switch (val) {
        case '0'://编辑
          this.$refs.classifyNode.open(row, this.row)
          break;
        case '1'://预览图片
          this.commandPackage(row)
          break;
        case '2'://删除
          this.deleNode(row)
          break;

        default:
          break;
      }
    },
    // 预览图片
    commandPackage(row) {
      this.imgSrc = this.$commonJS.checkViewer(row.systemFileList[0].guid)
      this.showImg = true
    },
    //关闭预览图片
    closeViewer() {
      this.showImg = false
    },
    // 删除
    deleNode(row) {
      this.$confirm('此操作将删除当前节点及其下属节点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口
        let params = [row.id]
        this.$api.deleteTreeNode(params).then(res => {
          if (res.code == 200) {
            this.getList()
            this.parentId = '0'
            this.getTableList()
            this.$message.success('删除该当前分类节点及所属子级分类节点成功!');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 按钮新增分类节点
    async handleAppend() {
      if(!(await this.$permission.producePermission(this.id,this.type))){
        this.$showPermissionDialog()
        return false
      }
      this.$refs.classifyNode.open(null, this.row)
    },
    // 根据产品名称查询产品
    async handleQuery() {
      await this.getList()
      // 遍历返回的数据，对有相同搜索值进行高亮
      this.getChildrenHeight(this.treeData)

    },
    // 递归查询每一个children是否有与搜索相同的字段
    getChildrenHeight(data) {
      data.forEach(item => {
        if (item.name.indexOf(this.productName) != -1) {
          item.name.replace(this.productName, `<span style="color:red;font-weight:700;">${this.productName}</span>`)
        }
        if (item.child && item.child.length > 0) {
          this.getChildrenHeight(item.child)
        } else {
          return
        }
      })

    },
    async nodeEvent(data, node,eventName){
      if(!(await this.$permission.producePermission(this.id,this.type))){
        this.$showPermissionDialog()
        return false
      }
      this[eventName](data,node)
    },
    // 树节点上的新增
    append(data, node) {
      this.$refs.classifyNode.open(null, this.row, data)
      // console.log(data, node);
    },
    // 树节点上的编辑
    edit(data, node) {
      this.$refs.classifyNode.open(data, this.row)
      // console.log(data, node);
    },
    // 树节点上的删除
    remove(data, node) {
      this.deleNode(data)
    },
    // 树节点上复制分类架构
    copy(data, node) {
      this.nodeId = data.id
      this.openNodeCopy()
    },
    // 树节点点击事件
    handleNodeClick(data, node) {
      // console.log(data, node);
      if (data.child && data.child.length > 0) {
        this.parentId = data.id
        this.getTableList()
      }
    },
    // 按钮复制分类架构
    async handleCopy() {
      if(!(await this.$permission.producePermission(this.id,this.type))){
        this.$showPermissionDialog()
        return false
      }
      this.nodeId = null
      this.openNodeCopy()
    },
    openNodeCopy() {
      var form = {
        toType: '2',//类型：1产品类别，2产品，3技术分类，4自定义树
        toTypeId: this.row.id,//产品id
        toNodeId: this.nodeId,//放到哪一个节点下面
        fromType: '1',//类型：1产品类别，2产品，3技术分类，4自定义树
        fromTypeId: this.row.categoryId,//类别id
      }
      this.$refs.nodeCopy.open(form)
    },
    submitNode(val) {
      this.getList()
      this.getTableList()
    },
    // 请求数据（tree）
    async getList(type) {
      let params = {
        name: this.productName,//事件名称
        type: this.row.type,//类型：1产品类别，2产品，3技术分类，4自定义树
        typeId: this.row.id,//产品或类别id
        projectId:this.projectId
      }
      await this.$api.queryTreeNodeTree(params).then(res => {
        if (res.code == 200) {
          this.treeData = res.data.data
          if(type){
            if(this.treeData.length>0){
              this.parentId = this.treeData[0].parentId
            }
          }
          
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    //准备生成检索式数据
    getSearch() {
      let arr = []
      let arr1 = ['name', 'type', 'typeId', 'parentId']
      arr1.forEach(item => {
        let label = ''
        if (item == 'name') {//产品名称
          label = this.productName
        } else if (item == 'type') {
          label = this.row.type
        } else if (item == 'typeId') {
          label = this.row.id
        } else {
          label = this.parentId ? this.parentId : '0'
        }
        let obj = {
          searchValue: {
            label: label
          },
          type: '1',
          value: item,
        }
        arr.push(obj)
      })
      return arr
    },
    // 生成检索式
    search(val) {
      let params = {}
      val.forEach(item => {
        if (item.type == 3) {
          params[item.value] = item.searchValue.map(itemValue => {
            return itemValue.value
          })
        } else {
          params[item.value] = item.searchValue.label
        }
      })

      
      // 返回字符串
      this.searchOption.searchQuery = this.$commonJS.objectToString(params)

    },
    // 请求列表数据
    getTableList() {
      let val = this.getSearch()
      this.search(val)

      let params = {
        ...this.queryParams,//分页
        ...this.searchOption,//检索条件
        orderDTOList: this.sort,//排序
        // name: this.productName,//事件名称
        // type: this.row.type,//类型：1产品类别，2产品，3技术分类，4自定义树
        // typeId: this.row.id,//产品或类别id
      }
      this.$api.queryTable(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      }).catch(err => {
        this.tableData = []
        this.total = 0
        this.$message.error(err.message)
      })
    },
    getPathName(){
      var obj = this.treeDataPath.find(item=>{
        return item.id == this.parentId
      })
      if(obj){
        if(obj.pathName == '/'){
          return ''
        }
        return obj.pathName
      }
      return ''
    },
    // 请求架构路径
    getPath() {
      let params = {
        type: this.row.type,//区分产品架构、自定义树等
        typeId: this.row.id,//产品或类别id
      }
      this.$api.queryTreePath(params).then(res => {
        if (res.code == 200) {
          this.treeDataPath = res.data.data
        }
      }).catch(err => {
        this.treeDataPath = []
        this.$message.error(err.message)
      })
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getTableList()
    },
  },
}
</script>

<style lang="scss">
.framework {
  .el-divider--horizontal {
    margin: 15px 0,
  }

  .el-dropdown .el-button-group {
    display: flex;
  }
}
</style>
<style lang="scss" scoped>
.framework {
  width: 100%;
}
</style>