<template>
  <el-container>
    <el-dialog
      id="palRelationAddress"
      :title="title"
      :visible.sync="dialogVisible"
      width="800px"
      :modal-append-to-body=false
      :destroy-on-close=true
      :append-to-body=true
      :close-on-click-modal=false
      :before-close="handleClose">
      <template>
        <div v-if="dialogVisible" style="width:100%; height: 400px; border:1px solid #f2f2f2;">
          <div class="div-left" :style="{'width': (relationType == 'file' ? '373px' : '249px')}">
            <div style="width: 100%;height: 32px;">
              <el-autocomplete
                v-model="treeSearchKey"
                size="small"
                :fetch-suggestions="treeSearch"
                @select="treeSearchSelect"
                suffix-icon="el-icon-search"
                placeholder="快速查询"
                :trigger-on-focus=false
                :style="{'width': (relationType == 'file' ? '373px' : '249px')}"
              >
                <template slot-scope="{ item }">
                  <el-tooltip class="item" placement="bottom-start">
                    <div slot="content">{{item.pathName}}</div>
                    <span>{{ item.name }}</span>
                  </el-tooltip>
                </template>
              </el-autocomplete>
            </div>
            <div>
              <div style="height: 368px;overflow: auto;">
                <div style="margin: 0px;">
                  <el-tree
                    ref="tree"
                    empty-text="无数据"
                    :expand-on-click-node=false
                    :props="treeProps"
                    :show-checkbox="relationType == 'file' && multiple"
                    :check-strictly=true
                    :highlight-current=true
                    @node-expand="expandNode"
                    @node-collapse="closeNode"
                    @check-change="handleNodeCheckChange"
                    node-key="id"
                    lazy
                    :load="loadNode"
                    @node-click="handleNodeClick">
                    <span slot-scope="{node, data}">
                      <i class="awsui-iconfont tree-content-icon tree-content-icon-padding" :style="{'color': node.data.icon.color}" v-html="node.data.icon.icon"></i>
                      <span>{{node.label}}</span>
                    </span>
                  </el-tree>
                </div>
              </div>
            </div>
          </div>
          <div v-if="relationType != 'file'" class="div-middle">
            <div style="width: 100%;height: 32px;">
              <el-input
                size="small"
                placeholder="快速查询"
                suffix-icon="el-icon-search"
                v-model="shapeSearchKey"
                @input="shapeSearch"
                width="249px">
              </el-input>
            </div>
            <div>
              <div style="height: 368px;overflow: auto;">
                <div style="margin: 0px;">
                  <template v-if="multiple">
                    <el-checkbox-group style="margin: 5px 0px 5px 5px;" v-model="shapeChecked" @change="handleChangeCheckShape">
                      <el-checkbox class="checkbox-item" v-for="item in shapeData" :label="item.id" :key="item.id" :disabled="item.isDisabled">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                  </template>
                  <template v-else>
                    <el-radio-group style="margin: 5px 0px 5px 5px;" v-model="shapeSelected" @change="handleChangeRadioShape">
                      <el-radio class="redio-item" v-for="item in shapeData" :label="item.id" :key="item.id" :disabled="item.isDisabled">{{item.name}}</el-radio>
                    </el-radio-group>
                  </template>
                </div>
              </div>
            </div>
          </div>
          <div class="div-right" :style="{'width': (relationType == 'file' ? '373px' : '249px')}">
            <div style="height: 100%;">
              <template>
                <el-table
                  :data="tableData"
                  :show-header=false
                  empty-text="请在左侧选择数据"
                  size="mini"
                  height="400px"
                  style="width: 100%">
                  <el-table-column
                    prop="name"
                    label="名称">
                  </el-table-column>
                  <el-table-column
                    prop="address"
                    label="操作"
                    width="40">
                    <template slot-scope="scope">
                      <div class="icon-delete-display">
                        <i class="iconfont" style="cursor: pointer;" @click="remove(scope.row.id)">&#xe644;</i>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </div>
          </div>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <awsui-button class="button-general-color" type="primary" @click="submit">确定</awsui-button>
        <awsui-button @click="cancel">取消</awsui-button>
      </span>
     </el-dialog>
  </el-container>
