<template>
  <div class="move-w">
    <div class="move-header">
      <h1>{{ selectScenes.length > 1 ? $t('manage.sceneAdmin.moveBtnText') :  $t('manage.myScenes.moveFolder') }}</h1>
      <p>{{ $t('manage.sceneAdmin.folderModule.selectTargetFolder') }}</p>
    </div>
    <div class="move-content-container">
      <div class="move-content">
        <div class="move-select-container">
          <div class="move-select-header">
            <input :placeholder="$t('manage.sceneAdmin.folderModule.inputFolderNameToSearch')" v-model="searchKey" />
          </div>
          <div class="move-select-content">
            <vue-tree v-if="!searchKey" :treeData="datas" ref="vtree" @clickNode="handleSelect" @saveFolder="saveFolder" @cancelCreate="cancelCreate"></vue-tree>
            <div class="search-result-w" v-else>
              <ul v-if="searchList.length > 0">
                <li :class="{'is-active': selectItem.id === item.id}" v-for="item in searchList" :key="item.id" @click="handleSelect(item)">
                  <span class="tree-icon" :type="item.icon"></span>{{ item.name }}
                </li>
              </ul>
              <div class="no-result" v-else>
                <p>{{ $t('manage.sceneAdmin.folderModule.noSearchResultTip') }}</p>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="create-folder" :class="{'disabled-link': isCreating || searchKey || !selectItem.name}" @click="handleCreateFolderBtnClick">
          <h-icon type="folder"></h-icon>
          <h-icon type="jiahao"></h-icon>
          {{$t('manage.sceneAdmin.createFolder')}}
        </div> -->
      </div>
    </div>
    <div class="move-footer">
      <div class="move-btn" @click="handleCancelBtnClick">{{ $t('common.cancle') }}</div>
      <div class="move-btn submit-btn" @click="handleMoveInFolder">{{ $t('common.confirm') }}</div>
    </div>
  </div>
</template>

<script>
import SceneApi from '@/apis/scene'
import { mapState } from "vuex";
export default {
  props: {
    selectScenes: Array,
    isLaser:Boolean,
    folderType:Number,
  },
  data () {
    return {
      searchKey: '',
      datas: [],
      isCreating: false,
      searchList: [],
      selectItem: {}
    }
  },
  computed: {    
    ...mapState({
    info: state => state.user.info,
    }),
    selectedFolderIds () {
      let arr = this.selectScenes.filter(item => item.isFolder) || []
      return arr.map(item => item.id).join(',')
    },
    selectedSceneIds () {
      let arr = this.selectScenes.filter(item => !item.isFolder) || []
      return arr.map(item => item.id).join(',')
    }
  },
  watch: {
    searchKey (val) {
      this.searchFolder()
    }
  },
  mounted () {
    console.log('type',this.isLaser)
    if(this.isLaser){
      this.laserTree()
    }else{
      this.getTree()
    }
  },
  methods: {
    laserTree(){
      SceneApi.getSceneLaserTreeList({
        "userName":this.info.userName,//用户手机号
      }).then(res => {
        console.log('getSceneLaserTreeList',res)
        let arr = res.data.data.map(item => {
          if (!item.children) {
            item.children = []
          }
          return item
        })
        let children = this.sortTree(arr, this.oldTree || [])
        this.$set(this.datas, 0, 
          {
            name: this.$t('manage.myDevices.gml'),
            id: '',
            children: children,
            expand: true
          }
        )
        this.oldTree = children
      })
    },
    getTree () {
      SceneApi.getSceneTreeList(this.folderType || 0).then(res => {
        let arr = res.data.data.map(item => {
          if (!item.children) {
            item.children = []
          }
          return item
        })
        let children = this.sortTree(arr, this.oldTree || [])
        this.$set(this.datas, 0,
          {
            name: this.$t('manage.myDevices.gml'),
            id: '',
            children: children,
            expand: true
          }
        )
        this.oldTree = children
      })
    },
    handleCancelBtnClick () {
      this.$emit('cancel')
    },
    handleSelect (treeItem) {
      this.selectItem = treeItem
    },
    handleCreateFolderBtnClick () {
      if (this.isCreating || this.searchKey || !this.selectItem.name) {
        return
      }
      this.isCreating = true
      if (!this.selectItem.id) {
        this.datas[0].children.push({
          name: '',
          parentId: '',
          children: []
        })
        return
      }
      if (!this.selectItem.children) {
        this.selectItem.children = []
      }
      this.selectItem.children.push({
        name: '',
        parentId: this.selectItem ? this.selectItem.id : '',
        children: []
      })
      this.isCreateFolderParent = this.selectItem
    },
    cancelCreate (item) {
      this.isCreating = false
      if (this.isCreateFolderParent) {
        this.isCreateFolderParent.children = this.isCreateFolderParent.children.filter(item => item.id)
      } else {
        this.datas[0].children = this.datas[0].children.filter(item => item.id)
      }
    },
    saveFolder (parent, folderName) {
      if (folderName) {
        folderName = folderName.trim()
      }
      if (!folderName) {
        this.$toast.show('warn', this.$t('manage.sceneAdmin.folderModule.emptyFolderName'))
        return
      }
      const data = {
        name: folderName,
        type: 0,
        parentId: parent.parentId || ''
      }
      SceneApi.createFolder(data).then(res => {
        if (res.data.code === 0) {
          this.getTree()
          this.isCreating = false
        } else {
          let tips = this.$t(`toast[${res.data.code}]`) === `toast[${res.data.code}]` ? this.$t('manage.sceneAdmin.folderModule.createFail') : this.$t(`toast[${res.data.code}]`)
          this.$alert(tips)
        }
      })
    },
    handleMoveInFolder () {
      if (!this.selectItem.name) {
        this.$toast.show('warn', this.$t('manage.sceneAdmin.folderModule.selectTargetFolderTip'))
        return
      }
      let data = {
        type: this.folderType || this.type || 0,
        parentId: this.selectItem ? this.selectItem.id : '',
        folderIds: this.selectedFolderIds,
        sceneIds: this.selectedSceneIds
      }
      if(this.isLaser){
        return SceneApi.moveSceneLaserOrFolder({
          ...data,
          parentId:data.parentId || 0,
          folderIds:data.folderIds? data.folderIds.split(',').map(ele => Number(ele)) : [],
          sceneIds:data.sceneIds ? data.sceneIds.split(',').map(ele => Number(ele)) : [],
          type:0,
        }).then(res => {
          if (res.data.code === 200) {
            this.$emit('moveSuccess')
          } else {
            this.$toast.show('error', this.$t(`toast[${res.data.code}]`))
          }
        })
      }
      return SceneApi.moveSceneOrFolder(data).then(res => {
        if (res.data.code === 0) {
          this.$emit('moveSuccess')
        } else {
          this.$toast.show('error', this.$t(`toast[${res.data.code}]`))
        }
      })
    },
    sortTree (arr, oldTree = []) {
      // 过滤已选择的文件夹
      return arr.filter(item => {
        let oldItem = oldTree.find(tree => tree.id === item.id) || {}
        item.expand = oldItem.expand || false
        if (item.children && item.children.length > 0) {
          item.children = this.sortTree(item.children, oldItem.children || [])
        }
        return this.selectedFolderIds.indexOf(item.id) === -1
      })
    },
    searchFolder () {
      SceneApi.searchFolder({name: this.searchKey, type: this.type || 0}).then(res => {
        this.searchList = res.data.data
      })
    }
  }
}
</script>

