<template>
  <div class="content_main content_main_page content_main_page_new">
    <div class="card mb24">
      <!-- 工具栏 -->
      <div class="table-tool" v-if="showTool">
        <a-button
          type="outline"
          class="setting-item setting-field"
          @click="handleToolClick($event.target, item)"
          v-for="(item, index) in settingConfig"
        >
          <component :is="item.icon"></component>
          <span>{{ item.label }}</span>
        </a-button>
      </div>
      <!-- 卡片菜单 -->
      <float-card
        v-model:remoteFieldData="remoteFieldData"
        v-model:visible="isShowCardLevel1"
        :position="cardLevel1Position"
        :defaultFieldsData="defaultFieldsData"
      ></float-card>
      <!-- 表格组件 -->
      <designTable
        :columns="columnsData"
        :data="data"
        v-bind="tableAttr"
        @pageChange="handlePageChange"
      ></designTable>
      <!-- 关联弹窗 -->
      <relationSqlTableModal
        v-model:visible="relationSqlModalVisible"
        @relationData="handleRelationData"
        @createNewData="handleCreateNewData"
      ></relationSqlTableModal>
      <!-- 关联抽屉 -->
      <relationDataDrawer
        v-model:visible="relationDataDrawerVisible"
        :componentId="props.componentId"
        @confirm="handleRelationDrawerConfirm"
      ></relationDataDrawer>
      <!-- 创建虚拟表 -->
      <createVirtualTable v-model:visible="createVirtualTableVisible"></createVirtualTable>
      <!-- 管理字段 -->
      <fieldManagerDrawer
        v-model:visible="fieldManagerDrawerVisible"
        :table_id="table_id"
      ></fieldManagerDrawer>
      <!-- 增加字段 -->
      <addVirtualTableField
        v-model:visible="addVirtualTableFieldDrawerVisible"
      ></addVirtualTableField>
    </div>
  </div>
</template>
<script setup lang="jsx">
/* @Author: 邓威 ilovede@163.com
 * @Date: 2024-11-22 11:30:01
 * @LastEditors: 邓威
 * @LastEditTime:
 * @Description:
 */
import {
  Drag,
  PreviewOpen,
  PreviewClose,
  More,
  Help,
  User,
  Right,
  TextStyleOne,
  HashtagKey,
  CalendarThirtyTwo,
  Link,
  RadioTwo,
  Check,
  ArithmeticOne,
  SwitchButton,
  Refraction,
  MouseOne,
  Me,
  Tag,
  ListNumbers
} from '@icon-park/vue-next'
import { Message } from '@arco-design/web-vue'
import './index.scss'
import designTable from './tables/index.vue'
import floatCard from './floatCard/floatCard1.vue'
import relationSqlTableModal from './modal/relationSqlTable.vue'
import relationDataDrawer from './drawer/relationDataDrawer.vue'
import addVirtualTableField from './drawer/addVirtualTableField.vue'
import createVirtualTable from './drawer/createVirtualTable.vue'
import fieldManagerDrawer from './drawer/fieldManagerDrawer.vue'
import request from './utils/request'
import emitter from './utils/mitt'
import getSearchParams from './utils/geSearchParams'
//获取写死的id
let props = defineProps({
  componentId: {
    type: String,
    default: '',
    required: true
  }
})

let showTool = ref(false)
// 监听 popstate 事件
let handleQueryChange = () => {
  showTool.value = getSearchParams('mode') === 'setting'
}

onMounted(() => {
  //页面加载首次调用
  if (!showTool.value) {
    handleQueryChange()
  }
  window.addEventListener('popstate', handleQueryChange)
})

onUnmounted(() => {
  window.removeEventListener('popstate', handleQueryChange)
})

//流程:
//1.请求服务器传递组件id,查看是否有数据源

//2.如果没有数据源,弹窗提供两个选项,新建数据源/选择已有数据源