</template>

<script>
    import awsuiAxios from "../../../../awsuiAxios";

    export default {
      name: "PalRelationAddress",
      props: {
        visible: {
          type: Boolean,
          default: false
        },
        relationType: {// 关联组件类型，shape/file，关联形状/文件，默认形状
          type: String,
          default: 'shape'
        },
        multiple: {// 选值类型，单选single，多选multiple，默认单选
          type: Boolean,
          default: false
        },
        title: {// 标题
          type: String,
          default: ''
        },
        selectFileId: {// 选择的文件id，多个以逗号分隔
          type: String,
          default: ''
        },
        selectShapeId: {// 选择的形状id，多个以逗号分隔
          type: String,
          default: ''
        },
        wsId: {// 资产库ID
          type: String,
          default: '',
          required: true
        },
        teamId: {// 小组ID
          type: String,
          default: ''
        },
        categorys: {// 建模大类,多个则逗号分隔
          type: String,
          default: ''
        },
        methods: {// 建模分类，多个则逗号分隔，空值默认可选所有建模方法数据，非空则只能选择范围内的数据，数据显示不控制
          type: String,
          default: ''
        },
        rootId: {// 指定根节点，为空则查询根节点
          type: String,
          default: ''
        }
      },
      data() {
        return {
          dialogVisible: false,
          pid: '',
          shapeSearchKey: '',
          shapeChecked: [],
          shapeSelected: '',
          shapeRecords: {},
          treeProps: {
            label: 'name',
            isLeaf: 'leaf'
          },
          tableData: [],
          shapeData: [],
          shapeTempData: [],
          treeSearchKey: '',
          timeout:  null,
          result: [],// [{id:xxx,versionId:xxx,name:xxxx,children:[{shapeId:xxx,name:xxx},{shapeId:xxx,name:xxx}]}]
        };
      },
      created() {
      },
      methods: {
        clearAllParam() {
          this.pid = '';
          this.shapeSearchKey = '';
          this.shapeChecked = [];
          this.shapeSelected = '';
          this.shapeRecords = {};
          this.tableData = [];
          this.shapeData = [];
          this.shapeTempData = [];
          this.treeSearchKey = '';
          this.timeout = null;
          this.result = [];
        },
        shapeSearch() {// 形状搜索
          if (this.shapeSearchKey && this.shapeSearchKey.trim() != '') {
            const key = this.shapeSearchKey.trim().toLocaleLowerCase();
            const shapeData = [];
            for (let i = 0; i < this.shapeTempData.length; i++) {
              const shape = this.shapeTempData[i];
              if (shape.name != '') {
                let name = (shape.name + '').toLocaleLowerCase();
                if (name.indexOf(key) != -1) {
                  shapeData.push(JSON.parse(JSON.stringify(shape)));
                }
              }
            }
            this.shapeData = shapeData;
          } else {
            this.shapeData = JSON.parse(JSON.stringify(this.shapeTempData));
          }
        },
        treeSearchSelect(item) {
          this.queryTreeByIdAndPath(item.id, item.path);
        },
        treeSearch(key, cb) {
          const that = this;
          if (key != undefined && key.trim() != '') {
            const data = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_search',
                wsId: that.wsId,
                teamId: that.teamId,
                categorys: that.categorys,
                rootId: that.rootId,
                name: key
              }
            };
            // 查询数据
            awsuiAxios.post(data).then(function (ro) {
              if (ro.result == 'ok') {
                if (ro.data.length > 0) {
                  clearTimeout(that.timeout);
                  that.timeout = setTimeout(() => {
                    cb(ro.data);
                  }, 3000 * Math.random());
                } else {
                  clearTimeout(that.timeout);
                }
              } else {
                clearTimeout(that.timeout);
              }
            }).catch(error=>{
              console.log(error);
            })
          } else {
            clearTimeout(that.timeout);
          }
        },
        queryTreeByIdAndPath(id, path) {// 定位展开某节点
          const that= this;
          const tree = that.$refs.tree;
          // 分隔字符串
          const pathArr = path.split(',');
          let index = 1;
          for (let i = 0; i < pathArr.length; i++) {// 依次展开
            if (i > 0) {
              if (tree.getNode(pathArr[i-1]) != null) {
                setTimeout(that._expandNode(tree, pathArr[i-1]), index * 300);
                index++;
              }
            }
          }
          setTimeout(function() {
            if (tree.getNode(id) != null) {
              tree.setCurrentKey(id);
            }
          }, index * 300);
        },
        _expandNode(tree, id) {
          return function() {
            tree.getNode(id).expand();
          }
        },
        loadNode(node, resolve) {// `动态`加载
          const that = this;
          // that.loading = true;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_subjson',
              wsId: that.wsId,
              teamId: that.teamId,
              categorys: that.categorys,
              pid: ''
            }
          };
          if (node.level === 0) {
            // 获取根目录
            data.data.pid = that.pid;
          } else {
            // 获取其他目录
            data.data.pid = node.data.id;
          }
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            for (let i = 0; i < ro.data.length; i++) {
              if (ro.data[i].id.length < 36) {
                ro.data[i].disabled = true;
              } else {
                if (that.categorys != '' && that.methods != '') {
                  if (that.methods.indexOf(ro.data[i].plMethodId) > -1) {
                    ro.data[i].disabled = false;
                  } else {
                    ro.data[i].disabled = true;
                  }
                } else if (that.categorys != '') {
                  if (that.categorys.indexOf(ro.data[i].plCategory) > -1) {
                    ro.data[i].disabled = false;
                  } else {
                    ro.data[i].disabled = true;
                  }
                } else {
                  if (that.methods.indexOf(ro.data[i].plMethodId) > -1) {
                    ro.data[i].disabled = false;
                  } else {
                    ro.data[i].disabled = true;
                  }
                }
              }
            }
            resolve(ro.data);
            that.initTreeCheck();
            // that.loading = false;
            if (node.level == 0 && ro.data.length > 0) {
              const tree = that.$refs.tree;
              tree.getNode(ro.data[0].id).expand();
              setTimeout(function(){
                const childNode = tree.getNode(ro.data[0].id).childNodes[0];
                if (childNode != null) {
                  childNode.expand();
                }
              }, 500);
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        expandNode(obj, node, tree) {// 展开节点

        },
        closeNode(obj, node, tree) {// 关闭时清空，下次展开重新请求动态加载
          node.childNodes = [];
          node.loaded = false;
        },
        initTreeCheck() {// 初始化树选中节点
          const relationType = this.relationType;
          if (relationType == 'file') {// 文件类型
            if (this.multiple) {// 多选
              const  result = this.result;
              const tree = this.$refs.tree;
              for (let i = 0; i < result.length; i++) {
                if (tree.getNode(result[i].id) != null) {
                  tree.setChecked(result[i].id, true);
                }
              }
            } else {// 单选
              const  result = this.result;
              const tree = this.$refs.tree;
              for (let i = 0; i < result.length; i++) {
                if (tree.getNode(result[i].id) != null) {
                  tree.setCurrentKey(result[i].id);
                }
              }
            }
          }
        },
        handleNodeCheckChange(data, isCheck) {// 树多选，只有在relationType为file时会出现
          if (isCheck) {// 选中
            const  result = this.result;
            if (!this.isFileExist(result,data.id, data.versionId)) {
              const tempObj = {};
              tempObj.id = data.id;
              tempObj.versionId = data.versionId;
              tempObj.name = data.name;
              tempObj.children = [];
              result.push(tempObj);
              this.initTableData();
            }
          } else {// 取消选中
            this.remove(data.id);
          }
        },
        handleClose(done) {
          this.closeDlalog('cancel');
          done();
        },
        cancel() {
          this.closeDlalog('cancel');
          this.dialogVisible = false;
        },
        submit() {
          this.closeDlalog('save');
          this.dialogVisible = false;
        },
        closeDlalog(type) {// 取消/确定之后的关闭
          if (type == 'save') {
            const result = JSON.parse(JSON.stringify(this.result));
            if (this.relationType == 'file') {
              for (let i = 0; i < result.length; i++) {
                delete result[i].children;
              }
            }
            this.$emit('getResult', result);
          } else {
            this.$emit('cancel');
          }
          // 清空所有数据
          this.clearAllParam();
        },
        handleNodeClick(data) {// 树节点点击
          const that = this;
          const relationType = this.relationType;
          if (relationType == 'file') {// 关联类型是文件
            if (!this.multiple) {// 单选处理，单选为选中
              // 判断
              if (that.categorys != '' && that.methods != '') {
                if (that.methods.indexOf(data.plMethodId) == -1) {
                  // 不支持
                  that.$message({message: '不支持关联的模型',type: 'warning'});
                  return;
                }
              } else if (that.categorys != '') {
                if (that.categorys.indexOf(data.plCategory) == -1) {
                  that.$message({message: '不支持关联的模型',type: 'warning'});
                  return;
                }
              } else {
                if (that.methods.indexOf(data.plMethodId) == -1) {
                  that.$message({message: '不支持关联的模型',type: 'warning'});
                  return;
                }
              }
              this.result = [];// 清空
              const result = this.result;
              const tempObj = {};
              tempObj.id = data.id;
              tempObj.versionId = data.versionId;
              tempObj.name = data.name;
              tempObj.children = [];
              result.push(tempObj);
              this.initTableData();
            }
          } else {// 关联类型是形状
            // 查询节点列表
            const that = this;
            that.shapeSearchKey = '';
            const params = {
              url:'jd',
              data:{
                cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_shapejson',
                id: data.id
              }
            };
            let isDisabled = true;
            if (that.categorys != '' && that.methods != '') {
              if (that.methods.indexOf(data.plMethodId) > -1) {
                isDisabled = false;
              } else {
                isDisabled = true;
              }
            } else if (that.categorys != '') {
              if (that.categorys.indexOf(data.plCategory) > -1) {
                isDisabled = false;
              } else {
                isDisabled = true;
              }
            } else {
              if (that.methods.indexOf(data.plMethodId) > -1) {
                isDisabled = false;
              } else {
                isDisabled = true;
              }
            }
            // 查询数据
            awsuiAxios.post(params).then(function (ro) {
              if (ro.result == 'ok') {
                const list = ro.data.list;
                const tempData = [];
                for (let i = 0; i < list.length; i++) {
                  const obj = {
                    id: list[i].id,
                    name: list[i].name,
                    fileId: list[i].fileId,
                    fileName: list[i].fileName,
                    versionId: list[i].versionId,
                    isDisabled: isDisabled
                  }

                  tempData.push(obj);
                  that.shapeRecords[list[i].id] = obj;
                }
                that.shapeData = tempData;
                that.shapeTempData = JSON.parse(JSON.stringify(that.shapeData));// 拷贝一份临时数据
              }
            }).catch(error=>{
              console.log(error);
            })
          }
        },
        initTableData() {// 初始化最右侧表格
          const relationType = this.relationType;
          if (relationType == 'file') {// 关联类型是文件
            const result = this.result;
            const tempData = [];
            for (let i = 0; i < result.length; i++) {
              const tempObj = {
                id: result[i].id,
                name: result[i].name,
                versionId: result[i].versionId
              }
              tempData.push(tempObj);
            }
            this.tableData = tempData;
          } else {// 关联类型是形状
            const result = this.result;
            const tempData = [];
            for (let i = 0; i < result.length; i++) {
              const currFile = result[i];
              const children = currFile.children;
              for (let j = 0; j < children.length; j++) {
                const currShape = children[j];
                const tempObj = {
                  id: currShape.shapeId,
                  name: currShape.name,
                  fileId: currFile.id,
                  fileName: currFile.name,
                  versionId: currFile.versionId
                }
                tempData.push(tempObj);
              }
            }
            this.tableData = tempData;
          }
        },
        isFileExist(result, fileId, versionId){// 文件是否存在于结果中
          for (let i = 0; i < result.length; i++) {
            const file = result[i];
            if (file.versionId == versionId) {
              return true;
            }
          }
          return false;
        },
        remove(id) {// 右侧表格删除
          const relationType = this.relationType;
          if (relationType == 'file') {// 关联类型是文件
            const result = this.result;
            for (let i = 0; i < result.length; i++) {
              const obj = result[i];
              if (obj.id == id) {
                result.splice(i, 1);
                if (this.multiple) {
                  this.$refs.tree.setChecked(id, false);
                } else {
                  this.$refs.tree.setCurrentKey(null);
                }
                break;
              }
            }
          } else {// 形状
            if (this.multiple) {// 多选
              const data = this.shapeRecords[id];
              if (data) {
                const result = this.result;
                const shapeId = data.id;
                const name = data.name;
                const fileId = data.fileId;
                const fileName = data.fileName;
                const fileVersionId = data.versionId;
                for (let i = 0; i < result.length; i++) {
                  const file = result[i];
                  if (file.id == fileId) {
                    const children = file.children;
                    for (let j = 0; j < children.length; j++) {
                      if (children[j].shapeId == id) {
                        children.splice(j, 1);
                        break;
                      }
                    }
                    if (children.length == 0) {
                      result.splice(i, 1);
                      break;
                    }
                  }
                }
              }
              // 删除选中节点
              for (let i = 0; i < this.shapeChecked.length; i++) {
                if (this.shapeChecked[i] == id) {
                  this.shapeChecked.splice(i, 1);
                  break;
                }
              }
            } else {// 单选
              this.result = [];
              this.shapeSelected = '';
            }
          }
          this.initTableData();
        },
        handleChangeRadioShape(id) {// 形状单选变化事件
          const data = this.shapeRecords[id];
          if (data) {
            const shapeId = data.id;
            const name = data.name;
            const fileId = data.fileId;
            const fileName = data.fileName;
            const fileVersionId = data.versionId;
            this.result = [];
            const result = this.result;
            const tempObj = {};
            tempObj.id = fileId;
            tempObj.versionId = fileVersionId;
            tempObj.name = fileName;
            tempObj.children = [];
            const children = {
              shapeId: shapeId,
              name: name
            };
            tempObj.children.push(children);
            result.push(tempObj);
            this.initTableData();
          }
        },
        handleChangeCheckShape(ids) {// 形状多选变化事件
          this.result = [];
          const result = this.result;
          for (let i = 0; i < ids.length; i++) {
            const id = ids[i];
            const data = this.shapeRecords[id];
            if (data) {
              const shapeId = data.id;
              const name = data.name;
              const fileId = data.fileId;
              const fileName = data.fileName;
              const fileVersionId = data.versionId;
              let fileExist = false;
              for (let j = 0; j < result.length; j++) {
                const file = result[j];
                if (file.id == fileId) {
                  fileExist = true;
                  const children = {
                    shapeId: shapeId,
                    name: name
                  };
                  file.children.push(children);
                }
              }
              if (!fileExist) {
                const tempObj = {};
                tempObj.id = fileId;
                tempObj.versionId = fileVersionId;
                tempObj.name = fileName;
                tempObj.children = [];
                const children = {
                  shapeId: shapeId,
                  name: name
                };
                tempObj.children.push(children);
                result.push(tempObj);
              }
            }
          }
          this.initTableData();
        },
        initData() {// 初始化传递进来的数据
          // 已选中的数据初始化到result、shapeSelected、shapeChecked里面
          const that = this;
          if (that.relationType == 'file') {
            if (that.selectFileId != '') {
              // 查询数据
              const data = {
                url:'jd',
                data:{
                  cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_file_query',
                  versionIds: that.selectFileId
                }
              };
              // 查询数据
              awsuiAxios.post(data).then(function (ro) {
                if (ro.result == 'ok') {
                  const result = [];
                  for (let i = 0; i < ro.data.length; i++) {
                    const currData = ro.data[i];
                    const tempObj = {};
                    tempObj.id = currData.id;
                    tempObj.versionId = currData.versionId;
                    tempObj.name = currData.name;
                    tempObj.children = [];
                    result.push(tempObj);
                  }
                  that.result = result;
                  that.initTableData();
                }
              }).catch(error=>{
                console.log(error);
              })
            }
          } else {
            if (that.selectFileId != '' && that.selectShapeId != '') {
              // 查询数据
              const data = {
                url:'jd',
                data:{
                  cmd: 'com.actionsoft.apps.coe.pal_repository_tree_component_file_shape_query',
                  fileIds: that.selectFileId,
                  shapeIds: that.selectShapeId
                }
              };
              // 查询数据
              awsuiAxios.post(data).then(function (ro) {
                if (ro.result == 'ok') {
                  if (ro.data.data.length > 0) {
                    that.shapeRecords = ro.data.shapes;
                    if (that.multiple) {
                      that.result = ro.data.data;
                      for (let i = 0; i < that.result.length; i++) {
                        const children = that.result[i].children;
                        for (let j = 0; j < children.length; j++) {
                          that.shapeChecked.push(children[j].shapeId);
                        }
                      }
                    } else {
                      that.result = ro.data.data;
                      for (let i = 0; i < that.result.length; i++) {
                        const children = that.result[i].children;
                        for (let j = 0; j < children.length; j++) {
                          that.shapeSelected = children[j].shapeId;// 取任意一个
                        }
                      }
                    }
                    that.initTableData();
                  }
                }
              }).catch(error=>{
                console.log(error);
              })
            }
          }
        }
      },
      watch: {
        visible(val) {
          this.dialogVisible = val;
          if (val) {// 打开
            this.clearAllParam();
            this.pid = this.rootId;
            this.initData();
          } else {// 关闭
          }
        }
      }
    }
</script>

<style scoped>
  #palRelationAddress >>> .el-dialog__body {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }
  #palRelationAddress >>> .el-input__inner {
    border-radius: 0px;
  }
  #palRelationAddress >>>  .el-tree {
    min-width: 100%;
    display:inline-block !important;
  }
  .checkbox-item {
    margin: 10px 0px;
    display: block;
  }
  .redio-item {
    margin: 10px 0px;
    display: block;
  }
  .div-left {
    float:left;
    width:249px;
    height:400px;
    border-right: 1px dashed #f2f2f2;
  }
  .div-middle {
    float:left;
    width: 248px;
    height:400px;
    border-right: 1px dashed #f2f2f2;
  }
  .div-right {
    float: right;
    width: 249px;
    height:400px;
    background-color: #2a85a0;
  }
  #palRelationAddress >>> .el-table__row .icon-delete-display{
    display: none;
  }
  #palRelationAddress >>> .el-table__row:hover .icon-delete-display{
    display: inline;
  }
  #palRelationAddress >>> .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    background-color: #F5F7FA;
    color: #4E7FF9;
  }
  #palRelationAddress >>> .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content .awsui-iconfont {
    color: #4E7FF9 !important;
  }
</style>
