<template>
  <div
    class="card-container"
    v-if="visible"
    :style="{ left: props.position.left + 'px', top: props.position.top + 'px' }"
  >
    <div class="card-items title">
      <span>字段配置</span>
      <Help></Help>
    </div>
    <vue-draggable
      @end="dragEnd"
      v-model="remoteData"
      item-key="field"
      animation="300"
      handle=".drag-handle"
      class="items-container"
    >
      <template #item="{ element, index }">
        <div class="card-items item" :key="index">
          <Drag class="drag-handle"></Drag>
          <component :is="element.icon"></component>
          <div class="field-name">
            <div>{{ element.title }}</div>
            <a-tooltip v-if="element.column_key == 1" content="锁定字段,不可删除" position="top">
              <Lock></Lock>
            </a-tooltip>
            <div v-else class="place-holder"></div>
          </div>
          <component
            :is="element.isVisible ? PreviewOpen : PreviewClose"
            class="field-show"
            @click="changeFieldVisible(element)"
          ></component>
          <DeleteOne class="field-delete" @click="handleDeleteField(element, index)" />
          <Edit class="field-edit" @click="handleEditField(element)" />
        </div>
      </template>
    </vue-draggable>
    <div class="card-items add">
      <icon-plus />
      新增字段
    </div>

    <float-card2
      :remoteData="remoteData"
      v-model:visible="visible2"
      v-if="visible2"
      :position="floatCard2Position"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      v-model:editField="currentEditField"
      :action="card2Action"
    ></float-card2>
    <floatCard3
      :editField="currentEditField"
      v-model:visible="visible3"
      v-if="visible3"
      :position="floatCard3Position"
      @selected="handleSelectedFieldType"
      :fieldTypes="props.defaultFieldsData"
    ></floatCard3>
  </div>
</template>

<script setup lang="jsx">
import { v4 as uuid } from 'uuid'
import vueDraggable from 'vuedraggable'
import {
  Drag,
  PreviewOpen,
  PreviewClose,
  More,
  Help,
  Edit,
  DeleteOne,
  TextStyleOne,
  Lock
} from '@icon-park/vue-next'
import floatCard2 from './floatCard2.vue'
import floatCard3 from './floatCard3.vue'
import { Message, Modal } from '@arco-design/web-vue'
let props = defineProps({
  position: {
    type: Object,
    default: () => ({
      left: 0,
      top: 0
    })
  },
  defaultFieldsData: {
    type: Array,
    default: () => []
  }
})
let dragEnd = () => {
  console.log(remoteData.value)
}
let remoteData = defineModel('remoteFieldData')
let visible = defineModel('visible')
let visible2 = ref(false)
let visible3 = ref(false)
//卡片2的操作模式 编辑/增加
let card2Action = ref('edit')
let floatCard2Position = ref({
  left: 600
})
let floatCard3Position = ref({})

//卡片1业务
//删除字段
let handleDeleteField = (item, index) => {
  if (item.column_key == 1) {
    Message.error('系统不允许删除主键锁定字段')
  } else {
    Modal.warning({
      title: '删除提示',
      content: () => {
        return (
          <div>
            您是否确定要删除
            <span style={{ color: 'red', fontWeight: 'bolder' }}> {item.title} </span>
            这个字段？
          </div>
        )
      },
      hideCancel: false,
      bodyStyle: { textAlign: 'center', fontSize: '18px' },
      onOk() {
        remoteData.value.splice(index, 1)
      }
    })
  }
}

//卡片2菜单按钮事件
let handleConfirm = (item, options) => {
  visible2.value = false
  //判断是编辑还是增加
  if (card2Action.value == 'edit') {
    console.log(currentEditField)
    cacheFieldData.title = item
    cacheFieldData.fieldType = currentEditField.value.fieldType
    cacheFieldData.fieldLabel = currentEditField.value.fieldLabel
    cacheFieldData.options = currentEditField.value.options
    cacheFieldData.icon = currentEditField.value.icon
  } else if (card2Action.value == 'add') {
    currentEditField.value.title = item
    currentEditField.value.isVisible = true
    currentEditField.value.dataIndex = uuid()
    remoteData.value.push(currentEditField.value)
    // console.log(remoteData.value)
  }
}
let handleCancel = (item) => {
  visible2.value = false
}

//卡片3菜单选中事件

let handleSelectedFieldType = (item) => {
  currentEditField.value.fieldType = item.fieldType
  currentEditField.value.fieldLabel = item.fieldLabel
  currentEditField.value.icon = item.icon
}

