<!-- 目录管理 -->
<template>
  <div style="height: 100%; width: 100%; padding: 0; margin: 0;">
    <!-- 左边 -->
    <div class="mains">
      <div class="left">
        <a-card class="box-card" body-style="{height:'100%'}">
          <a-input-search v-model:value="treeSearchValue" style="margin-bottom: 8px" placeholder="搜索关键字" />
          <a-tree class="tree-list" v-if="treeData.length" :tree-data="treeData" @select="nodeSelect" :expandedKeys="expandedKeys" :defaultExpandedKeys="expandedKeys"
            :auto-expand-parent="autoExpandParent" @expand="onExpand">
            <template #title="{ title }">
              <span v-if="title.indexOf(treeSearchValue) > -1">
                {{ title.substr(0, title.indexOf(treeSearchValue)) }}
                <span style="color: #f50">{{ treeSearchValue }}</span>
                {{ title.substr(title.indexOf(treeSearchValue) + treeSearchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </a-card>
      </div>
      <!-- 右边 -->
      <div class="right">
        <div class="right-head">
          <a-card>
            <a-row>
              <a-col :span="10">
                类型：
                <!-- <a-checkbox v-model:checked="checked.checked1" @change="(e)=>{selectType(e)}">地图MR</a-checkbox>
              <a-checkbox v-model:checked="checked.checked2" @change="(e)=>{selectType(e)}">场景ER</a-checkbox>
              <a-checkbox v-model:checked="checked.checked3" @change="(e)=>{selectType(e)}">文件数据DR</a-checkbox> -->
                <a-checkbox-group v-model:value="checked" name="checkboxgroup" :options="plainOptions"
                  @change="(checkedValue) => { selectType(checkedValue) }" />
              </a-col>
              <a-col :span="5">
                坐标系：<a-select ref="select" :value="coordinateSearchvalue" style="width: 150px" @change="handleChange">
                  <a-select-option v-for="item in coordinateData" :key="item.ID" :value="item.GEOMNAME">{{ item.GEOMNAME
                  }}</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="5">
                资源名称：<a-input-search v-model:value="inputValue" placeholder="支持名称搜索" style="width: 150px" @search="onSearch" />
              </a-col>
              <a-col :span="4" style="display: flex;justify-content: flex-end;">
                <a-button style="margin-right: 10px;" @click="resetKeyWord">重置</a-button>
                <a-button type="primary" @click="getKeyWordData">查询</a-button>
              </a-col>
            </a-row>
          </a-card>
        </div>
        <div class="right-content">
          <div class="right-content-left">
            <a-card style="height: 100%;">
              <div class="right-content-head">
                <a-row>
                  <a-col :span="10"><span style="font-weight: 700; font-size: 16px;">可用资源</span> </a-col>
                </a-row>
              </div>
              <div class="right-content-bottom">
                <a-checkbox-group v-model:value="useValue" name="checkboxgroup" @change="(e) => { selectUsedData(e) }">
                  <a-row :gutter="24">
                    <a-col :span="12" v-for="item in usedResourceData" :key="item.value">
                      <a-checkbox :value="item.value">
                        <span class="rtype"
                          :class="{ 'color-mr': item.rtype === 'MR', 'color-er': item.rtype === 'ER', 'color-dr': item.rtype === 'DR' }">{{
                            item.rtype }}</span>
                        <span class="label">{{ item.label }}</span>
                      </a-checkbox>
                    </a-col>
                  </a-row>
                </a-checkbox-group>
              </div>
              <a-pagination size="small" :total="50" :show-total="total => 'Total 50 items'" />
            </a-card>
          </div>
          <div class="right-content-middle">
            <div class="btn-group">
              <a-button class="add-btn" @click="addAssociateData">{{ `>>添加关联` }}</a-button>
              <a-button class="del-btn" style="margin-top: 20px;" @click="cancelAssociateData">{{ `<<移除关联` }}</a-button>
            </div>
          </div>
          <div class="right-content-right">
            <a-card style="height: 100%;">
              <div class="right-content-head">
                <a-row>
                  <a-col :span="10"><span style="font-weight: 700; font-size: 16px;">已关联资源</span> </a-col>
                </a-row>
              </div>
              <div class="right-content-bottom">
                <a-checkbox-group v-model:value="cancleUseValue" name="checkboxgroup"
                  @change="(checkedValue) => { cancleUsedData(checkedValue) }">
                  <!-- <a-row :gutter="24">
                    <a-col :span="12" v-for="item in associatedData" :key="item.serviceid" :value="item.serviceid">
                      <a-checkbox></a-checkbox>
                    </a-col>
                  </a-row> -->
                  <a-row :gutter="24">
                    <a-col :span="12" v-for="item in associatedData" :key="item.value">
                      <a-checkbox :value="item.value">
                        <span class="rtype"
                          :class="{ 'color-mr': item.rtype === 'MR', 'color-er': item.rtype === 'ER', 'color-dr': item.rtype === 'DR' }">{{
                            item.rtype }}</span>
                        <span class="label">{{ item.label }}</span>
                      </a-checkbox>
                    </a-col>
                  </a-row>
                </a-checkbox-group>
              </div>
            </a-card>
          </div>
        </div>
      </div>
    </div>
    <!-- <a-modal :visible="visible" title="添加节点" @ok="handleOk" width="50%">
    <div style="margin: 10px;">
      <a-form :model="formState2" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
        <a-row>
          <a-col :span="10">
            <a-form-item label="上级节点">
             <a-input v-model:value="formState2.pName" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="名称">
             <a-input v-model:value="formState2.name" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="别名">
             <a-input v-model:value="formState2.alaisename" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item label="分类">
             <a-input v-model:value="formState2.type" />
            </a-form-item>
          </a-col>
          <a-col :span="20">
            <a-form-item label="描述">
              <a-textarea v-model:value="formState2.remark" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal> -->
  </div>
</template>
<script>

import { defineComponent, ref, watch, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getDirectoryTreeList, addTreeNode } from '/@/api/sys/gis';
// import Guid from 'guid'
import { v4 as uuidv4 } from 'uuid';
import { session } from '/@/utils/Memory';

export default defineComponent({

  setup() {
    let coordinateChangeValue = ref('2000坐标系4490')
    let typeChangeValue = ref('MR,SR,ER,DR,DT')
    let clickTreeNode = ref({})
    // 生命周期函数
    onMounted(() => {
      getTreeList()
      getcoordinateData()
      getUsedResource(coordinateChangeValue.value, typeChangeValue.value)
    })
    // 获取树的节点列表
    const treeData = ref([]) // 树的数据
    const treeSearchValue = ref('') // 树的搜索值
    const inputSearchValue = ref('') // 头部搜索框的数据
    const dataList = ref([])//用于树搜索的数据列表
    const expandedKeys = ref([])
    const autoExpandParent = ref(true)
    const getTreeList = () => {
      const gisToken = session.getItem('tokenV2')
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.sdatacatlog.SDataCatlogProvider')
      directoryFormData.append('methodName', 'findList')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', '')
      getDirectoryTreeList(directoryFormData).then((res) => {
        if (res.status == 0) {
          const data = JSON.parse(res.result)
          // 让每层带上自己的孩子节点、title、key
          data.forEach((item) => {
            item['title'] = item.name
            item['key'] = item.id
            data.forEach((item2) => {
              if (item.id == item2.pid) {
                if (item.children) {
                  item.children.push(item2)
                } else {
                  item['children'] = []
                  item.children.push(item2)
                }
              }
            })
          });
          // console.log(data)
          // 找出树形数据
          data.forEach((item) => {
            if (item.pid === '') {
              treeData.value = item.children
            }
          })
          treeData.value.forEach(item=>{
            expandedKeys.value.push(item.id)
          })
          generateList(treeData.value)
        }
      });
    }
    //生成用于树搜索的dataList
    const generateList = (data) => {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const key = node.key;
        dataList.value.push({
          key,
          title: node.title,
        });
        if (node.children) {
          generateList(node.children);
        }
      }
    }
    //获取所有父节点key
    const getParentKey = (key, tree) => {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key;
          } else if (getParentKey(key, node.children)) {
            parentKey = getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    }
    //树结构展开时触发
    const onExpand = (keys) => {
      expandedKeys.value = keys;
      autoExpandParent.value = false;
    }
    watch(
      () => treeSearchValue.value,
      (val) => {
        if (val) {
          let expanded = dataList.value
            .map(item => {
              if (item.title.indexOf(val) > -1) {
                return getParentKey(item.key, treeData.value);
              }
              return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);
          expandedKeys.value = expanded;
        } else {
          expandedKeys.value = [];
        }
        treeSearchValue.value = val;
        autoExpandParent.value = true;
      }
    )

    // 请求坐标系数据
    let coordinateData = ref([]) // 坐标系数据
    let coordinateSearchvalue = ref('2000坐标系4490')
    const getcoordinateData = () => {
      const gisToken = session.getItem('tokenV2')
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.geomname.GeomNameCDProvider')
      directoryFormData.append('methodName', 'getGeomNameList')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', '')
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          coordinateData.value = JSON.parse(res.result)
        }
      })
    }

    const inputValue = ref(null)
    const getKeyWordData = ()=>{

    }
    const resetKeyWord = () => {
      inputValue.value = ''
    }

    // 坐标系下拉框处理函数
    const handleChange = value1 => {
      coordinateChangeValue.value = value1
      getUsedResource(coordinateChangeValue.value, typeChangeValue.value)
      getAssociatedData(clickTreeNode.value.id, coordinateChangeValue.value)
    }

    // 请求可用资源
    let usedResourceData = ref([]) // 可使用资源数据
    const getUsedResource = (value1, value2) => {
      const gisToken = session.getItem('tokenV2')
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.sservicebase.SServicebaseProvider')
      directoryFormData.append('methodName', 'pageList')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', '1')
      directoryFormData.append('args[]', '50')
      directoryFormData.append('args[]', '')
      directoryFormData.append('args[]', value2)
      directoryFormData.append('args[]', '')
      directoryFormData.append('args[]', value1)
      console.log("参数" + JSON.stringify(directoryFormData))
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          usedResourceData.value = []
          const data = JSON.parse(res.result)
          data.items.forEach((item) => {
            console.log(item.rtype);
            usedResourceData.value.push({
              label: item.servicename,
              value: JSON.stringify({
                name: item.servicename,
                id: item.serviceid
              }),
              rtype: item.rtype
            })
          })
        }
      })
    }

    // 选择可用数据
    let useValue = ref([])
    const selectUsedData = (value) => {
      console.log("可使用数据")
      console.log(value);
      useValue.value = value
    }

    // 顶部复选框处理函数
    let checked = ref(['MR', 'DR', 'ER']) // 复选框
    const plainOptions = ref([{
      label: '地图MR',
      value: 'MR',
    }, {
      label: '场景DR',
      value: 'DR',
    }, {
      label: '文件数据ER',
      value: 'ER',
    }])
    const selectType = (e) => {
      let typeValue = e.toString()
      typeChangeValue.value = typeValue
      getUsedResource(coordinateChangeValue.value, typeChangeValue.value)
    }

    // 点击树节点函数
    const nodeSelect = (selectedKeys, { selectedNodes, node }) => {
      console.log("点击树的数据")
      console.log(node.dataRef);
      clickTreeNode.value = { ...node.dataRef }
      getAssociatedData(clickTreeNode.value.id, coordinateChangeValue.value)
    }

    // 得到已经关联的数据
    let associatedData = ref([]) //已关联数据
    const getAssociatedData = (value1, value2) => {
      const gisToken = session.getItem('tokenV2')
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.sservicebase.SServicebaseProvider')
      directoryFormData.append('methodName', 'getByDids')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', value1)
      directoryFormData.append('args[]', value2)
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          let data = JSON.parse(res.result)
          associatedData.value = data
          associatedData.value.forEach((item) => {
            item['label'] = item.servicename
            item['value'] = item.serviceid
          })
        }
      })
    }

    // 添加关联数据
    const addAssociateData = () => {
      const gisToken = session.getItem('tokenV2')
      let associatedValueArr = []
      useValue.value.forEach((item) => {
        let obj = JSON.parse(item)
        let associatedValue = {
          id: uuidv4(),
          serviceid: obj.id,
          servicename: obj.name,
          did: clickTreeNode.value.id,
          dname: clickTreeNode.value.name,
        }
        associatedValueArr.push(associatedValue)
      })
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.sbdc.SBDCProvider')
      directoryFormData.append('methodName', 'insertList')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', JSON.stringify(associatedValueArr))
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          getAssociatedData(clickTreeNode.value.id, coordinateChangeValue.value)
          useValue.value = []
        }
      })
    }

    // 选择取消关联的数据
    let cancleUseValue = ref([])
    const cancleUsedData = (value) => {
      console.log("取消可使用数据" + JSON.stringify(value))
    }

    // 取消关联数据
    const cancelAssociateData = () => {
      const gisToken = session.getItem('tokenV2')
      let directoryFormData = new FormData()
      directoryFormData.append('interfaceName', 'antu.space.provider.sbdc.SBDCProvider')
      directoryFormData.append('methodName', 'deleteByDidAndServiceIds')
      directoryFormData.append('args[]', gisToken)
      directoryFormData.append('args[]', clickTreeNode.value.id)
      directoryFormData.append('args[]', cancleUseValue.value.toString())
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          getAssociatedData(clickTreeNode.value.id, coordinateChangeValue.value)
          cancleUseValue.value = []
        }
      })
    }

    return {
      coordinateChangeValue,
      typeChangeValue,
      treeData,
      treeSearchValue,
      expandedKeys,
      autoExpandParent,
      onExpand,
      handleChange,
      getTreeList,
      coordinateData,
      coordinateSearchvalue,
      getcoordinateData,
      usedResourceData,
      getUsedResource,
      checked,
      plainOptions,
      selectType,
      nodeSelect,
      associatedData,
      getAssociatedData,
      useValue,
      selectUsedData,
      addAssociateData,
      cancleUseValue,
      cancleUsedData,
      cancelAssociateData,
      inputValue,
      getKeyWordData,
      resetKeyWord
    };
  },

});
</script>