<style lang="less" scoped>
.move-w {
  background: #fff;
  width: 335px;
  border-radius: 10px;
}
.move-header {
  line-height: 46px;
  padding: 0 20px;
  border-bottom: 1px solid #ebebeb;
  h1 {
    font-size: 14px;
    font-weight: 600;
    display: inline-block;
  }
  p {
    color: rgba(144, 144, 144, 1);
    font-size: 12px;
    display: inline-block;
    margin-left: 10px;
  }
}
.move-content-container {
  padding: 20px ;
  border-bottom: 1px solid #ebebeb;
}
.move-select-container {
  border: 1px solid #EBEBEB;;
}
.move-select-header {
  border-bottom: 1px solid #EBEBEB;;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;

  input {
    border: none;
    width: 100%;
    font-size: 12px;
    color: rgb(59, 59, 59);;
  }
}
.create-folder {
  color: #15BEC8;
  margin-top: 10px;
  cursor: pointer;
  display: inline-block;
}
.move-select-content {
  height: 268px;
  overflow: auto;
  position: relative;
  .no-result {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: #EBEBEB;;
    line-height: 1;
    font-size: 14px;
  }
}
.move-footer {
  padding: 20px;
  text-align: center;
  overflow: hidden;
}
.move-btn {
  width: calc(50% - 7.5px);
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 0.373333rem;
  background: #ebebeb;
  display: inline-block;
  cursor: pointer;
  border-radius: 4px;
  float: left;
  &.submit-btn {
    background: #15BEC8;
    color: #fff;
    float: right;
  }
}
.search-result-w {
  padding: 20px;
  font-size: 14px;
  li {
    cursor: pointer;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    &:hover, &.is-active {
      color: #15BEC8;
    }
  }
}
.tree-icon {
  /* color: #15BEC8; */
  /* font-size: 18px; */
  margin: 0 4px 0 10px;
  display: inline-block;
  width: 18px;
  height: 14px;
  background: url(~@/assets/images/refactor/usercenter/folder.png) no-repeat center center;
  background-size: cover;
}
</style>
