<script lang="ts" setup>
/**
 * @Name: select-tmpl.vue
 * @Description: 自动化-选择模板
 * @Author: Cheney
 */

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'])

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';
      }
    }
);

async function getTmplList() {
  const resp = await api.getTemplateList({
    page: 1,
    pageSize: 999,
    type: props.data.ruleType,
  });
  tmplList.value = resp.data;
}

function 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)
}

function 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();
  }
}

defineExpose({ getTmplList });
</script>

<template>
  <el-card class="mt-3">
    <div class="asj-h3">
      <span class="custom-title-icon"></span>
      选择模板
    </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; width: 220px"-->
        <!--  placeholder="将规则同时保存为模板（可选）" />-->
        <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-select>
      </div>
    </el-radio-group>
  </el-card>
</template>

<style scoped>
.custom-title-icon {
  padding: 0 5px;
}

.custom-title-icon:before {
  content: '';
  width: 4px;
  height: 15px;
  background: #3569d6;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
}
</style>