<style lang="less" scoped>
.head {
  padding: 10px;
  height: 74px;
  margin-right: 30px;
  margin-left: 10px;
}

.mains {
  .box-card {
    height: calc(100% - 0px);

    .tree-list {
      height: 760px;
      overflow: auto;

      &::-webkit-scrollbar {
        width: 3px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 2px;
        background: #ccd5df;
      }

      &::-webkit-scrollbar-track {
        display: none;
      }
    }
  }

  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  height: calc(100% - 0px);

  .left {
    height: calc(100% - 0px);
    width: 20%;
  }

  .right {
    display: flex;
    flex-direction: column; //设置主轴为y轴 
    justify-content: flex-start; //子元素排列方式，
    align-items: flex-start; //设置侧轴上子元素对齐方式
    padding: 20px;
    padding-top: 0;
    padding-bottom: 0;
    height: calc(100% - 0px);
    width: 100%;

    .right-head {
      width: 100%;
      height: 10%;
    }

    .right-content {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: calc(100% - 0px);
      margin-top: 20px;
      width: 100%;

      .right-content-left {
        width: 46%;
        height: calc(100% - 0px);
      }

      .right-content-middle {
        width: 8%;
        height: calc(100% - 0px);
        display: flex;
        align-items: center;
        justify-content: center;

        .btn-group {
          width: 94px;

          ::v-deep .add-btn {
            padding: 0;
            width: 94px;
            height: 34px;
            background: #0671DD;
            font-size: 14px;
            font-weight: normal;
            line-height: 34px;
            color: #FFFFFF;
          }

          ::v-deep .del-btn {
            padding: 0;
            width: 94px;
            height: 34px;
            background: #F8252C;
            font-size: 14px;
            font-weight: normal;
            line-height: 34px;
            color: #FFFFFF;
          }
        }
      }

      .right-content-right {
        width: 46%;
        height: calc(100% - 0px);
      }

      .right-content-head {
        height: 40px;
      }

      .right-content-bottom {
        height: 600px;
        width: 100%;
        border-style: solid;
        border-width: 1px;
        border-color: #E9E9E9;
        // box-shadow:0 0 10px #ddd;
        padding: 20px;
        overflow: auto;

        ::v-deep label {
          // display: flex;
          padding: 10px 0;
          // align-items: center;

          span {
            &:last-child {
              align-items: center;
              vertical-align: text-bottom;
            }
          }
        }

        .rtype {
          margin-right: 5px;
          display: inline-block;
          font-family: Source Han Sans CN;
          font-size: 12px;
          font-weight: bold;
          line-height: 20px;
          color: #FFFFFF;
          text-align: center;
          width: 30px;
          height: 20px;
          border-radius: 10px;
        }

        .color-mr {
          background: #8205C1;
        }

        .color-er {
          background: #05C17F;
        }

        .color-dr {
          background: #FC8B01;
        }

        .label {
          display: inline-block;
          width: 150px;
          height: 20px;
          font-size: 16px;
          line-height: 20px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }

}
</style>
