<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { getEventList, createEvent, updateEvent } from '../api'
import { ElMessage } from 'element-plus'
import type { EventProp, MemberProp, AttributesProp } from '../types'

const route = useRoute()

interface Props {
  info?: MemberProp
  data?: AttributesProp
}
const props = defineProps<Props>()

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

const formRef = $ref<FormInstance>()
const form = $ref(
  props.data || {
    experiment_meta_event_id: ''
  }
)

const rules = ref<FormRules>({
  experiment_meta_event_id: [{ required: true, message: '请选择' }]
})

let eventList = $ref<EventProp[]>()
onMounted(() => {
  getEventList().then(res => {
    eventList = res.data.map(
      (item: any) =>
        item.attributes.map((cItem: any) =>
          props.data ? (cItem.value = JSON.parse(props.data.fields)[cItem.id]) : (cItem.value = '') && cItem
        ) && item
    )
  })
})

// 属性
const eventAttributes = computed(() => {
  return eventList?.find(item => item.id === form.experiment_meta_event_id)?.attributes
})

// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const attributes = eventAttributes.value?.reduce((a: any, b: any) => {
    a[b.id] = b.value
    return a
  }, {})
  const [data] = eventAttributes.value || []
  formEl.validate(valid => {
    if (valid) {
      if (props.data) {
        const params = {
          id: props.data?.id,
          fields: attributes
        }
        updateEvent(params).then(() => {
          emit('update')
          emit('update:modelValue', false)
          ElMessage({ message: '更新成功', type: 'success' })
        })
      } else {
        console.log(data, 'data')
        const params = {
          experiment_member_id: route.query?.user_id as '',
          experiment_meta_event_id: form.experiment_meta_event_id,
          fields: attributes
        }
        createEvent(params).then(() => {
          emit('update')
          emit('update:modelValue', false)
          ElMessage({ message: '创建成功', type: 'success' })
        })
      }
    }
  })
}
</script>

<template>
  <el-dialog
    :title="!props.data ? '新建用户事件属性' : '修改用户事件属性'"
    :close-on-click-modal="false"
    width="500px"
    @closed="$emit('update:modelValue', false)">
    <div class="update-event_info">
      <span>姓名：{{ props.info?.name }}</span>
      <span>来源链接：{{ props.info?.connection_name }}</span>
    </div>
    <el-form
      :disabled="props.data?.isView"
      ref="formRef"
      :model="form"
      :rules="rules"
      label-suffix="："
      label-width="122px">
      <el-form-item label="请选择事件" prop="experiment_meta_event_id">
        <el-select :disabled="!!props.data" v-model="form.experiment_meta_event_id" style="width: 100%">
          <el-option v-for="item in eventList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- 属性字段 -->
      <el-form-item :label="item.name" v-for="item in eventAttributes" :key="item.id">
        <template v-if="item.type === '4' || item.type === '5'">
          <el-date-picker
            v-if="item.format === 'yyyy-mm-dd'"
            v-model="item.value"
            type="date"
            placeholder="请选择"
            style="width: 100%"
            value-format="YYYY-MM-DD" />
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-else
            v-model="item.value"
            type="datetime"
            placeholder="请选择"
            style="width: 100%" />
        </template>
        <el-input v-else v-model="item.value" style="width: 100%" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="$emit('update:modelValue', false)">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<style lang="scss">
.btn-box {
  text-align: center;
  margin-bottom: 20px;
}
.update-event_info {
  padding-left: 25px;
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
</style>
