<template>
  <Dialog title="字段设置"  width="270" v-model="popoverVisible">
    <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="buttonsBox">
      <el-button size="mini" @click="reset">重置</el-button>
      <el-button size="mini" @click="closeRowDrop">关闭</el-button>
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import * as tableColumnsFun from '@/utils/disposition/tableColumns'
import * as RedisApi from '@/api/redis'
import ButtonBase from '@/components/XButton/src/ButtonBase.vue'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import draggable from "vuedraggable";

defineOptions({ name: 'RowDrop' })

const props = defineProps({
  HeadButttondata: {
    type: Array,
    default: () => {
      return []
    }
  },
  routeName: {
    type: String,
    default: null
  },
  tableColumns: {
    type: Array,
    default: () => {
      return []
    }
  }
})
const oldData = ref()
const newData = ref()
const dataList = ref([])
const allSeletType = ref('NoSelect')
const buttonsData = ref([defaultButtons.defaultSetBtn(null)])
const popoverVisible = ref(false)

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(props.routeName).then(res => {
      initSelectSta()
      closeRowDrop()
    }).catch(err => {
      console.log(err)
    })
  })
}

// 关闭页面
const closeRowDrop = () => {
  popoverVisible.value = false
}
  
// 格式化表头数据
const formatData = (val) => {
  dataList.value = JSON.parse(JSON.stringify(val))
}

// 保存
const save = () => {
  let saveDate = tableColumnsFun[props.routeName].allSchemas.tableColumns
  sort(saveDate, allData)
  console.log(99, saveDate)
  
  // // 默认列表第一列（弹出详情用）
  // saveDate.push(tableColumnsFun[props.routeName].allSchemas.tableColumns[0])
  // // 默认列表最后一列（操作）
  // saveDate.push(tableColumnsFun[props.routeName].allSchemas.tableColumns[tableColumnsFun[props.routeName].allSchemas.tableColumns.length-1])
  // checkedDataList.value.forEach((item,index) => {
  //   item.isTable = false
  //   if (tableColumnsFun[props.routeName].allSchemas.tableColumns.indexOf(item) > 0) {
  //     item.isTable = true
  //     saveDate.push(item)
  //   } else {

  //   }
  // })
  // tableColumnsFun[props.routeName].allSchemas.tableColumns.forEach((item,index) => {
  //   if (index == 0) {
  //     saveDate.push(item)
  //   }
  //   if ((tableColumnsFun[props.routeName].allSchemas.tableColumns.length - 1) == index) {
  //     saveDate.push(item)
  //   } else {
  //     item.isTable = false
  //     if (checkedDataList.value.indexOf(item.label) > 0) {
  //       item.isTable = true
  //       saveDate.push(item)
  //     }
  //   }
  // })

  // updataTableColumns(saveDate)
  // RedisApi.addRedis({key: props.routeName,value: JSON.stringify(saveDate)}).then(res => {
  // }).catch(err => {
  //   console.log(err)
  // })
}

// 记录移动过程中信息
const dragenter = (value, e) => {
  // this.newData = value
  console.log('2222222',value)
  
  e.preventDefault()
}

// 拖拽最终操作
const dragend = (value, e) => {
  
  console.log('3333333',allData)
  sort(checkedDataList.value,allData.value)
  console.log(143,checkedDataList )
  save()
  // if (this.oldData !== this.newData) {
  //   let oldIndex = this.dataList.indexOf(this.oldData)
  //   let newIndex = this.dataList.indexOf(this.newData)
  //   let newItems = [...this.dataList]
  //   // 删除老的节点
  //   newItems.splice(oldIndex, 1)
  //   // 在列表中目标位置增加新的节点
  //   newItems.splice(newIndex, 0, this.oldData)
  //   this.dataList = [...newItems]
  //   this.save()
  // }
}

// 数组排序 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(props.routeName).then(res => {
    if (res) {
      checkedDataList.value = []
      allData.value = []
      updataTableColumns(JSON.parse(res))
      // 显示缓存中的字段
      JSON.parse(res).forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        if (index != 0) {
          if (item.field != 'action') {
            checkedDataList.value.push(item.label)
          }
        }
      })
      // 字段设置 显示全部字段
      dataList.value.forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        if (index != 0) {
          if (item.field != 'action') {
            allData.value.push(item.label)
          }
        }
      })
    } else {
      checkedDataList.value = []
      allData.value = []
      dataList.value.forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        if (index != 0) {
          if (item.field != 'action') {
            checkedDataList.value.push(item.label)
            allData.value.push(item.label)
          }
        }
      })
      checkAll.value = true
      updataTableColumns(dataList.value)
    }
  }).catch(err => {
    console.log(err)
  })
  
}

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

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

/** 初始化 **/
onMounted(() => {
  formatData(props.tableColumns)
  initSelectSta()
})

defineExpose({
  popoverVisible
})

</script>
<style lang="scss" scoped>

.rowDropContain {
 

  .el-popover {
    position: fixed !important;
    right: 30px !important;
    padding: 0 !important;
    .el-popper {
      left: 85% !important;
    }
    
  }
  

  .transition-wrapper {
    display: block;
    max-height: calc(90vh - 280px);
    overflow: auto;
    padding: 0 0 20px 20px;

    .sort-item {
      margin-bottom: 6px;
      display: flex;
      cursor: grab;
      align-items: center;

      &:last-child {
        margin-bottom: 0;
      }

      .lable {
        padding: 0 15px 0 10px;
      }
    }
  }

  .el-divider--horizontal {
    margin: 20px;
    width: calc(100% - 40px);
  }

  .text {
    color: #333;
    font-weight: bold;
    padding: 20px 0 0 20px;
  }

  .allSelectContent {
    user-select: none;
    cursor: pointer;
    padding: 0 0 10px 20px;

    .icon {
      font-size: 18px;
      vertical-align: middle;
      color: #409EFF;
      margin-right: 5px;
    }
  }

  .buttonsBox {
    text-align: center;
    margin: 0;
    padding: 15px;
    border-top: #eee solid 1px;
  }

  .checkbox-svg {
    width: 20px;
    flex-shrink: 0;
    fill: currentColor;
    color: #999;
    font-size: 18px;
    cursor: pointer;

    &.show {
      color: #409EFF;
    }
  }
}
</style>