//获取位置
let getClickTargetPosition = (target) => {
  //获取dom的rect属性
  let rect = target.getBoundingClientRect()
  //   console.log(rect)
  return {
    top: rect.top,
    left: rect.right
  }
}
//显示/隐藏字段
let changeFieldVisible = (item) => {
  item.isVisible = item.isVisible ? 0 : 1
}
//被选中编辑的字段对象
let currentEditField = ref({})
//编辑字段
//缓存响应式的对象
let cacheFieldData = {}
let handleEditField = (item) => {
  cacheFieldData = item
  currentEditField.value = { ...item }
}

//点击事件代理
let clickListener = function (e) {
  //点击图标dom
  let parentTarget = e.target.closest('.i-icon')
  //顶部工具栏按钮
  let parentTarget3 = e.target.closest('.setting-item')
  //编辑字段按钮dom
  let parentEdit = e.target.closest('.field-edit')
  //卡片菜单1容器
  let card1Container = e.target.closest('.card-container')
  //卡片菜单2容器
  let card2Container = e.target.closest('.card-container2')
  //卡片菜单3容器
  let card3Container = e.target.closest('.card-container3')
  //增加容器
  let addContainer = e.target.closest('.add')
  //点击非目标区域隐藏
  if (!parentTarget && !card1Container && !parentTarget3 && !card2Container) {
    visible.value = false
    visible2.value = false
    visible3.value = false
  }
  //点击编辑图标
  if (parentEdit || card2Container || card3Container || addContainer) {
    //点击了增加按钮
    if (addContainer) {
      floatCard2Position.value = getClickTargetPosition(addContainer)
      //初始化数据
      currentEditField.value = {
        id: uuid(),
        title: '字段名称',
        fieldType: 'text',
        fieldLabel: '文本',
        icon: markRaw(TextStyleOne)
      }
      //变更卡片2的操作
      card2Action.value = 'add'
    }
    if (parentEdit) {
      floatCard2Position.value = getClickTargetPosition(parentEdit.parentNode)
      card2Action.value = 'edit'
    }
    //判断是否点击了卡片2中的确认或者取消按钮
    if (!e.target.closest('.last')) {
      visible2.value = true
    }
  } else {
    visible2.value = false
  }
  //点击卡片菜单1关闭卡片2,只有点击卡片1的"更多"才出发卡片2显示
}
//鼠标悬浮时间代理
let mousemoveListener = useDebounceFn(function (e) {
  //   console.log('悬浮')
  //   console.log(e.target)
  let fieldParent = e.target.closest('.field-item-inner')
  let card3Parent = e.target.closest('.card-container3')
  //点击编辑的字段类型
  if (fieldParent || card3Parent) {
    visible3.value = true
    if (fieldParent) {
      floatCard3Position = getClickTargetPosition(fieldParent)
    }
  } else {
    visible3.value = false
  }
}, 100)

onMounted(() => {
  //事件代理
  document.addEventListener('click', clickListener)
  document.addEventListener('mousemove', mousemoveListener)
  //检查位置是超出屏幕bottom
})
onUnmounted(() => {
  document.removeEventListener('click', clickListener)
})
</script>
<style scoped lang="scss">
.card-container {
  user-select: none;
  position: fixed;
  background-color: #fff;
  z-index: 999;
  //   max-height: 70vh;
  width: 290px;
  box-shadow: 2px 4px 12px 0px rgba(0, 0, 0, 0.1);
  border: 1px solid #dee0e3;
  border-radius: 6px;
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  //   gap: 10px;
  font-size: 16px;
  font-weight: bolder;
  color: #5e5e5e;
  .card-items {
    border-bottom: 1px solid #dededf;
    padding: 15px;
    &:hover {
      background-color: #edeeee;
    }
  }
  & > .card-items:last-child {
    border-bottom: 0;
  }
  .drag-handle {
    cursor: pointer;
  }
  .item {
    display: grid;
    grid-template-columns: 1fr 1fr 6fr 1fr 1fr 1fr;
    gap: 5px;
  }
  .i-icon {
    cursor: pointer;
    display: grid;
    // grid-template-columns: 1fr;
    align-items: center;
  }
  .card-items.title {
    display: grid;
    grid-template-columns: 1fr 2fr;
    align-items: center;
  }
  .field-name {
    display: flex;
    // grid-template-columns: 1fr 1fr;
    align-items: center;
    gap: 10px;
  }
  .items-container {
    max-height: 60vh;
    overflow: auto;
  }
}
</style>
