<template>
  <div>
    <div class="asj-h3">选择模板</div>
    <el-radio-group v-model="ruleUsage" @change="changeRuleUsage">
      <div style="display: flex; justify-content: flex-start; flex-direction: column">
        <el-radio label="custom">自定义规则</el-radio>
        <el-input
          v-model="data.templateName"
          v-show="ruleUsage === 'custom'"
          style="margin-left: 22px"
          placeholder="将规则同时保存为模板（可选）"></el-input>
        <el-radio label="tmpl">使用已有模板</el-radio>
        <el-select v-show="ruleUsage === 'tmpl'" @change="changeTmpl" v-model="tmplId" style="margin-left: 22px">
          <el-option v-for="info in tmplList" :label="info.name" :value="info.id" :key="info.id"></el-option>
        </el-select>
      </div>
    </el-radio-group>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import * as api from './api'
import XEUtils from 'xe-utils'

interface Props {
  data: AutoCampaignRule
}
const props = defineProps<Props>()
const ruleUsage = ref('custom')
const tmplId = ref(0)
if (props.data.template) {
  tmplId.value = props.data.template.id
}

const tmplList = ref([])
// const emits = defineEmits(['change-tmpl'])

const getTmplList = async () => {
  const resp = await api.getTemplateList({
    page: 1,
    pageSize: 999,
    type: props.data.ruleType,
  })
  tmplList.value = resp.data
}
const changeTmpl = () => {
  const tmpl = XEUtils.find(tmplList.value, (item) => item.id === tmplId.value)
  props.data.rule = XEUtils.clone(tmpl.rule, true)
  props.data.template = tmpl
  // emits('change-tmpl', tmpl)
}
const changeRuleUsage = () => {
  props.data.useTmpl = ruleUsage.value === 'tmpl'
  if (props.data.useTmpl) {
    if (!tmplId.value && tmplList.value.length > 0) {
      tmplId.value = tmplList.value[0].id
    }
    changeTmpl()
  }
}

onMounted(async () => {
  await getTmplList()
})

watch(
  () => props.data.useTmpl,
  () => {
    if (props.data.useTmpl) {
      ruleUsage.value = 'tmpl'
      tmplId.value = props.data.template.id
    } else {
      ruleUsage.value = 'custom'
    }
  }
)

defineExpose({ getTmplList })
</script>

<style scoped></style>
