<template>
  <div>
          <!-- <div v-else> -->
            <div style="display: flex;margin: 10px 10px;">
               <el-input v-model="queryParams.structureName" size="small" placeholder="请输入产品名称" style="margin-right: 10px;"></el-input>
              <el-button type="primary" size="small" @click="getList(false)"> 查询 </el-button>
              <el-button type="primary" size="small" @click="handleAppen()" v-if="!productsRow.structureId"> 新增分类节点 </el-button>
            </div>
          <!-- lazy :load="loadNode" 懒加载 -->
            <!-- <el-tree @node-click="handleNodeClick" node-key="id" lazy :load="loadNode" :highlight-current="true"> -->
            <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="append(data,node)">
                    <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="edit(data,node)">
                    <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="remove(data,node)">
                    <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>
            </el-tree>
          <!-- </div> -->
          <!-- 弹窗 -->
          <el-dialog :title="title"
            :visible.sync="visible"
            width="500"
            :close-on-click-modal="false"
            :before-close="close">
            <el-form :rules="rules" ref="frameworkForm" :model="frameworkForm" label-width="120px">
                <el-form-item label="所属产品名称 " prop="productName">
                  <el-input v-model="frameworkForm.productName" disabled placeholder="请输入产品名称"></el-input>
                </el-form-item>
                <el-form-item :label="frameworkForm.id?'上级产品架构':'所属架构'" prop="parentPath">
                  <!-- <el-input v-model="frameworkForm.parentPath" placeholder="请选择上级架构"></el-input> -->
                  <el-select v-model="frameworkForm.parentId" @change="getPatentData" placeholder="请选择" style="width: 100%;" :disabled="frameworkForm.id?false:true">
                    <el-option key="0" label="/" :value='number' ></el-option>
                    <!--  v-for="item in options.filter(item=>{ return item.id!= frameworkForm.id})" -->
                    <el-option
                      v-for="item in options.filter(item=>{return !item.path.includes(frameworkForm.id)})"
                      :key="item.path"
                      :label="item.pathStructureName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="产品架构名称 " prop="structureName">
                  <el-input v-model="frameworkForm.structureName" placeholder="请输入产品架构名称"></el-input>
                </el-form-item>
                <el-form-item label="产品架构图片 ">
                  <el-upload ref="upload"  action="#" :auto-upload="false"  :on-change="handleChange"  list-type="picture" :show-file-list="false">
                  <span v-if="frameworkForm.pictures&&frameworkForm.pictures.length>0" class="avatar">
                    <span class="deleteImg">
                    <span> 
                      <i class="el-icon-zoom-in" @click.stop="handlePictureCardPreview"></i>
                      <i class="el-icon-delete" @click.stop="handleRemove"></i></span>
                    </span>
                    <el-image ref="image" style="width:100%;height: 100%;" :src="frameworkForm.pictures[0].id? $p + frameworkForm.pictures[0].url:frameworkForm.pictures[0].url" :preview-src-list="frameworkForm.pictures?frameworkForm.pictures.map(item=>{return item.id? $p + item.url:item.url}):[]"></el-image>
                  </span>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>
                <el-form-item label="产品架构说明">
                  <el-input v-model="frameworkForm.remark" type="textarea" placeholder="请输入产品说明"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="close">取 消</el-button>
              <el-button type="primary" @click="sure">确 定</el-button>
            </span>
        </el-dialog>
  </div>
</template>

<script>

