<script lang="ts" setup>
import { onMounted, provide, reactive, ref, Ref } from 'vue';
import { Search, WarningFilled } from '@element-plus/icons-vue';
import { TemplateType } from '../utils/enum';
import { DelObj, 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';
import AutomatedRuleTips from '/@/views/efTools/automation/components/automatedRuleTips.vue';

//自动化规则提示
const autoInfo = ref(false);
//关联广告活动弹窗
const isDialogVisible = ref(false);
// const templateId = ref('');
// const activeModel = ref('');
const rowData = ref({});
provide('isDialogVisible', isDialogVisible);

//查询
const templateList = ref('');
const templateType = ref('');

//创建，编辑
const CreateTemplateOptions = ref(TemplateType.filter(item => item.value !== ''));
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 gridOptions = reactive({
  //border: 'inner',
  height: 820,
  align: null,
  loading: false,
  rowConfig: {
    isHover: true,
    height: 45
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: {
    enabled: true,
    total: 20,
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30],
  },
  columns: [
    { field: 'id', title: 'ID', width: 140 },
    { field: 'name', title: '模板名称' },
    {
      field: 'rule.type',
      title: '模板类型',
      formatter: ({ cellValue }) => getTemplateTypeLabel(cellValue),
      slots: { default: 'type' }
    },
    { field: 'campaignNumber', title: '广告活动数量' },
    { field: 'creator_username', title: '创建人' },
    //{ field: 'createTime', title: '创建时间' },
    { field: 'modifier_username', title: '更新人' },
    //{ field: 'updateTime', 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();
    }
  },
};

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

const showDialog = (row: any) => {
  // templateId.value = row.id;
  // activeModel.value = row.rule.activeModel;
  rowData.value = row;
  isDialogVisible.value = true;
};

function handleClick() {
  autoInfo.value = true;
}

function 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: [],
  };
  showDrawer.value = true;
}

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

async function deleteTmpl(row: any) {
  await DelObj(row.id);
  await getList();
}

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

function handleTypeChange() {
  localStorage.setItem('templateType', JSON.stringify(templateType.value));
  getList();
}

function handleTemplateListChange() {
  localStorage.setItem('templateList', JSON.stringify(templateList.value));
  getList();
}

async function getList() {
  const savedTemplateType = localStorage.getItem('templateType');
  if (savedTemplateType) {
    templateType.value = JSON.parse(savedTemplateType);
  }
  const savedTemplateList = localStorage.getItem('templateList');
  if (savedTemplateList) {
    templateList.value = JSON.parse(savedTemplateList);
  }
  try {
    gridOptions.loading = true;
    const response = await GetList({
      page: gridOptions.pagerConfig.currentPage,
      limit: gridOptions.pagerConfig.pageSize,
      type: templateType.value,
      name: templateList.value,
    });
    gridOptions.data = response.data.map(item => ({
      ...item,
      rule: {
        ...item.rule,
        typeLabelWithColor: getTemplateTypeLabel(item.rule.type),
      },
    }));
    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);
  if (template) {
    return { label: template.label, type: type };
  }
  return { label: '', type: '' };
}

const cellStyle = () => {
  return {
    fontSize: '13px',
    //fontWeight: '500',
  };
};

const headerCellStyle = () => {
  return {
    fontSize: '14px',
    fontWeight: '500',
    color: '#2d2d2d',
  };
};

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

<template>
  <div class="flex" style="justify-content: space-between">
    <div class="mx-3 mt-3" style="display: flex; gap: 14px;">
      <el-input v-model="templateList"
                :prefix-icon="Search"
                clearable
                placeholder="模板名称"
                style="width: 240px"
                @change="handleTemplateListChange"
      />
      <el-select v-model="templateType" placeholder="所有类型" style="width: 240px" value-key="value"
                 @change="handleTypeChange">
        <el-option
            v-for="item in TemplateType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
    </div>
    <div class="mx-3 mt-3" style="display: flex; gap: 14px;">
      <el-button link style="color: #2b7ed9;font-size: 12px" @click="handleClick">
        <el-icon>
          <question-filled />
        </el-icon>
        如何使用自动化规则？
      </el-button>
    </div>
  </div>
  <el-card class="mx-3 my-3">
    <vxe-grid :cell-style="cellStyle" :header-cell-style="headerCellStyle" show-overflow v-bind="gridOptions"
              v-on="gridEvents">
      <template #toolbar_buttons>
        <SelectBotton :options="CreateTemplateOptions" btn-title="新建模板" @click="createTmpl"></SelectBotton>
      </template>
      <template #operate="{ row }">
        <el-button icon="Edit" style="color: #0b52a7" type="text" @click="editTmpl(row)"></el-button>
        <el-button icon="SetUp" style="color: #0b52a7" type="text" @click="showDialog(row)"></el-button>
        <el-popconfirm
            :icon="WarningFilled"
            icon-color="#ff8d2b"
            title="删除模板后，所有使用该模板的广告活动将暂停相关自动化规则"
            width="300"
            @confirm="deleteTmpl(row)"
        >
          <template #reference>
            <el-button icon="Delete" style="color: #0b52a7" type="text"></el-button>
          </template>
          <template #actions="{ confirm, cancel }">
            <el-button size="small" @click="cancel">No!</el-button>
            <el-button
                size="small"
                type="danger"
                @click="confirm"
            >
              Yes?
            </el-button>
          </template>
        </el-popconfirm>
      </template>
      <template #type="{row}">
        <!--<el-tag :type="getTagType(row.rule.typeLabelWithColor.type)">-->
        {{ row.rule.typeLabelWithColor.label }}
        <!--</el-tag>-->
      </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-if="isDialogVisible" v-model="isDialogVisible" :rowData @confirmSuccess="getList" />
  <AutomatedRuleTips v-model="autoInfo"></AutomatedRuleTips>
</template>

<style>
.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>