<script setup>
import { CommonTable,KsSearch,KsPagin,KSTree,KsDialog } from '@ksconsole/components'
import { usePageSearch,useColumnsSet,usePageDownload } from "@ksconsole/hooks";
import { getList,getTreeData } from "../mock/index.js";
import { Table, TableColumn,Button,Icon,Message,ButtonGroup } from "@king-design/vue";
import { ref,reactive,nextTick, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {isObject,has,assign,unset,mapKeys,eq,get} from 'lodash-es'

const route = useRoute();
const router = useRouter();
const { tableData } = usePageSearch(getList);
// 搜索条件
const searchOptions = [
    {
        key: 'name',
        label: '实例名称',
        placeholder: '我是自定义的搜索条件',
    },
    {
        key: 'id',
        label: '实例ID',
    },
    //  {
    //     key: 'tele',
    //     label: '手机',
    // },
    // {
    //     key: 'type',
    //     label: '类型',
    // },
]
const onSearch = (v) => {
    console.log("🚀 ~ onSearch ~ v:", v)
}
const total = ref(10)
onMounted(() => {
  // setTimeout(() => {
  //   total.value = 0
  // }, 2000)
})
const selectKeys = ref(0)
const current = ref(1)
const onChange = () => {

}
const columns = ref([
  {
    key: "instanceType",
    title: "普通",
    disabled: true,
  },
  {
    type: 'slot',
    slotName: 'test',
    title: "开头"
  },
  {
    type: 'format',
    key: "productType",
    title: "格式化",
    format([data, row, i]) {
      return `自定义${row.instanceIP}`
    },
    group: [
      {label: '全部', value: ''},
      {label: '运行中', value: 'active'},
      {label: '已关闭', value: 'stopped'}
    ]
  },
  {
    key: "instanceName",
    title: "link可点击带回调",
    type: 'link',
    click: ([val, row, i]) => {
     alert(`我被点击了${val}`)
    }
  },
  {
    key: "region",
    title: "状态",
    type: 'status',
    props([data, row, i]) {
      return {
        type: data === 'active' ? 'success' : 'error',
        text: data === 'active' ? '运行中' : '已关闭'
      }
    }
  }
]);
const columnKey = 'test'
const { columnDatas,columnsChange } = useColumnsSet(columns, columnKey)
const { getDownDatas } = usePageDownload(columns,tableData,'test');
const downloadFn = () => {
  getDownDatas()
}
const firstColumnsGroup = ref([
  {label: '全部', value: ''},
  {label: '运行中', value: 'active'},
  {label: '已关闭', value: 'stopped'}
])

function firstChangeGroup(group) {
  console.log(group)
}

const secondGroup = ref({
  instanceType: []
})

// --------tree组件相关start-------
let treeData=ref([])
const treeRef = ref(null);
const uniqueId = ref(100);
let selectedKeys=ref([])
async function getTreeDataApi() {
  treeData.value = await getTreeData()
  selectedKeys.value=[treeData.value[1].key]
}
getTreeDataApi()


// 异步展开子节点，在子组件渲染后调用
function expandNode(key) {
  nextTick(() => {
        // 在这里，你可以调用子组件的展开方法
        treeRef.value.tree.expand(key);
      });
}
// 添加子节点
function appendNode({data, node, index}) {
  console.log("父组件监听到appendNode事件", data, node, index);
  data.children = data.children || [];
  uniqueId.value++;
  data.children.push({
    key: `${uniqueId.value}`,
    label: "子节点" + `${uniqueId.value}`,
  });
  expandNode(data.key)
}
// 添加一级节点
function rootAppendNode() {
  console.log("父组件监听到rootAppendNode事件");
  uniqueId.value++;
  treeData.value.push({
    key: `${uniqueId.value}`,
    label: "子节点" + `${uniqueId.value}`,
  })
}
// 删除节点
function removeNode({data, node, index}) {
  console.log("父组件监听到removeNode事件", data, node, index);
   const children = node.parent ? node.parent.data.children : treeData.value;
  children.splice(index, 1);
}
// 编辑节点
function editNode({data, node, index}) {
  console.log("父组件监听到editNode事件", data, node, index);
}
// 拖拽节点
function dragend(data) {
  console.log("父组件监听到dragend事件", data);
}
// 搜索节点
function searchNode(keywords) {
  console.log("父组件监听到searchNode事件", keywords);
}
// 节点选中变化
function changeSelectedKeys(data) {
  console.log("父组件监听到changeSelectedKeys事件", data);
}

// --------tree组件相关end-------


const submitloading = ref(false)
const onSubmit = () => {
  console.log('我是确认')
  let isClose = true
  submitloading.value = true
  setTimeout(() => {
      submitloading.value = false
      isClose = false
      if(!isClose) {
        Message.error('操作失败')
      }else {
        globalData._backDetails('memberAdd',router,route)
      }
  }, 2000);
}
const _toDetails = (query, queryKey = 'details',router,route)=> {
    if (!isObject(query)) {
        query = { [queryKey]: query }
    }
    // 路由中已经存在 参数 且 值相同
    mapKeys(route.query, (value, key) => {
        if (has(query, key) && eq(value, get(query, key))) {
            unset(query, key)
        }
    })
    query = assign({}, route.query, query)
    router.replace({ query })
} 
/**
* 详情返回
* 去除当前页面的 query 中 detailsVisible 触发隐藏
*/
const _backDetails =  (queryKey,router,route) => {
    const query = omit(assign({}, route.query), concat(
        [
            'details',
            '_readonly',
            queryKey,
        ]
    ))
    router.replace({ query })
}
const onAdd = () => {
  _toDetails('','memberAdd',router,route)

}
const onEdit = () => {
  _toDetails('1111','memberEdit',router,route)
}

</script>

<template>
  <div>
     <ks-dialog 
      title = '关联成员'
      querykey='memberAdd'
      @onSubmit='onSubmit'
      :submitloading ='submitloading'
     >
      我是内容
     </ks-dialog>
     <ks-dialog 
      title = '编辑'
      querykey='memberEdit'
      dialogType='drawer'
      @onSubmit='onSubmit'
      :submitloading ='submitloading'
      
     >
     <!-- <template #myfooter>
      我是footer
     </template> -->
     </ks-dialog>
  <KSTree ref="treeRef" :data="treeData"  @append="appendNode" @rootAppend="rootAppendNode" @remove="removeNode" @edit="editNode" @dragend="dragend" @search="searchNode" :showRootAppend="true" titleAlign="left" :selectedKeys="selectedKeys" @changeSelectedKeys="changeSelectedKeys">组织</KSTree>
         <!-- hasDown
            @export="downloadFn" -->
    <ks-search
      :searchOptions ='searchOptions'
      noRetrieval
      @onSearch='onSearch'
      hasDown
      @onExport="downloadFn"
      hasRefresh
      :columnDatas="columnDatas"
      :columnKey='columnKey'
      @changeColumns ='columnsChange'
    >
      <Button type='primary' ><Icon class="k-icon-add" @click='onAdd'/> 关联成员1 </Button>   
      <Button @click='onEdit'> 编辑</Button>
    </ks-search>
    <CommonTable :a="1" test="我的" :data="tableData" :columns="columnDatas" :group="{ productType: '' }" @$change:group="firstChangeGroup">
      <template v-slot:test>
        <TableColumn title="开头111" key="test1">
          <template v-slot:template="[data, index]">
            <span>{{ data.region }}</span>
          </template>
        </TableColumn>
      </template>
      <TableColumn title="测试111" key="test2">
        <template v-slot:template="[data, index]">
          <span>{{ data.region }}</span>
        </template>
      </TableColumn>
    </CommonTable>
    <h3> 有已经选中数据</h3>
    <ks-pagin 
      className='zy-demo'
      :total="total" 
      :selectKeys='selectKeys' 
      :value="current"
      @change="onChange" 
    />
    <h3> 没有已经选中数据</h3>
    <ks-pagin 
      className='zy-demo'
      :total="total" 
      :value="current"
      @change="onChange" 
    />
     <h3> 无共多条数据</h3>
      <ks-pagin 
        className='zy-demo'
        :total="total" 
        noTotal
        :value="current"
        @change="onChange" 
      />
    <Table :data="tableData" :group="{ instanceName: '',region: ''  }" @$change:group="firstChangeGroup">
      <TableColumn key="instanceType" title="用户名"></TableColumn>
      <TableColumn key="instanceName" title="姓名" :group="firstColumnsGroup"></TableColumn>
      <TableColumn key="region" title="邮箱" :group="firstColumnsGroup"></TableColumn>
    </Table>
    <Table :data="tableData" :group="{
  instanceType: []
}" @$change:group="firstChangeGroup">
      <TableColumn key="instanceType" title="用户名" :group="firstColumnsGroup" multiple></TableColumn>
      <TableColumn key="instanceName" title="姓名"></TableColumn>
      <TableColumn key="region" title="邮箱"></TableColumn>
    </Table>
  </div>
</template>

<style scoped>
:deep(.zy-demo) {
  margin: 20px;
}
</style>