//3.新增数据源展开新增数据源抽屉,并且进行添加

//4.绑定数据源可以选择已有的表table_id进行绑定,发送请求

//关联数据弹窗

let relationSqlModalVisible = ref(false)
//关联数据抽屉
let relationDataDrawerVisible = ref(false)
//增加虚拟表抽屉
let createVirtualTableVisible = ref(false)
//增加字段抽屉
let addVirtualTableFieldDrawerVisible = ref(false)
//字段管理抽屉
let fieldManagerDrawerVisible = ref(false)
let table_id = ref('')

emitter.on('virtualTableSaveAnddManager', (tableId) => {
  fieldManagerDrawerVisible.value = true
  table_id.value = tableId
})

emitter.on('addVirtualTableField', () => {
  addVirtualTableFieldDrawerVisible.value = true
})
emitter.on('relationConfirm', () => {
  getComponentData()
})
emitter.on('addVirtualTableField', (tableId) => {
  console.log(tableId)
})
//关联数据按钮
let handleRelationData = () => {
  relationDataDrawerVisible.value = true
}
//创建新的关联
let handleCreateNewData = () => {
  //   relationDataDrawerVisible.value = true
  createVirtualTableVisible.value = true
}
//点击抽屉确定的时候
let handleRelationDrawerConfirm = () => {
  getComponentData()
}
//卡片菜单1位置
let cardLevel1Position = ref({ left: 900, top: 0 })
//是否显示卡片菜单1
let isShowCardLevel1 = ref(false)
//获取点击元素的x y坐标
let getClickTargetPosition = (target) => {
  //获取dom的rect属性
  let rect = target.getBoundingClientRect()
  //   console.log(rect)
  cardLevel1Position.value = {
    top: rect.bottom,
    left: rect.left
  }
}
//根据类型映射图标
let typeInfoMaps = new Map([
  ['serial', { fieldLabel: '序号', icon: markRaw(ListNumbers) }],
  ['image', { fieldLabel: '图片', icon: markRaw(Me) }],
  ['tag', { fieldLabel: '标签', icon: markRaw(Tag) }],
  ['switch', { fieldLabel: '开关', icon: markRaw(SwitchButton) }],
  ['text', { fieldLabel: '文本', icon: markRaw(TextStyleOne) }],
  ['number', { fieldLabel: '数字', icon: markRaw(ArithmeticOne) }],
  ['date', { fieldLabel: '日期', icon: markRaw(CalendarThirtyTwo) }],
  ['file', { fieldLabel: '附件', icon: markRaw(Link) }],
  ['radios', { fieldLabel: '单选', icon: markRaw(RadioTwo) }],
  ['action', { fieldLabel: '操作', icon: markRaw(MouseOne) }]
])

//点击工具栏
let handleToolClick = (target, item) => {
  if (item.key === 'fieldSetting') {
    let parentTarget = target.closest('.setting-field')
    isShowCardLevel1.value = true
    getClickTargetPosition(parentTarget)
  } else if (item.key === 'relationData') {
    relationDataDrawerVisible.value = true
  } else if (item.key === 'new') {
    createVirtualTableVisible.value = true
  }
}
//卡片1字段数据,后续从远程获取
let remoteFieldData = ref([
  //   {
  //     id: 1,
  //     title: '单选',
  //     icon: markRaw(TextStyleOne),
  //     fieldLabel: '单选',
  //     fieldType: 'single',
  //     isVisible: true
  //   },
])

