<template>
  <!-- <Dialog title="字段设置"  width="270" v-model="popoverVisible" :scroll="true" :maxHeight="500"> -->
    <div class="test_wrapper" @dragover="dragover($event)">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handlecheckallchange">全部</el-checkbox>
      <el-checkbox-group v-model="checkedDataList" @change="handlecheckedchange">
        <draggable :list="allData" :force-fallback="true" chosen-class="chosen" animation="300" @end="dragend" @update="dragenter" >
          <template #item="{element}">
            <div><el-checkbox :key="element" :label="element">{{element}}</el-checkbox></div>
          </template>
        </draggable>
      </el-checkbox-group>
    </div>
    <div class="footer">
    <!-- <template #footer> -->
      <el-button size="small" @click="reset">重置</el-button>
      <el-button size="small" @click="closeRowDrop">关闭</el-button>
    <!-- </template> -->
  </div>
  <!-- </Dialog> -->
</template>
<script setup lang="ts">
import { ElMessageBox } from 'element-plus'
import * as RedisApi from '@/api/redis'
import draggable from "vuedraggable";

defineOptions({ name: 'RowDrop' })


const props = defineProps({
  allSchemas: {
    type: Object,
    default: null
  }
})
const popoverVisible = ref(false)
const route = useRoute() // 路由信息
const routeName = ref(route.name)


const isIndeterminate = ref(true)
const allData = ref([]) // 字段设置列表展现字段 除操作外
const checkedDataList = ref([])
const checkAll = ref(true)
const handlecheckallchange = (val: boolean) => {
  checkedDataList.value = val ? allData.value : []
  isIndeterminate.value = false
  save()
}
const handlecheckedchange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allData.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allData.value.length
  save()
}

const reset = () => {
  ElMessageBox.confirm('重置后，字段设置将恢复初始设置，是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    RedisApi.deleteRedis(routeName.value).then(() => {
      initSelectSta()
      closeRowDrop()
    }).catch(err => {
      console.log(err)
    })
  })
}

// 关闭页面
const closeRowDrop = () => {
  emit('closeRowDrop')
}

// 保存
const save = () => {
  let saveDate:any[] = []
  // 默认列表第一列（弹出详情用）
  saveDate.push(props.allSchemas.tableColumns[0])
  allData.value.forEach((item) => {
    const _item:any = props.allSchemas.tableColumns.find(itemColumns => (itemColumns.label == item ))
    _item.isTable = false
    if (checkedDataList.value.indexOf(_item.label) > -1) {
      _item.isTable = true
      saveDate.push(_item)
    }
  })
  // 默认操作列
  saveDate.push(props.allSchemas.tableColumns[props.allSchemas.tableColumns.length-1])
  updataTableColumns(saveDate)
  console.log(99, saveDate)
  RedisApi.addRedis({key: routeName.value,value: JSON.stringify(saveDate)}).then(() => {
  }).catch(err => {
    console.log(err)
  })
}

// 记录移动过程中信息
const dragenter = (e) => {
  e.preventDefault()
}

// 拖拽最终操作
const dragend = ( e) => {
  sort(checkedDataList.value,allData.value)
  save()
  e.preventDefault()
}

// 数组排序 arr1 按照 arr2 排序
const sort = (arr1,arr2) => {
  arr1.sort((a,b) => arr2.indexOf(a)-arr2.indexOf(b))
}

// 拖动事件（主要是为了拖动时鼠标光标不变为禁止）
const dragover = (e) => {
  e.preventDefault()
}

// 初始化当前全选状态
const initSelectSta = () => {
  RedisApi.getRedis(routeName.value).then(res => {
    const _myTableColumns = props.allSchemas?.tableColumns
    // 有缓存
    if (res) {
      checkedDataList.value = []
      allData.value = []
      // 缓存回显临时变量
      const _showTableColumns = []
      _showTableColumns.push(_myTableColumns[0])
      // 显示缓存中的字段
      JSON.parse(res).forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        // 列表字段操作列不能参与排序及显隐操作
        if (!item.fixed) {
          if (item.field != 'action') {
            checkedDataList.value.push(item.label)
            _showTableColumns.push(_myTableColumns.find(myItem => (myItem.label == item.label)))
            allData.value.push(item.label)
          }
        }
      })
      // 字段设置 显示全部字段
      _myTableColumns?.forEach((myTableItem, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        // 列表字段操作列不能参与排序及显隐操作
        if (!myTableItem.fixed) {
          if (myTableItem.field != 'action') {
            if (allData.value.indexOf(myTableItem.label) == -1) {
              allData.value.push(myTableItem.label)
            }
          }
        }
      })
      
      _showTableColumns.push(_myTableColumns[_myTableColumns.length-1])
      if(checkedDataList.value.length>0){
        if(allData.value?.length != checkedDataList.value.length){
          isIndeterminate.value = true
        }else{
          isIndeterminate.value = false
          checkAll.value = true
        }
      }else{
        isIndeterminate.value = false
        checkAll.value = false
      }
     
      updataTableColumns(_showTableColumns)
     
    } else { // 无缓存
      checkedDataList.value = []
      allData.value = []
      _myTableColumns?.forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        // 列表字段操作列不能参与排序及显隐操作
        if (!item.fixed) {
          if (item.field != 'action') {
            checkedDataList.value.push(item.label)
            allData.value.push(item.label)
          }
        }
      })
      checkAll.value = true
      updataTableColumns(_myTableColumns)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 更新主列表字段
const updataTableColumns = (val) => {
  emit('updataTableColumns', val)
}

// 传递给父类
const emit = defineEmits([
  'updataTableColumns',
  'closeRowDrop'
])

/** 初始化 **/
onMounted(() => {
  initSelectSta()
})

defineExpose({
  popoverVisible
})

</script>
<style lang="scss" scoped>
.test_wrapper{
  max-height: calc(100vh - 350px);
  overflow-y: auto;
}
.footer{
  margin-top: 10px;
}
.el-checkbox-group ::v-deep(.el-checkbox .el-checkbox__inner){
  background: url(../../assets/imgs/Eyes-closed.png) no-repeat 0px 0px;
  background-size: 16px;
  width: 16px;
  height: 16px;
  border: none;
}
.el-checkbox-group ::v-deep(.el-checkbox .is-checked .el-checkbox__inner){
  background: url(../../assets/imgs/eye.png) no-repeat 0px 0px;
  background-size: 16px;
  width: 16px;
  height: 16px;
  border: none;
}
</style>