<script setup lang="ts">
import type { EventProp, EventDetailProp, EventAttributesProp } from '../types'
import { ElMessage } from 'element-plus'
import { useMapStore } from '@/stores/map'
import { Close, QuestionFilled } from '@element-plus/icons-vue'
import { getMetaEventDetail, updateAttributes, getIsDeleteAttribute } from '../api'

const store = useMapStore()

interface Props {
  data?: EventProp
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

// 属性字段类型
const experimentAttributeOptions = $ref(store.getMapValuesByKey('experiment_attribute_type'))

// 添加字段
const addField = function () {
  tableData.push({ id: '', name: '', english_name: '', type: '', format: '' })
}

// 删除字段
const deleteField = function (scope: { $index: number; row: EventAttributesProp }) {
  if (scope.row.isDefault) return
  if (tableData[scope.$index]?.id === '') {
    tableData.splice(scope.$index, 1)
  } else {
    // 判断当前属性是否可以删除
    getIsDeleteAttribute({ id: scope.row.id }).then((res) => {
      res.data?.can_delete ? tableData.splice(scope.$index, 1) : ElMessage({ message: '不能删除', type: 'warning' })
    })
  }
}

// 事件详情
let eventDetail = $ref<EventDetailProp>()

onBeforeMount(() => {
  getMetaEventDetail({ id: props.data?.id || '' }).then((res) => {
    eventDetail = res.data
    tableData = defaultFields.concat(res.data.attributes)
  })
})

// 默认字段
const defaultFields = [
  { id: '1', name: '事件ID', english_name: 'action_id', type: '1', format: '25', isDefault: true },
  { id: '2', name: '事件发生时间', english_name: 'action_time', type: '5', format: 'yyyy-mm-dd hh:mm:ss', isDefault: true },
  { id: '3', name: '用户ID', english_name: 'user_id', type: '1', format: '25', isDefault: true }
]

// 字段
let tableData = $ref<EventAttributesProp[]>([])

// 提交
function handleSubmit() {
  handleUpdate()
}

function handleUpdate() {
  const params = {
    id: eventDetail?.id || '',
    attributes: JSON.stringify(tableData.filter((item) => !item.isDefault))
  }
  updateAttributes(params).then(() => {
    ElMessage({ message: '保存成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}

const changeFormatType = function (row: any) {
  switch (row.type) {
    case '1':
      row.format = '25'
      break
    case '2':
      row.format = '4'
      break
    case '3':
      row.format = '20'
      break
    case '4':
      row.format = 'yyyy-mm-dd'
      break
    case '5':
      row.format = 'yyyy-mm-dd hh:mm:ss'
      break
  }
}

const popoverText = function (row: any) {
  let t = ''
  if (row.type === '1') {
    t = '你可以在这个字段中输入最多25个字符'
  }
  if (row.type === '2') {
    t = '该字段可以存储最多四位数的整数'
  }
  if (row.type === '3') {
    t = '数字的总长度为20位，包括整数部分和小数部分'
  }
  if (row.type === '4') {
    t =
      'yyyy: 表示四位数的年份，例如2023年会被表示为“2023”。<br/>mm: 表示两位数的月份，从01到12，例如3月表示为“03”。<br/>dd: 表示两位数的日期，从01到31，具体取决于月份和是否为闰年。<br/>例如“2023-04-01”代表的是2023年4月1日'
  }
  if (row.type === '5') {
    t =
      'yyyy: 表示四位数的年份，例如2023。<br/>mm: 表示两位数的月份，从01到12表示1月到12月。<br/>dd: 表示两位数的日期，从01到31，依据具体月份和是否为闰年。<br/>hh: 表示两位数的小时，使用24小时制，从00到23表示。<br/>mm: 表示两位数的分钟，从00到59。<br/>ss: 表示两位数的秒，从00到59。<br/>例如"2023-04-01 15:30:45"表示的是2023年4月1日下午3点30分45秒'
  }
  return t
}
</script>

<template>
  <el-dialog title="事件属性" :close-on-click-modal="false" width="800px" @update:modelValue="(value) => $emit('update:modelValue', value)">
    <div style="display: flex; justify-content: space-around">
      <el-form label-width="120px">
        <el-form-item label="事件英文名称:">{{ eventDetail?.english_name }}</el-form-item>
        <el-form-item label="事件名称:">{{ eventDetail?.name }}</el-form-item>
      </el-form>
      <el-form label-width="120px">
        <el-form-item label="所属链接:">{{ eventDetail?.connection_name }}</el-form-item>
        <el-form-item label="状态:">{{ eventDetail?.status_name }}</el-form-item>
      </el-form>
    </div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>事件属性字段</span>
          <el-button type="primary" @click="addField" :disabled="props.data?.can_edit === '0'">添加</el-button>
        </div>
      </template>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="属性英文名">
          <template #default="{ row }">
            <el-input v-model="row.english_name" placeholder="请输入" :disabled="row.isDefault"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="属性名称">
          <template #default="{ row }">
            <el-input v-model="row.name" placeholder="请输入" :disabled="row.isDefault"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="字段类型">
          <template #default="{ row }">
            <el-select @change="changeFormatType(row)" :disabled="row.id !== ''" v-model="row.type" placeholder="请选择">
              <el-option :label="item.label" :value="item.value" :key="item.id" v-for="item in experimentAttributeOptions"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段格式">
          <template #default="{ row }">
            <el-select :disabled="row.id !== ''" v-if="row.type === '4' || row.type === '5'" v-model="row.format" placeholder="请选择">
              <el-option v-if="row.type !== '5'" label="yyyy-mm-dd" value="yyyy-mm-dd"></el-option>
              <el-option v-if="row.type !== '4'" label="yyyy-mm-dd hh:mm:ss" value="yyyy-mm-dd hh:mm:ss"></el-option>
            </el-select>
            <el-input
              v-else
              :disabled="row.id !== ''"
              type="number"
              v-model="row.format"
              :placeholder="row.type === '1' ? '请输入字符串长度' : '请输入长度'"></el-input>
          </template>
        </el-table-column>
        <el-table-column width="30">
          <template #default="{ row }">
            <el-popover placement="top-start" :width="300" trigger="hover" :title="row.type_name">
              <template #reference>
                <div style="display: flex; justify-content: center; cursor: pointer">
                  <el-icon size="20"><QuestionFilled /></el-icon>
                </div>
              </template>
              <div v-html="popoverText(row)"></div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="30" v-if="props.data?.can_edit !== '0'">
          <template #default="scope">
            <div @click="deleteField(scope)" style="display: flex; justify-content: center; cursor: pointer" v-if="!scope.row.isDefault">
              <el-icon size="20"><Close /></el-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit" v-if="props.data?.can_edit !== '0'">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