//使用计算属性让内容变更的时候重新生成数据,比如显示字段隐藏字段
let columnsData = computed(() => {
  return remoteFieldData.value
    .filter((item) => item.isVisible) // 首先过滤出 isVisible 为 true 的数据
    .map((item) => {
      // 然后根据 fieldType 处理每个字段
      switch (item.fieldType) {
        case 'switch':
          return {
            ...item,
            render: ({ record }) => {
              return <a-switch v-model={record[item.dataIndex]}></a-switch>
            }
          }
        case 'action':
          return {
            ...item,
            render: ({ record }) => {
              //   console.log(record[item.dataIndex])
              return (
                <div>
                  <a-button type="primary" status="success" size="small" style="margin-right: 8px;">
                    <icon-edit />
                    编辑
                  </a-button>
                  <a-button type="primary" status="danger" size="small" style="margin-right: 8px;">
                    <icon-delete />
                    删除
                  </a-button>
                </div>
              )
            }
          }
        case 'image':
          return {
            ...item,
            render({ record }) {
              //   console.log(record)
              //获取静态资源前缀
              //判断是否要拼接域名
              let currentData = record[item.dataIndex]
              let el = null
              const isArray = /^\[\s*(.+\s*,\s*)*.*\s*\]$/.test(currentData)
              console.log(isArray)
              if (isArray) {
                el = JSON.parse(currentData).map((srcItem) => {
                  if (srcItem.includes('http')) {
                    return <a-image width="100" preview={true} src={srcItem} />
                  } else {
                    let src = item.staticDomain + '/' + srcItem
                    return <a-image width="50" preview={true} src={src} />
                  }
                })
                // console.log(el)
              } else {
                if (currentData.includes('http')) {
                  el = <a-image width="100" preview={true} src={currentData} />
                } else {
                  let src = item.staticDomain + '/' + currentData
                  el = <a-image width="100" preview={true} src={src} />
                }
              }
              return el
            }
          }
        case 'tag':
          return {
            ...item,
            render({ record }) {
              let options = item.options ?? [{}]
              let color = 'gray'
              if (options.length) {
                color = options[0].value
              }
              return (
                <a-tag color={color} size="large">
                  {record[item.dataIndex]}
                </a-tag>
              )
            }
          }
        case 'serial':
          let newData = []
          data.value.forEach((dataItem, index) => {
            newData.push({
              ...dataItem,
              [item.dataIndex]: index + 1
            })
          })
          data.value = newData
          console.log(newData)

        default:
          return item // 如果没有特殊处理，返回原始字段
      }
    })
})

//修改列数据
let modifierColumns = async (columnList) => {
  try {
    let res = await request('modifierVirtualTableDataColumns', {
      component_id: props.componentId,
      columnList
    })
  } catch (e) {
    Message.error('修改失败:' + e.toString())
  }
}
//列数据变更的时候请求服务器保存数据
//延迟侦听 避免首次进入数据处理的时候多发一次请求
let timeout = setTimeout(() => {
  watch(
    columnsData,
    (newVal) => {
      modifierColumns([...remoteFieldData.value])
    },
    {
      deep: true
    }
  )
}, 2000)

//卡片3字段数据 ['action', { fieldLabel: '操作', icon: markRaw(MouseOne) }]
let commonFields = []
for (const [key, value] of typeInfoMaps) {
  let obj = {
    id: key,
    fieldType: key,
    ...value
  }
  commonFields.push(obj)
}
let defaultFieldsData = ref([
  {
    tag: '常规',
    fields: commonFields
  }
])
//工具栏配置
let settingConfig = ref([
  {
    icon: <icon-settings />,
    label: '字段设置',
    key: 'fieldSetting'
  },
  {
    icon: <icon-relation />,
    label: '绑定数据源',
    key: 'relationData'
  },
  {
    icon: <icon-filter />,
    label: '筛选',
    key: 'filter'
  },
  {
    icon: <icon-plus />,
    label: '新增虚拟表',
    key: 'new'
  }
])

//模拟列数据
//  {
//     id: 1,
//     title: '姓名',
//     dataIndex: 'name',
//     key: 'name',
//     width: 150,
//     align: 'center',
//     fieldType: 'text',
//     isVisible: true
//   }
let columns = ref([])
let data = ref([])

