<template>
  <div>
    <el-form :model="formData" :rules="rules" ref="form" label-width="80px" label-position="right" size="small" style="max-width: 800px;">
      <el-form-item prop="landMarkId" label="地标ID">
        <el-input v-model="formData.landMarkId" disabled style="width:200px;"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="标题">
        <el-input v-model="formData.name" disabled style="width:200px;"></el-input>
      </el-form-item>
      <el-form-item prop="aimPlace" label="导游包">
        <!-- <el-input v-model="formData.aimPlace"></el-input>
      </el-form-item>
        <el-form-item >-->
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable style="width:200px;"></el-input>
        <div class="tree">
          <el-tree ref="tree" class="useTree" :data="treeList" show-checkbox node-key="id" :filter-node-method="filterNode" :default-checked-keys="checkKeys">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="node-title">
                <small>{{listName[data.typeName].typeName}}</small>
                {{ node.label }}
              </span>
              <span>
                <el-button type="text" v-if="data.typeName=='aimPlaceInfoList'" size="mini" @click="goAR(data)">AR内容</el-button>
                <el-button type="text" size="mini" @click="goEdit(data)">编辑</el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button @click="onSave" :loading="$store.state.fetchingData" type="primary">保存</el-button>
        <el-button @click="$router.go(-1)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import formValidator from '../formValidator'

export default {
  created() {
    if (this.$route.query.column) {
      this.subColumn = this.$route.query.column.split(',')[1];
      this.subValue = this.$route.query.column.split(',')[0];
    }

    if (this.$route.query.id) {
      this.$http.get({
        url: '/navigationPackage/getOne',
        data: {
          id: this.$route.query.id
        }
      }).then(res => {
        if (res.success) {


          this.formData = res.data;

          if (this.$route.query.column) {
            this.formData[this.subColumn] = this.subValue;
          }

          var list = res.data.aimPlace ? res.data.aimPlace.split(',') : [];
          list.forEach(item => {
            this.checkKeys.push('aimPlaceInfoList_' + item)
          })


          this.getLandMarkInfo();

        }
      })
    } else {
      if (this.$route.query.column) {
        this.formData[this.subColumn] = this.subValue;
      }
    }

  },
  data() {
    return {
      filterText: '',
      saving: false,
      formData: {
        price: 0,
        rank: 0
      },
      rules: {
      },
      landMarkIdOptions: [],
      subColumn: '',
      subValue: '',
      landMarkInfo: {},
      listName: {
        landMarkInfo: {
          id: 'landMarkInfo_',
          label: 'mapName',
          type: 'json',
          typeName: '地标',
          src: '/landMark?id='
        },
        areaInfoList: {
          id: 'areaInfoList_',
          label: 'areaName',
          type: 'list',
          typeName: '区域',
          src: '/areaInfo?id='
        },
        thingInfoList: {
          id: 'thingInfoList_',
          label: 'thingName',
          type: 'list',
          typeName: '事物',
          src: '/thingInfo?id='
        },
        aimGroupInfo: {
          id: 'aimGroupInfo_',
          label: 'groupName',
          type: 'json',
          typeName: '点标组',
          src: '/aimGroupInfo?id='
        },
        aimPlaceInfoList: {
          id: 'aimPlaceInfoList_',
          label: 'name',
          type: 'list',
          typeName: '点标',
          src: '/aimPlaceInfo?id='
        }
      },
      treeList: [],
      checkKeys: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    goEdit(data) {
      var id = data.id.replace(this.listName[data.typeName].id, '');
      this.$router.push(this.listName[data.typeName].src + id);
    },
    goAR(data) {
      var id = data.id.replace('aimPlaceInfoList_', '')
      this.$router.push('/ArContents?column=' + id + ',aimPlaceId')
    },
    filterNode(value, data) {
      if (!value) return true;
      if (!data.label) return false;
      return data.label.indexOf(value) !== -1;
    },
    onSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submit();
        } else {
          return false;
        }
      });
    },
    getCheckedKeys() {
      // console.log(this.$refs.tree.getCheckedKeys());
      var result = []
      var list = [...this.$refs.tree.getCheckedKeys()];
      list.forEach(item => {
        if (item.indexOf('aimPlaceInfoList_') != -1) {
          result.push(item.replace('aimPlaceInfoList_', ''))
        }
      })
      return result.join(',');
    },
    submit() {
      //   console.log()
      //   return;
      var data = {
        id: this.formData.id,
        aimPlace: this.getCheckedKeys()
      };

      this.$http.post({
        url: '/navigationPackage/update',
        data: data
      }).then(res => {
        if (res.success) {
          this.$message.success('成功');
          this.$router.go(-1);
        } else {
          this.$message.warning('失败')
        }
      });
    },
    getLandMarkInfo() {

      if (this.formData.landMarkId) {

        this.$http.get({
          url: '/landMark/mapInfo',
          data: {
            id: this.formData.landMarkId
          }
        }).then(res => {
          if (res.success) {
            this.landMarkInfo = res.data;
            this.treeList = this.getTreeList({
              landMarkInfo: res.data
            });
          }
        });
      }

    },
    getTreeList(data) {
      var tree = []



      for (var key in this.listName) {
        if (data[key]) {
          if (this.listName[key].type == 'json') {
            var jsonp = {
              id: this.listName[key].id + data[key].id,
              label: data[key][this.listName[key].label] || '',
              typeName: key,
              children: this.getTreeList(data[key])
            }
            tree.push(jsonp);
          }
          else {
            data[key].forEach(item => {
              var jsonp = {
                id: this.listName[key].id + item.id,
                label: item[this.listName[key].label] || '',
                typeName: key,
                children: this.getTreeList(item)
              }

              tree.push(jsonp)
            })
          }

        }
      }
      return tree;

    },
    onDelete() {
      this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
        return this.$http.post({
          url: '/navigationPackage/del',
          data: { id: this.formData.id }
        })
      }).then(() => {
        this.$message.success('删除成功');
        this.$router.go(-1);
      }).catch(action => {
        if (action === 'cancel') {
          this.$message.info('删除取消');
        } else {
          this.$message.error('删除失败');
        }
      })
    },
  }
}
</script>
<style lang="less" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    line-height: 30px;

    span {
        small {
            color: #409eff;
            //   font-size: 9px;
        }
    }
}

.tree {
    height: 500px;
    overflow: auto;
    margin-top: 20px;
    border-top: 1px solid #eee;
}

.node-title {
    width: 500px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
