<template>
  <q-dialog v-model="show" class="col-6" persistent transition-show="scale" transition-hide="scale" @show="showDialog"
    @hide="hideDialog">
    <q-card style="width: 600px; height: 600px; max-width: 80vw">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">选择部门 <span v-if="showType === 0">/员工</span></div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="q-pt-none" style="height: 480px">
        <div class="row" style="height: 100%">
          <div class="col-6 q-px-sm" style="border-right: 1px solid #999; height: 100%">
            <q-input color="teal" dense outlined placeholder="请输入" v-model="filter" style="margin-bottom: 10px"
              clearable @clear="clearInput">
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
            <q-tree style="height: calc(100% - 50px); overflow-y: scroll" ref="tree" class="col-12" :nodes="treeData"
              :node-key="nodeKey" :label-key="labelKey" :children-key="childrenKey" :tick-strategy="strategy"
              :default-expand-all="defaultExpandAll" no-connectors v-model:ticked="ticketArr"
              @update:ticked="tickedTree" :filter="filter" :filter-method="myFilterMethod" />
          </div>
          <div class="col-6 q-px-sm">
            <div class="list-title">已选择的部门<span v-if="showType === 0">或成员</span></div>
            <div class="q-pb-none col-12 list-box">
              <div v-for="(item, index) in selectArray" :key="index" class="list-item">
                <div class="flex-center">
                  <q-icon name="work" color="primary" v-if="item.Type == '1'" />
                  <q-icon name="person" color="accent" v-if="item.Type == '2'" />
                  <span class="q-ml-sm">{{ item.DeptName }}</span>
                </div>
                <q-icon name="cancel" @click="delItem(item.Id, index)"></q-icon>
              </div>
            </div>
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn flat label="取消" v-close-popup />
        <q-btn color="primary" @click="goback" unelevated label="确定" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script lang="ts">
  import {
    ref,
    watch
  } from 'vue'

  interface parmas {
    [key: string]: any
  }
  interface SelectParams {
    Id: string
    DeptName: string
    Type: number
  }
  export default {
    props: {
      modelValue: {
        type: Boolean,
        default: false,
        required: true
      },
      //树形结构列表
      treeData: {
        type: Array,
        required: true
      },
      showType: {
        type: Number, //0:显示部门和员工，1：只显示部门
        default: 0
      },
      //是否默认展开
      defaultExpandAll: {
        type: Boolean,
        default: false
      },
      //默认选中值
      defaultArray: {
        type: Array,
        default: () => [],
        required: true
      },
      //节点Key
      nodeKey: {
        type: String, //格式需拼成 '类型-名字-id'的形式
        default: 'id'
      },
      //节点名称
      labelKey: {
        type: String,
        default: 'name'
      },
      //子节点名称
      childrenKey: {
        type: String,
        default: 'children'
      },
      strategy: {
        type: String,
        default: 'strict'
      }
    },

    setup(props, ctx) {
      let show = ref(false)
      let tree = ref < any > (null)
      let keys = ref < Array < string >> ([])
      let selectArray = ref < Array < SelectParams >> ([])
      let ticketArr = ref < Array < any >> ([])
      watch(
        () => props.modelValue,
        val => {
          show.value = val
        }
      )
      let hideDialog = () => {
        ctx.emit('update:modelValue', false)
      }
      let filter = ref('')
      const filterRef = ref < any > (null)
      // 过滤树形列表
      const myFilterMethod = (node, filter) => {
        const filt = filter.toLowerCase()
        return node[props.labelKey] && node[props.labelKey].toLowerCase().indexOf(filt) > -1
      }
      let clearInput = () => {
        filter.value = ''
      }
      // 有默认值-----start-------
      let flag = true
      let initDefault = () => {
        selectArray.value = []
        if (props.defaultArray && props.defaultArray.length > 0 && flag) {
          if (props.showType == 0) {
            props.defaultArray.map(e => {
              if (e.slice(0, 1) == 1) {
                const node = tree.value.getNodeByKey(e)
                if (node[props.childrenKey] && node[props.childrenKey].length > 0) {
                  findChild(node[props.childrenKey])
                } else {
                  ticketArr.value.push(node.DataType + '-' + node.DeptId)
                }
              } else {
                ticketArr.value.push(e)
              }
            })
             flag = false
          } else {
            ticketArr.value = JSON.parse(JSON.stringify(props.defaultArray))
            console.log('有默认值',ticketArr.value)
          }
         
        }
      }
      let findChild = (arr: Array < parmas > ) => {
        arr.map(e => {
          if (e[props.childrenKey] && e[props.childrenKey].length > 0) {
            findChild(e[props.childrenKey])
          } else {
            ticketArr.value.push(e.DataType + '-' + e.DeptId)
          }
        })
      }

      // 有默认值----end--------
      let showDialog = () => {
        initDefault()
        getselectArray(props.treeData)
      }
      //处理选中值-------------
      const getselectArray = (arr: parmas[]) => {
        for (var i = 0; i < arr.length; i++) {
          let j = arr[i]
          let flag = tree.value.isTicked(j[props.nodeKey])
          if (flag == true) {
            selectArray.value.push({
              Id: j[props.nodeKey],
              DeptName: j.DeptName,
              Type: j.DataType
            })
          } else {
            if (j[props.childrenKey] && j[props.childrenKey].length > 0) {
              getselectArray(j[props.childrenKey])
            }
          }
        }
      }
      let tickedTree = val => {
        if (props.showType === 0) {
          let filt = val.filter(e => e.slice(0, 1) == 2).length
          ctx.emit('getNum', filt)
        }
        setTimeout(() => {
          selectArray.value = []
          getselectArray(props.treeData)
        }, 100)
      }
      let delItemitem = (arr: parmas) => {
        arr.map(x => {
          if (x[props.childrenKey] && x[props.childrenKey].length > 0) {
            delItemitem(x[props.childrenKey])
          } else {
            keys.value.push(x[props.nodeKey])
          }
        })
      }
      let delItemArray = (arr: parmas, Id: string) => {
        for (let i = 0; i < arr.length; i++) {
          let j = arr[i]
          if (j[props.nodeKey] == Id) {
            if (j[props.childrenKey] && j[props.childrenKey].length > 0) {
              delItemitem(j[props.childrenKey])
            } else {
              keys.value.push(Id)
            }
          } else {
            if (j[props.childrenKey] && j[props.childrenKey].length > 0) {
              delItemArray(j[props.childrenKey], Id)
            }
          }
        }
      }
      let delItem = (Id: string, i: number) => {
        keys.value = []
        delItemArray(props.treeData, Id)
        tree.value.setTicked(keys.value, false)
        selectArray.value.splice(i, 1)
      }
      let goback = () => {
        ctx.emit('select', selectArray.value)
      }
      return {
        show,
        ticketArr,
        myFilterMethod,
        filter,
        filterRef,
        clearInput,
        tree,
        hideDialog,
        tickedTree,
        delItem,
        getselectArray,
        selectArray,
        delItemArray,
        delItemitem,
        showDialog,
        goback
      }
    }
  }

</script>
<style scoped>
  ::-webkit-scrollbar {
    height: 7px;
    width: 7px;
  }

  ::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 3px;
    background-color: #ddd;
  }

  ::-webkit-scrollbar-track-piece {
    background-color: #fff;
    -webkit-border-radius: 12px;
  }

  .list-title {
    height: 50px;
    padding-bottom: 10px;
    color: #606266;
    font-size: 14px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
  }

  .list-box {
    height: 420px;
    overflow-y: scroll;
  }

  .list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 3px 0 0 10px;
    border-radius: 5px;
    height: 30px;
  }

</style>