//表格属性
let tableAttr = ref({
  rowKey: 'table_id',
  //   stripe: true,
  //   'table-layout-fixed': true,
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  loading: false,

  pagination: {
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: true,
    showPageSize: true
    // pageSizeOptions: [5, 10, 20]
    // showJumper: true
  },
  pagePosition: 'bottom'
})

//页码变更

let handlePageChange = (page) => {
  tableAttr.value.pagination.current = page
  getComponentData(page)
}

//根据组件id查询是否有关联数据

let checkComponentRelationData = async () => {
  if (!props.componentId) {
    Message.error('请传入componentId')
    return
  }
  try {
    let res = await request('checkComponentRelation', { component_id: props.componentId })

    if (Array.isArray(res.data) && res.data.length === 0) {
      //组件未关联数据
      relationSqlModalVisible.value = true
    } else {
      //根据组件id查询数据
      getComponentData()
    }
  } catch (e) {
    console.log(e)
  }
}
checkComponentRelationData()

//数据类型映射字典
let dataTypeMap = new Map([
  ['int', 'number'],
  ['bigint', 'number'],
  ['decimal', 'number'],
  ['timestamp', 'date'],
  ['varchar', 'text'],
  ['char', 'text'],
  ['longtext', 'text'],
  ['json', 'text'],
  ['tinyint', 'number'],
  ['text', 'text'],
  ['date', 'date'],
  ['radios', 'radios'],
  ['number', 'number'],
  ['file', 'file'],
  ['switch', 'switch'],
  ['image', 'image'],
  ['action', 'action'],
  ['tag', 'tag'],
  ['serial', 'serial']
])

//根据组件id查询组件数据
let getComponentData = async (page = 1, pageSize = 23) => {
  tableAttr.value.loading = true
  try {
    let res = await request('getVirtualList', { component_id: props.componentId, page, pageSize })
    //获取静态资源前缀
    let res2 = await request('getResourceDomain')
    //映射数据
    let columnsData = res.data.columns.map((item) => {
      let fieldType = dataTypeMap.get(item.fieldType) ?? 'text'
      let fieldLabel = typeInfoMaps.get(fieldType).fieldLabel
      //console.log(fieldLabel)
      //判断当前选项的value是不是一串url
      if (fieldType === 'text' || fieldType === 'image') {
      } else {
      }

      return {
        ...item,
        fieldType,
        icon: typeInfoMaps.get(fieldType).icon,
        fieldLabel,
        align: 'center',
        title: item.title ? item.title : fieldLabel,
        ellipsis: true,
        options: item.options ? item.options : [],
        staticDomain: res2.data.domain,
        render({ record }) {
          return (
            <a-tooltip content={record[item.dataIndex] + ''} trigger="hover">
              <div>{record[item.dataIndex]}</div>
            </a-tooltip>
          )
        }
      }
    })
    remoteFieldData.value = columnsData
    data.value = res.data.data.data
    // console.log(res)
    tableAttr.value.pagination.total = res.data.data.total
    tableAttr.value.pagination.pageSize = pageSize
    tableAttr.value.loading = false
    // console.log(remoteFieldData.value)
  } catch (e) {
    console.log(e)
    Message.error('获取数据失败,' + e.toString())
  }
}
defineExpose({
  name: 'soulTable'
})
</script>
<style lang="scss" scoped>
.table-tool {
  display: grid;
  //   background-color: red;
  box-shadow: 0 1px 11px rgba(0, 10, 0, 0.12);
  padding: 10px 0;
  padding-left: 10px;
  margin-bottom: 10px;
  border-radius: 6px;
  gap: 5px;
  grid-template-columns: repeat(16, 1fr);
  .setting-item {
    // box-shadow: 0 1px 11px rgba(0, 10, 0, 0.12);
    font-size: 16px;
    cursor: pointer;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    box-sizing: border-box;
    &:hover {
      background-color: #edeeee;
    }
    span {
      margin-left: 5px;
    }
  }
}
</style>
