<template>
  <el-drawer :model-value="drawerShow" @close="close" title="编辑列表" size="40%">
    <!-- <el-checkbox  label="12" />
        <el-checkbox  label="2" /> -->
    <el-table :data="columnRef" style="width: 100%; height: 700px" border ref="tableEl1">
      <el-table-column
        v-for="column in headtop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        flexible
      >
        <template #header>
          <el-text class="mx-1">{{ column.label }}</el-text>
        </template>
        <template #default="scope">
          <el-text class="mx-1" v-if="column.prop == 'label'">{{ scope.row[column.prop] }}</el-text>
          <el-checkbox
            v-else-if="column.label == '隐藏'"
            v-model="scope.row.head"
            @change="checkboxitem(scope)"
          >
          </el-checkbox>
          <el-checkbox
            v-else-if="column.label == '冻结'"
            v-model="scope.row.fixed"
            :disabled="scope.row.label === '操作'"
            @change="checkboxitem(scope)"
          >
          </el-checkbox>
          <el-checkbox
            v-else-if="column.label == '排序'"
            v-model="scope.row.sortable"
            @change="checkboxitem(scope)"
          >
          </el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <!-- </el-checkbox-group> -->
    <div></div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, watchEffect, onMounted, watch, inject, nextTick } from 'vue';
import type { PropType } from 'vue';
import { useRoute } from 'vue-router';
import { getTableSeting, postSaveTableSeting } from '@/api/basic/table';
const functions = inject('functions') as any;
import Sortable from 'sortablejs';
import { getObjType, handleClearTableQuery } from '@/utils/util';
interface TableColumnType {
  /** 表格列的key */
  prop: string;
  /** 表格列的名字 */
  label: string;
  /**
   * 对应列表头的类型
   * 0:直接显示为单选，prop，label，全部传空
   * 1:普通表格，正常显示
   * 2:带输入框表格
   * 3:带下拉框表格
   * 4:带日期选择器列
   * 5:带日期时间选择器
   * 6:操作栏，prop，label，全部传空
   * 7:测试
   */
  type: number | string;
  /** 用于接受表头的值 */
  values: number | string;
  /** 表头宽度 number string undefined */
  width: number | string | undefined;
  /** 下拉框可选项 */
  checkarr?: {
    value: string | number;
    label: string | number;
  }[];
  /** 是否固定表头
   * true false
   * left right
   */
  fixed: boolean | string;
  /** 是否统计
   * true false 或者直接不写该参数
   */
  isshowSummary?: boolean;
  /** 是否排序
   * true false 或者直接不写该参数
   */
  sortable?: boolean;
  /** 是否显示列
   * true false 或者直接不写该参数
   */
  head?: boolean;
}
interface headtoptype {
  prop: string;
  label: string;
  width?: string | number;
}

const $route = useRoute();

let emit = defineEmits(['setcolum', 'closce', 'update:modelValue']);
let props = defineProps({
  // columnList: {
  //   type: Array as PropType<TableColumnType[]>,
  //   required: true,
  // },
  drawerShow: {
    type: Boolean as PropType<boolean>,
    required: true,
  },
  modelValue: {
    type: Array as PropType<TableColumnType[]>,
    required: true,
  },
  /** 从本地获取的list名称 */
  columnListName: {
    type: String as PropType<string>,
    required: false,
    default: 'columnList',
  },
});

const columnRef = ref([...props.modelValue]);

const tableEl1 = ref();

// const _arr = functions.getStorage($route.fullPath + props.columnListName);

// if (_arr) {
//   columnRef.value = [..._arr];
//   handleClearTableQuery(_arr);
//   emit('update:modelValue', _arr);
// }

const initTable = async () => {
  try {
    console.log('$route :>> ', $route);
    const submitData = { tableKey: $route.path + props.columnListName };

    const res = await getTableSeting(submitData);

    const { code, data } = res.data;
    if (code !== 200) return;

    const _arr = JSON.parse(data);

    if (getObjType(_arr) !== 'array') return;

    // 设置的表格数据
    const _setArr = [];

    // 本地设置的表格数据
    const _oldArr = [...columnRef.value];

    for (let j = 0; j < _arr.length; j++) {
      const item = _arr[j];
      for (let i = 0; i < _oldArr.length; i++) {
        const value = _oldArr[i];

        if (item.prop + item.label + item.type !== value.prop + value.label + value.type) continue;
        _setArr.push(item);
        _oldArr.splice(i, 1);
        break;
      }
    }

    _setArr.push(..._oldArr);

    console.log('_setArr :>> ', _setArr);
    columnRef.value = [..._setArr];
    handleClearTableQuery(_setArr);
    emit('update:modelValue', _setArr);
  } catch (error) {
    console.log('error :>> ', error);
  }
};

initTable();

onMounted(() => {
  for (let index = 0; index < props.modelValue.length; index++) {
    const item = props.modelValue[index];

    item.fixed =
      item.fixed === true || item.fixed === 'right' || item.fixed === 'left' ? item.fixed : false;
  }
  nextTick(() => {
    console.log('onMounted');
    initSortable();
  });
});

watch(
  () => props.drawerShow,
  val => {
    if (val)
      nextTick(() => {
        initSortable();
        console.log('watch');
      });
  }
);

const initSortable = () => {
  if (tableEl1.value && tableEl1.value.$el) {
    const el1 = tableEl1.value.$el.querySelector('.el-table__body tbody');
    console.log(el1);
    Sortable.create(el1, {
      // handle: '.move-icon',
      animation: 100, // 动画
      onEnd: async ({ newIndex, oldIndex }) => {
        console.log(newIndex, oldIndex);
        const arr = props.modelValue;
        const currRow = arr.splice(oldIndex, 1)[0];
        arr.splice(newIndex, 0, currRow);

        // functions.setStorage($route.fullPath + props.columnListName, arr);
        postSaveTableSeting({
          tableKey: $route.path + props.columnListName,
          tableSetCongig: JSON.stringify(arr),
        });
        // emit('update:modelValue', arr);
        // nextTick(() => {
        //   emit('setcolum', arr, 4);
        // })
      },
    });
  }
};

function close() {
  emit('closce', false);
}

function checkboxitem({ row }) {
  postSaveTableSeting({
    tableKey: $route.path + props.columnListName,
    tableSetCongig: JSON.stringify(props.modelValue),
  });
}
let headtop = ref<headtoptype[]>([
  {
    prop: 'label',
    label: '列名',
    width: '',
  },
  {
    prop: '',
    label: '隐藏',
    // width:'150'
  },
  {
    prop: '',
    label: '冻结',
    // width:'150'
  },
  {
    prop: '',
    label: '排序',
    // width:'150'
  },
]);
</script>
<style lang="scss"></style>
