<template>
  <div class="mx-3 mt-3" style="display: flex; gap: 14px;">
    <el-input v-model="templateList" :prefix-icon="Search" placeholder="快速查询" style="width: 240px" @change=""></el-input>
    <el-select v-model="templateType" placeholder="Select" style="width: 240px">
      <el-option
          v-for="item in TemplateType"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
  </div>
  <el-card class="mx-3 my-3">
    <vxe-grid v-bind="gridOptions" v-on="gridEvents">
      <template #toolbar_buttons>
        <SelectBotton :options="TemplateType" btn-title="新建模板" @click="createTmpl"></SelectBotton>
      </template>
      <template #operate="{ row }">
        <el-button icon="Edit" type="text" @click="editTmpl(row)"></el-button>
        <el-button icon="SetUp" type="text" @click="showDialog" :disabled="true"></el-button>
        <el-button icon="Delete" type="text" @click=""></el-button>
      </template>
    </vxe-grid>
  </el-card>
  <el-drawer v-model="showDrawer" :close-on-click-modal="false" :destroy-on-close="true"
             :title="mode === 'add' ? '新建模板' : '编辑模板'"
             size="70%">
    <div style="padding: 0 15px">
      <component
          :is="dyComponents[formData.rule.type]"
          :data="formData"
          :mode="mode"
          :submitFormData="submitFormData"
          @refresh="refreshTable"></component>
    </div>
  </el-drawer>
  <AdActivityDialog v-model:visible="isDialogVisible" />
</template>

<script lang="ts" setup>
import { onMounted, provide, reactive, ref, Ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { TemplateType } from '../utils/enum';
import { GetList } from '/@/views/efTools/automation/api';
import SelectBotton from '/@/components/select-button/index.vue';
import TimerBidTmpl from '/@/views/components/auto/auto-templates/timer-bid.vue';
import TimerBudgetTmpl from '/@/views/components/auto/auto-templates/timer-budget.vue';
import SwitchCampaignTmpl from '/@/views/components/auto/auto-templates/switch-campaign.vue';
import TargetRuleTmpl from '/@/views/components/auto/auto-templates/target-rule.vue';
import SearchTermTmpl from '/@/views/components/auto/auto-templates/search-term.vue';
import NegKeywordTmpl from '/@/views/components/auto/auto-templates/neg-keyword.vue';
import AdActivityDialog from './components/adActivityDialog.vue';
import { AddObj, UpdateObj } from './api';

const isDialogVisible = ref(false);

const showDialog = () => {
  isDialogVisible.value = true;
};
provide('isDialogVisible',isDialogVisible)
//查询
const templateList = ref('');
const templateType = ref('');

//创建，编辑
const mode = ref('');
const showDrawer = ref(false);

const formData: Ref<AutoTemplate> = ref({
  name: '',
  rule: {
    type: 0,
    campaignType: '',
    campaignAd: [],
    action: {},
    activeModel: '',
    setTime: '',
    weekdays: [],
    conditions: [],
  },
});

const dyComponents = {
  1: TimerBidTmpl,
  2: TimerBudgetTmpl,
  3: SwitchCampaignTmpl,
  4: TargetRuleTmpl,
  5: SearchTermTmpl,
  6: NegKeywordTmpl,
};

const refreshTable = () => {
  showDrawer.value = false;
  getList();
};

const createTmpl = (val: number) => {
  mode.value = 'add';
  delete formData.value.id;
  formData.value.name = '';
  formData.value.rule = {
    type: val,
    campaignType: '',
    campaignAd: [],
    action: {},
    activeModel: '',
    setTime: '',
    weekdays: [],
    conditions: [],
  };
  //console.log(formData.value);
  showDrawer.value = true;
};

const editTmpl = (row: any) => {
  mode.value = 'edit';
  formData.value.id = row.id;
  formData.value.name = row.name;
  formData.value.rule = row.rule;
  showDrawer.value = true;
};

const submitFormData = async () => {
  if (mode.value === 'add') {
    await AddObj(formData.value);
  } else if (mode.value === 'edit') {
    await UpdateObj(formData.value);
  }
  refreshTable();
};

//表格配置
const gridOptions = reactive({
  border: 'inner',
  height: 900,
  align: null,
  loading: false,
  rowConfig: {
    isHover: true,
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  columns: [
    {field: 'id', title: 'ID'},
    {field: 'name', title: '模板名称'},
    {field: 'rule.type', title: '模板类型', formatter: ({cellValue}) => getTemplateTypeLabel(cellValue)},
    {field: 'campaignNumber', title: '广告活动数量'},
    {field: 'creator_username', title: '创建人'},
    {field: 'modifier_username', title: '修改人'},
    {title: '操作', width: 120, slots: {default: 'operate'}},
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  data: [],
});

const gridEvents = {
  pageChange({currentPage, pageSize}) {
    if (gridOptions.pagerConfig) {
      gridOptions.pagerConfig.currentPage = currentPage;
      gridOptions.pagerConfig.pageSize = pageSize;
      getList();
    }
  },
};

async function getList() {
  try {
    gridOptions.loading = true;
    const response = await GetList({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
    });
    gridOptions.data = response.data.map(item => ({
      ...item,
      rule: {
        ...item.rule,
        typeLabel: getTemplateTypeLabel(item.rule.type),
      },
    }));
    console.log(response.data);
    gridOptions.pagerConfig.total = response.total;
  } catch (error) {
    console.error('Error fetching task data:', error);
  } finally {
    gridOptions.loading = false;
  }
}

function getTemplateTypeLabel(type: number) {
  const template = TemplateType.find(t => t.value === type);
  return template ? template.label : '';
}

onMounted(() => {
  getList();
});
</script>

<style>
.custom-inline {
  display: flex;
  justify-content: space-around;
  margin: 12px 0;
  gap: 4px;
}

.custom-dialog .el-dialog__header {
  height: 60px;
  line-height: 60px;
  padding: 0 24px;
  background-color: #fff;
  border-bottom: 1px solid #e5e6eb;
  border-radius: 10px 10px 0 0;
}
</style>