<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 @click="router.push({ path: 'add' })" type="primary">新增概况</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="newsTitle">
                                <el-input v-model="queryParams.newsTitle" placeholder="请输入标题" clearable style="width: 180px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="状态" prop="newsStatus">
                                <el-select style="width: 140px" v-model="queryParams.newsStatus" 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="dataList" min-height="0" max-height="100%">
                        <vxe-column title="序号" align="center" type="seq" width="60" />
                        <vxe-column title="标题" align="center" field="newsTitle" :formatter="colNoData" />
                        <vxe-column title="关联品种" align="center" field="relatedVariety" :formatter="colNoData">
                            <template #default="{ row }">
                                <div v-if="row.variety?.length">
                                    <el-tag>已关联品种({{ row.variety?.length }})</el-tag>
                                </div>
                                <div v-else><el-tag>已关联品种(0)</el-tag></div>
                                <el-button type="text" @click="bindVariety(row)">绑定品种</el-button>
                            </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="newsStatus">
                            <template #default="{ row }">
                                <dict-tag :options="news_status" :value="row.newsStatus" />
                            </template>
                        </vxe-column>
                        <vxe-column title="操作" width="250" align="center" fixed="right">
                            <template #default="{ row }">
                                <el-button type="text" size="small" @click="row.newsStatus === '1' ? unpublishNews(row) : publishNews(row)">
                                    {{ row.newsStatus === '1' ? '下架' : '上架' }}
                                </el-button>
                                <el-button type="text" size="small" @click="editNews(row)">编辑</el-button>
                                <el-button type="text" size="small" @click="viewNewsDetail(row)">详情</el-button>
                                <el-button type="text" size="small" @click="deleteNews(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>
    <el-dialog title="添加关联品种" v-model="showVarietyDialog" width="500px">
        <div>
            <el-form :model="form" label-width="80px">
                <el-form-item label="关联品种">
                    <el-select v-model="form.variety" filterable multiple clearable placeholder="请选择...">
                        <el-option v-for="item in varietyOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <div class="dialog-footer" style="text-align: right; margin-top: 20px;">
            <el-button @click="showVarietyDialog = false">取消</el-button>
            <el-button type="primary" @click="edit">确认添加</el-button>
        </div>
    </el-dialog>
</template>

<script setup name="MedicineNews" lang="ts">
import { colNoData } from '@/utils/noData';
import {Edit} from '@element-plus/icons-vue'
import { getMedicineList } from '@/api/dgtmedicine/variety';
import { editNews as editNewsApi,publishNews as publishNewsApi, unpublishNews as unpublishNewsApi, removeNews, fetchNewsList } from '@/api/dgtmedicine/news';
const router = useRouter();
import { debounce } from 'lodash';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { news_status } = toRefs<any>(proxy?.useDict('news_status'));
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const showVarietyDialog = ref(false);
const queryFormRef = ref<ElFormInstance>();
const dataList = ref<any[]>([]);
const initFormData = {
    id: undefined,
    newsType: 0,
    variety: [],
};
const data = reactive<any>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        newsType: '0',
        newsTitle: '',
        newsStatus: ''
    },
    rules: {}
});

const { queryParams, form } = toRefs(data);
/** 查询会员信息列表 */
const getList = async () => {
    loading.value = true;
    const res = await fetchNewsList(queryParams.value);
    dataList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};


/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

/** 编辑新闻 */
const editNews = (row) => {
    router.push({ path: `add`, query: { id: row.id } });
};

/** 删除新闻 */
const deleteNews = async (row) => {
    ElMessageBox.confirm(`确认要删除 "${row.newsTitle}" 新闻吗？`, '删除提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const res = await removeNews([row.id]);
        if (res) {
            ElMessage.success('删除成功');
            getList();
        }
    });
};

/** 查看新闻详情 */
const viewNewsDetail = (row) => {
    router.push({ path: `add`, query: { id: row.id, disable: '1' } });
};
/** 上架新闻 */
const publishNews = async (row) => {
    try {
        const res = await publishNewsApi(row.id); // Replace with your API call
        if (res) {
            ElMessage.success('新闻已上架');
            getList();
        }
    } catch (error) {
        ElMessage.error('上架失败');
    }
};

/** 下架新闻 */
const unpublishNews = async (row) => {
    try {
        const res = await unpublishNewsApi(row.id); // Replace with your API call
        if (res) {
            ElMessage.success('新闻已下架');
            getList();
        }
    } catch (error) {
        ElMessage.error('下架失败');
    }
};

/** 编辑新闻 */
const edit = debounce(async () => {
    const res = await editNewsApi(form.value);
    if (res && res.code === 200) {
        showVarietyDialog.value = false;
        ElMessage.success('编辑成功');
        getList();
    }
}, 500);

const varietyOptions = ref([]);

const fetchVarietyOptions = async () => {
    const res = await getMedicineList({});
    if (res && res.code === 200) {
        varietyOptions.value = res.data.map(item => ({
            label: item.varietyName,
            value: item.id
        }));
    }
};

const bindVariety = async (row) => {
    form.value.id = row.id;
    form.value.variety = row.variety;
    showVarietyDialog.value = true;
};

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