export default {
  props:['productsRow','isDelete','tableRow','isEdit'],
  data() {
    return {
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'structureName',
      },
      title:'',
      queryParams: {
        structureId:0,
      },
      query:{},
      frameworkForm: {
      },
      file:[],
      options:[],
      rules: {
        productName:[{ required: true, message: '请输入产品名称', trigger: 'blur' },],
        structureName:[{ required: true, message: '请输入产品架构名称', trigger: 'blur' },],
      },
      visible: false,
      parentId:null,
      expandedKeys: [],
      parentName: '',
      number:0,
    }
  },
  created() {},
  computed: {},
  watch: {
    isDelete() {
      this.remove(this.tableRow)
    },
    isEdit() {
      this.edit(this.tableRow)
    },
  },
  async mounted() { 
    if(this.productsRow.structureId){
      this.queryParams.structureId = this.productsRow.structureId
    }
    await this.getList()
    this.handleNode()
    this.parentPath()
    this.frameworkForm.productName=this.productsRow.productName
  },
  methods: {
   async getList(isClick) {//产品的id
      this.queryParams.productId = this.productsRow.id//产品id
      if(!isClick){
        if (this.queryParams.structureName) {//查询名称
          this.queryParams.structureId=0
        }
        if(this.productsRow.structureId){
          this.queryParams.structureId = this.productsRow.structureId
        }
      }
     await this.$api.queryStructures(this.queryParams).then(res => {
        if (res.code == 200) {
          if (this.queryParams.structureId) {
            if(this.productsRow.structureId && !isClick){
              this.treeData = [res.data]
            }
            if(!res.data){
              res.data = {
                children:[]
              }
            }
            if(!isClick){
              res.data = {
                children:[res.data]
              }
            }
            this.$emit('table',res.data)
            this.queryParams.structureId=0
          } else {
            let a = JSON.parse(sessionStorage.getItem('parentId'))
            if (!a || this.queryParams.structureId == 0) {
              this.$emit('table', res.data)
              sessionStorage.removeItem("parentId");
            } 
            this.treeData = res.data.children
          }
          
        }
      })
    },
    // 路径
    parentPath() {
      let a = {
        productId: this.productsRow.id,
        structureId:this.productsRow.structureId?this.productsRow.structureId:null,
      }
      this.$api.queryPathStructureName(a).then(res => {
        if (res.code==200) {
          this.options = res.data
        }
      })
    },
    // 左侧树形结构事件
    handleNodeClick(data, node, tree) { 
      sessionStorage.setItem('parentId',JSON.stringify(data.id))
      this.queryParams.structureId = data.id
      this.getList(true)
    },
    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()
        })
      }
    },
    // 新增一级架构
    handleAppen(val) { 
      this.title = "新增分类节点"
      this.frameworkForm.parentId = 0
      this.frameworkForm.parentPath='0'
      this.frameworkForm.productName=this.productsRow.productName
      this.visible=true
    },
    // 新增子架构
    append(data,node) {
      this.title="新增子级分类节点"
      this.frameworkForm.parentId = data.id // 父级架构的parentId
      this.frameworkForm.productName = this.productsRow.productName
      this.frameworkForm.parentPath=data.path
      this.visible=true
    }, 
     sure() {
       this.$refs.frameworkForm.validate(valid => {
         if (valid) {
          var formData = new FormData()
          if (this.file) {
            for (var i = 0; i < this.file.length; i++) {
              formData.append("files", this.file[i]);
            }
           }
           this.frameworkForm.productId = this.productsRow.id//产品id
          formData.append('jsons', JSON.stringify(this.frameworkForm))
           if (this.frameworkForm.id) {
             this.$api.updateStructures(formData).then(async res => {
                if (res.code == 200) {
                  this.$message.success("编辑分类节点成功")
                  this.queryParams.structureId=0
                  await this.getList()
                  this.handleNode()
                  if  (this.tableRow.parentId!=this.frameworkForm.parentId||this.tableRow.structureName!=this.frameworkForm.structureName) {
                    this.parentPath()
                  }
                  this.close()
                }
             }).catch(err => {
                this.$message.error(err.message)
              })
          } else {
             this.$api.addNewStructures(formData).then(async res => {
              if (res.code == 200) {
                this.queryParams.structureId=0
                this.$message.success("新增分类节点成功")
                await this.getList()
                this.handleNode()
                this.parentPath()
                this.close()
              }
             }).catch(err => {
              this.$message.error(err.message)
            })
          }
          
        }
      })
    },
    close() {
      this.file = []
      this.$refs.upload.clearFiles()
      this.frameworkForm={}
      this.visible = false
    },
    // 编辑
    edit(val,node) {
      for (let k in val) {
        this.tableRow[k]=val[k]
      }
      this.frameworkForm = JSON.parse(JSON.stringify(val))
      this.frameworkForm.productName = this.productsRow.productName
      this.title="编辑分类节点"
      this.visible=true
    },
    //编辑获取父级数据
    getPatentData(val) {
      if (val != 0) {
        var arr = this.options.find(item => {
          return item.id == val
        })
        this.frameworkForm.parentPath = arr.path
      } else {
        this.frameworkForm.parentPath = '0'
      }
      
    },
    // 删除架构
    remove(val) {
      this.$confirm('此操作将删除该当前分类节点及所属子级分类节点，不可恢复，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.$api.deleteStructures({id:val.id}).then(async res => {
              if (res.code == 200) {
                this.$message.success("删除该当前分类节点及所属子级分类节点成功")
                await this.getList()
                this.handleNode()
                this.parentPath()
              }
            }).catch(err => {
              this.$message.error(err.message)
            })
          }).catch(() => {
            this.$message.info("已取消删除")
      });
    },
    //  上传图片
    handlePictureCardPreview(file) {
        this.$refs.image.showViewer = true
    },
    handleRemove() {
      this.file = []
        this.frameworkForm.pictures = []
    },
    handleChange(file, fileList) {
      this.$set(this.frameworkForm,'pictures', [{url:file.url}])
      this.file=[file.raw]
    },
  },
}
</script>

<style lang="scss" scoped>
.avatar-uploader-icon {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
 .avatar {
  
  position: relative;
    width: 148px;
    height: 148px;
    display: block;
  }
  .avatar:hover .deleteImg {
    display: block;
}
.deleteImg {
  display: none;
  font-size: 30px;
  width: 148px;
  height: 148px;
  background-color:black;
	opacity: 0.6; 
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  margin: auto;
  z-index: 999;
}
.deleteImg span i{
  margin-left: 10px;
  color: #fff;
}
.deleteImg span{
  display: flex;
  align-items:center;/*垂直居中*/
  justify-content: center;/*水平居中*/
  width:100%;
  height:100%;
}
</style>