<!-- 目录管理 -->
<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-group v-model:value="checked" name="checkboxgroup" :options="plainOptions"
                  @change="(checkedValue) => { selectType(checkedValue) }" />
              </a-col>
              <a-col :span="5">
                坐标系：<a-select allowClear ref="select" :value="coordinateChangeValue" 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 v-model:value="inputValue" placeholder="支持名称搜索" style="width: 150px" />
              </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>
              <div class="pagination-box">
                <Pagination size="small" v-model:current="pagination.current" :page-size="50" :total="pagination.total"
                  @change="pageChange" />
              </div>
            </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>
  </div>
</template>

<script>
import { defineComponent, ref, watch, reactive, onMounted } from 'vue';
import { message, Pagination } 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({
  name: 'resourceCataloging',
  components: { Pagination },
  setup() {
    let coordinateChangeValue = ref('')
    let typeChangeValue = ref('MR,ER,DR')
    let clickTreeNode = ref({})
    let associatedFlag = ref('')
    const pagination = reactive({
      current: 1,
      total: 100
    })
    // 分页重新查
    const pageChange = (page, pageSize) => {
      getUsedResource()
    }
    // 生命周期函数
    onMounted(() => {
      getTreeList()
      getcoordinateData()
      getUsedResource()
    })
    // 获取树的节点列表
    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([]) // 坐标系数据
    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('')
    const getKeyWordData = () => {
      getUsedResource()
    }
    const resetKeyWord = () => {
      inputValue.value = ''
      checked.value = ['MR', 'DR', 'ER']
      typeChangeValue.value = 'MR,ER,DR'
      coordinateChangeValue.value = ''
      associatedFlag.value = ''
      pagination.current = 1
      getUsedResource()
      getAssociatedData()
    }

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

    // 请求可用资源
    let usedResourceData = ref([]) // 可使用资源数据
    const getUsedResource = () => {
      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[]', pagination.current)
      directoryFormData.append('args[]', '50')
      directoryFormData.append('args[]', inputValue.value)
      directoryFormData.append('args[]', typeChangeValue.value)
      directoryFormData.append('args[]', associatedFlag.value)
      directoryFormData.append('args[]', coordinateChangeValue.value)
      console.log("参数" + JSON.stringify(directoryFormData))
      addTreeNode(directoryFormData).then((res) => {
        if (res.status == 0) {
          usedResourceData.value = []
          const data = JSON.parse(res.result)
          pagination.total = data.totalItems
          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) => {
      useValue.value = value
    }

    // 顶部复选框处理函数
    const checked = ref(['MR', 'DR', 'ER']) // 复选框
    const plainOptions = ref([
      {
        label: '地图MR',
        value: 'MR',
      },
      {
        label: '场景ER',
        value: 'ER',
      },
      {
        label: '文件数据DR',
        value: 'DR',
      },
      {
        label: '未关联',
        value: 'false',
      }
    ])
    const selectType = (e) => {
      if (e.toString().indexOf('false') > -1) {
        typeChangeValue.value = e.slice(0, -1).toString()
        associatedFlag.value = 'false'
      }
      else {
        typeChangeValue.value = e.toString()
        associatedFlag.value = ''
      }
      getUsedResource()
    }

    // 点击树节点函数
    const nodeSelect = (selectedKeys, { selectedNodes, node }) => {
      if (selectedKeys.length) {
        clickTreeNode.value = { ...node.dataRef }
        getAssociatedData()
      }else{
        clickTreeNode.value = {}
        associatedData.value = []
      }
    }

    // 得到已经关联的数据
    let associatedData = ref([]) //已关联数据
    const getAssociatedData = () => {
      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[]', clickTreeNode.value.id)
      directoryFormData.append('args[]', coordinateChangeValue.value)
      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 = () => {
      if(!clickTreeNode.value.id){
        message.info('请选择目录');
        return;
      }
      if(!useValue.value.length){
        message.info('请选择资源');
        return;
      }
      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()
          useValue.value = []
        }
      })
    }

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

    // 取消关联数据
    const cancelAssociateData = () => {
      if(!clickTreeNode.value.id){
        message.info('请选择目录');
        return;
      }
      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()
          cancleUseValue.value = []
        }
      })
    }

    return {
      pagination,
      pageChange,
      coordinateChangeValue,
      typeChangeValue,
      treeData,
      treeSearchValue,
      expandedKeys,
      autoExpandParent,
      onExpand,
      handleChange,
      getTreeList,
      coordinateData,
      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;
        }
      }

      .pagination-box {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }

}
</style>
