<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">{{  t('ts.全部') }}</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">{{ t('ts.重置') }} </el-button>
      <el-button size="small" @click="closeRowDrop"> {{ t('ts.关闭') }}</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 { t } = useI18n()

const props = defineProps({
  allSchemas: {
    type: Object,
    default: null
  },
  detailAllSchemas: {
    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) => {
  // console.log('handlecheckallchange全部',val)
  checkedDataList.value = val ? allData.value : []
  isIndeterminate.value = false
  save()
}
const handlecheckedchange = (value: string[]) => {
  // console.log('handlecheckedchange',value)
  // console.log('allData',allData.value)
  const checkedCount = value.length
  checkAll.value = checkedCount === allData.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allData.value.length
  save()
}

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

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

// 保存
const save = () => {
  // 默认列表第一列（弹出详情用）
  let myTableColumns = props.allSchemas.tableColumns
  if(props.detailAllSchemas){
    myTableColumns = [...props.allSchemas?.tableColumns,...props.detailAllSchemas?.tableMainColumns]
  }
  // console.log('myTableColumns',myTableColumns)
  // console.log('checkedDataList',checkedDataList)
  // console.log('allData',allData.value)
  
  let leftArr = []
  let rightArr = []
  myTableColumns.forEach(item=>{
    if(item.fixed=='left'){
      leftArr.push(item)
    }else if(item.fixed=='right'){
      rightArr.push(item)
    }
  })
  let saveDate:any[] = [...leftArr]
  allData.value.forEach(itemLabel=>{
      const _item:any = myTableColumns.find(itemColumns => (itemColumns.label == itemLabel ))
      if(_item){
        _item.isTable = checkedDataList.value.find(checkedLabel => checkedLabel==itemLabel)?true:false
        if(_item.isTable){
          saveDate.push(_item)
        }
      }
  })
  saveDate = [...saveDate,...rightArr]
  updataTableColumns(saveDate)
  let paramsData = saveDate.map(item=>({
    label:item.label,
    fixed:item.fixed,
    field:item.field,
    isTable:item.isTable
  }))
  // console.log('paramsData',paramsData)
  RedisApi.addRedis({key: routeName.value,value: JSON.stringify(paramsData)}).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 => {
    let myTableColumns = [...props.allSchemas?.tableColumns]
    if(props.detailAllSchemas){
      myTableColumns = [...props.allSchemas?.tableColumns,...props.detailAllSchemas?.tableMainColumns]
    }
    let leftArr = []
    let rightArr = []
    myTableColumns.forEach(item=>{
      if(item.fixed=='left'){
        leftArr.push(item)
      }else if(item.fixed=='right'){
        rightArr.push(item)
      }
    })
    updateSort(myTableColumns)
    // 有缓存
    if (res) {
      checkedDataList.value = []
      allData.value = []
      // 缓存回显临时变量
      let _showTableColumns = [...leftArr]
      // 显示缓存中的字段
      JSON.parse(res).forEach((item, index) => {
        // 列表字段第一个不能参与排序及显隐操作（详情弹窗必备）
        // 列表字段操作列不能参与排序及显隐操作
        if (!item.fixed) {
          if (item.isTable) {
            checkedDataList.value.push(item.label)
          }
          let itemColumn = myTableColumns.find(myItem => (myItem.label == item.label))
          itemColumn.isTable = item.isTable
          _showTableColumns.push(itemColumn)
          allData.value.push(t(`ts.${item.label}`).replace('ts.',''))
        }
      })
      _showTableColumns = [..._showTableColumns,...rightArr]
      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) {
          checkedDataList.value.push(item.label)
          allData.value.push(t(`ts.${item.label}`).replace('ts.',''))
        }
      })
      checkAll.value = true
      updataTableColumns(myTableColumns)
    }
  }).catch(err => {
    console.log(err)
  })
}
const updateSort= (val)=>{
  val.forEach(item=>{
    if(!item.sortTableDefault){
      if(item.fixed=='left'){
        item.sortTableDefault = 0
      }else if(item.fixed=='right'){
        item.sortTableDefault = 9999
      }else{
        item.sortTableDefault = 999 // 默认999
      }
    }
  })
  val.sort((column1,column2)=>{
    return column1.sortTableDefault - column2.sortTableDefault
  })
}
// 更新主列表字段
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>