<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { submitScheduleEvent, getScheduleEvent } from '../api'
import type { ScheduleEvent } from '../types'
import type { FormInstance } from 'element-plus'

import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const OtherFields = defineAsyncComponent(() => import('../components/OtherFields.vue'))

const props = defineProps<{ data?: ScheduleEvent }>()

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

// const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = $ref<any>({
  experiment_id: props.data?.experiment_id,
  connect_id: props.data?.connect_id,
  event_id: '',
  member_rate: '',
  size: '',
  cover_type: 1,
  created_field: ''
})

let fieldsValue = $ref<any[]>([])
const submitForm = async (formEl: FormInstance | undefined, bl: string) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.create_data = bl
      ruleForm.other_fields = JSON.stringify(
        fieldsValue.reduce((a: any, b: any) => {
          a[b.id] = {
            type: b.rule?.type,
            fixed_value: b.rule?.fixed_value,
            rand_value: b.rule?.rand_value
          }
          return a
        }, {})
      )
      submitScheduleEvent(ruleForm).then((res: any) => {
        if (res.code === 0) {
          ElMessage({
            message: '保存成功',
            type: 'success'
          })
          emit('update:modelValue', false)
        } else {
          ElMessage({
            message: res.message
          })
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const rules = [{ required: true }]

onMounted(() => {
  if (props.data?.last_event !== '') {
    eventChange(props.data?.last_event)
  }
})

// 用户事件改变的时候
const eventChange = function (eId?: string) {
  getScheduleEvent({
    experiment_id: ruleForm.experiment_id,
    connect_id: ruleForm.connect_id,
    event_id: eId || ruleForm.event_id
  }).then(res => {
    if (res.data) {
      mergeJson(ruleForm, res.data)
      fieldsValue = res.data.other_fields.map((item: any) => {
        if (item?.rule) {
          item.rule.type = parseInt(item.rule.type)
        }
        return item
      })
    }
  })
}
const mergeJson = function (target: any, source: any) {
  if (source) {
    Object.keys(target).forEach(function (key) {
      if (source.hasOwnProperty(key)) {
        target[key] = source[key]
      }
    })
  }
}

const option = computed(() => {
  return fieldsValue.reduce((a: any, b: any) => {
    if (parseInt(b.type) === 5) {
      a.push(b)
    }
    return a
  }, [])
})
</script>

<template>
  <el-dialog
    style="width: 800px"
    class="data-form"
    title="自动生成用户事件数据"
    :close-on-click-modal="false"
    @closed="$emit('update:modelValue', false)">
    <div class="button-flex">
      <el-form
        :disabled="userStore.role?.id === 1"
        label-suffix="："
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
        status-icon>
        <el-form :model="ruleForm" label-suffix="：">
          <el-form-item label="用户事件" :rules="rules" label-width="205">
            <el-select @change="eventChange" v-model="ruleForm.event_id" placeholder="请选择">
              <el-option v-for="item in props.data?.events" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-form-item label="请输入随机调取用户比例" :rules="rules">
          <el-input v-model="ruleForm.member_rate" placeholder="请输入">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="请输入每个用户生成事件数" :rules="rules">
          <el-input v-model="ruleForm.size" placeholder="请输入"> </el-input>
        </el-form-item>
        <el-form-item label="请选择数据覆盖形式" :rules="rules">
          <el-radio-group v-model="ruleForm.cover_type">
            <el-radio :value="1">全新覆盖</el-radio>
            <el-radio :value="2">追加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="事件发生时间" :rules="rules">
          <el-select v-model="ruleForm.created_field" placeholder="请选择">
            <el-option v-for="item in option" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-divider />
        <OtherFields :data="fieldsValue || []"></OtherFields>
        <el-form :model="ruleForm">
          <el-form-item style="justify-content: center">
            <div style="justify-content: center; display: flex; width: 100%">
              <el-button @click="$emit('update:modelValue', false)">取消</el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef, 'false')"> 保存 </el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef, 'true')"> 提交生成数据 </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-form>
    </div>
  </el-dialog>
</template>
<style lang="scss">
.connect-form {
  .el-dialog__body {
    padding-top: 10px;
  }
}
.button-flex {
  // margin-top: 40px;
  display: flex;
  justify-content: center;
}
</style>
