<template>
    <div class="p-3">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln" v-show="showSearch">
            <div class="pd-16 border-bottom">
                <div class="f-s-20 c-333 f-w-7 mb-10">广告管理</div>
                <div class="d-flex">
                    <div class="mr-40">
                        <el-button type="primary" @click="handleAdd">新增</el-button>
                    </div>
                    <div class="flex1 ov-hd d-flex j-ed">
                        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto">
                            <el-form-item label="标题" prop="title">
                                <el-input v-model="queryParams.title" placeholder="请输入广告标题" clearable style="width: 180px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="发布时间" prop="dateRange">
                                <div class="d-flex" style="width: 180px">
                                    <DateRange v-model="queryParams.dateRange" v-model:start-date="queryParams.startDate" v-model:end-date="queryParams.endDate"></DateRange>
                                </div>
                            </el-form-item>
                            <el-form-item label="状态" prop="newsStatus">
                                <el-select style="width: 140px" v-model="queryParams.status" clearable placeholder="请选择状态">
                                    <el-option v-for="item in news_status" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>

            <div class="d-flex flex1 ov-hd flex-cln pd-16">
                <div class="pd-8"></div>
                <div class="flex1 ov-hd">
                    <vxe-table :loading="loading" border :data="adList" min-height="0" max-height="100%">
                        <vxe-column title="序号" align="center" type="seq" width="60" :formatter="colNoData" />
                        <vxe-column title="广告图片" align="center" field="adImg" :formatter="colNoData">
                            <template #default="{ row }">
                                <image-preview :src="row.adImg" :width="80" :height="70" />
                            </template>
                        </vxe-column>
                        <vxe-column title="广告标题" align="center" field="title" :formatter="colNoData" />
                        <vxe-column title="放置页面" align="center" field="adPage" :formatter="colNoData">
                            <template #default="{ row }">
                                <dict-tag :options="dm_ad_page" :value="row.adPage" />
                            </template>
                        </vxe-column>
                        <vxe-column title="跳转方式" align="center" field="adPosition" :formatter="colNoData">
                            <template #default="{ row }">
                                <dict-tag :options="dm_ad_type" :value="row.adType" />
                            </template>
                        </vxe-column>
                        <vxe-column title="广告样式" align="center" field="style" :formatter="colNoData">
                            <template #default="{ row }">
                                <dict-tag :options="dm_ad_style" :value="row.style" />
                            </template>
                        </vxe-column>
                        <vxe-column title="广告位置" align="center" field="adPosition" :formatter="colNoData">
                            <template #default="{ row }">
                                <dict-tag :options="dm_ad_position" :value="row.adPosition" />
                            </template>
                        </vxe-column>
                        <vxe-column title="生效日期" align="center" field="validFrom" :formatter="colNoData">
                            <template #default="{ row }">
                                <span>{{ parseTime(row.validFrom, '{y}-{m}-{d}') }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column title="失效日期" align="center" field="validUntil">
                            <template #default="{ row }">
                                <span>{{ parseTime(row.validUntil, '{y}-{m}-{d}') }}</span>
                            </template>
                        </vxe-column>
                        <vxe-column title="操作人" align="center" field="createByName" :formatter="colNoData" />
                        <vxe-column title="操作时间" align="center" field="createTime" :formatter="colNoData" />
                        <vxe-column title="状态" align="center" field="status">
                            <template #default="{ row }">
                                <dict-tag :options="news_status" :value="row.status" />
                            </template>
                        </vxe-column>
                        <vxe-column title="操作" width="250" align="center" fixed="right">
                            <template #default="{ row }">
                                <el-button type="text" size="small" @click="row.status === '1' ? unpublishAd(row) : publishAd(row)">
                                    {{ row.status === '1' ? '下架' : '上架' }}
                                </el-button>
                                <el-button type="text" size="small" @click="handleUpdate(row)">编辑</el-button>
                                <el-button type="text" size="small" @click="viewAddDetail(row)">详情</el-button>
                                <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
                <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
            </div>
        </div>
    </div>
</template>

<script setup name="AdManagement" lang="ts">
import { listAd, getAd, delAd, addAd, updateAd, publishAd as publishAdApi,unpublishAd as unpublishAdApi} from '@/api/dgtmedicine/ad';
import { ElMessageBox, ElMessage } from 'element-plus';
import { colNoData } from '@/utils/noData';
import { DateRange } from '@/views/models/index';

const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const router = useRouter();
const queryFormRef = ref<ElFormInstance>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { news_status,dm_ad_type,dm_ad_position,dm_ad_page,dm_ad_style } = toRefs<any>(proxy?.useDict('news_status',
    'dm_ad_type','dm_ad_position','dm_ad_page','dm_ad_style'));
const adList = ref<any[]>([]);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: '',
  adPosition: '',
});

const getList = async () => {
  loading.value = true;
  const res = await listAd(queryParams);
  adList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 广告新增   */
const handleAdd = (row) => {
  router.push({ path: `adAdd`, query: { id: row.id ,title:'新增广告'} });
};

/** 广告详情 */
const viewAddDetail = (row) => {
    router.push({ path: `adAdd`, query: { id: row.id, disable: '1' ,title:'广告详情'} });
};

/** 上架广告 */
const publishAd = async (row) => {
  loading.value = true;
    try {
        const res = await publishAdApi(row.id); // Replace with your API call
        if (res) {
            ElMessage.success('新闻已上架');
            getList();
        }
    } catch (error) {
        ElMessage.error('上架失败');
    }
    loading.value = false;
};

/** 下架广告 */
const unpublishAd = async (row) => {
  loading.value = true;
    try {
        const res = await unpublishAdApi(row.id); // Replace with your API call
        if (res) {
            ElMessage.success('新闻已下架');
            getList();
        }
    } catch (error) {
        ElMessage.error('下架失败');
    }
    loading.value = false;
};

const handleUpdate = async (row) => {
  router.push({ path: `adAdd`, query: { id: row.id ,title:'编辑广告'} });

};

const handleDelete = async (row) => {
  ElMessageBox.confirm(`确认要删除广告 "${row.title}" 吗？`, '删除提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await delAd(row.id);
    ElMessage.success('删除成功');
    getList();
  });
};

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