<template>
    <hc-card>
        <template #header>
            <div class="mr-10px w-140px">
                <el-select v-model="searchForm.msgType" class="block" clearable filterable placeholder="请选择公告类型">
                    <el-option label="更新公告" value="1" />
                    <el-option label="普通公告" value="2" />
                </el-select>
            </div>
            <div class="mr-10px w-140px">
                <el-select v-model="searchForm.pushStatus" class="block" clearable filterable placeholder="发布状态">
                    <el-option label="待发布" value="1" />
                    <el-option label="已发布" value="2" />
                    <el-option label="已取消" value="3" />
                </el-select>
            </div>
            <el-button type="primary" @click="searchClick">搜索</el-button>
        </template>
        <template #extra>
            <el-badge :value="releasedNum" style="margin-right: 18px;">
                <el-button @click="releasedShow">待发布</el-button>
            </el-badge>
            <el-button type="primary" @click="generalShow">发布普通公告</el-button>
            <el-button type="warning" @click="systemUpdateShow">发布系统公告</el-button>
            <el-button type="danger" @click="handleDelete">批量删除公告</el-button>
        </template>
        <hc-table
            ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
            is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }" @selection-change="tableCheckChange"
        >
            <template #msgType="{ row }">
                <span v-if="row.msgType === 1">更新公告</span>
                <span v-if="row.msgType === 2">普通公告</span>
            </template>
            <template #pushDateTime="{ row }">
                <template v-if="row.msgType === 1">
                    <span>剩余</span>
                    <el-tag type="danger" size="small">{{ row.msgWarnTime }}分钟</el-tag>
                    <span>进行提醒，</span>
                    <el-tag type="danger" size="small">{{ row.msgCountDownTime }}分钟</el-tag>
                    <span>开始进入倒计时</span>
                </template>
                <template v-else>
                    <span>-</span>
                </template>
            </template>
            <template #pushStatus="{ row }">
                <el-tag v-if="row.pushStatus === 3" type="danger" effect="dark" size="small">已取消</el-tag>
                <el-tag v-if="row.pushStatus === 2" type="success" effect="dark" size="small">已发布</el-tag>
                <el-tag v-if="row.pushStatus === 1" type="info" effect="dark" size="small">待发布</el-tag>
            </template>
            <template #action="{ row }">
                <el-link type="warning" :disabled="row.pushStatus !== 3" @click="handleEdit(row)">修改</el-link>
                <el-link type="danger" :disabled="row.pushStatus !== 1" @click="handleCancel(row)">取消发布</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 待发布 -->
        <hc-dialog v-model="isReleasedShow" title="待发布的公告" ui="hc-system-announcement-dialog black-card" widths="660px" :footer="false" @close="releasedCancel">
            <el-divider v-if="releasedData.updateMsg.length > 0" content-position="left" class="hc-system-announcement-black-divider top">更新公告</el-divider>
            <div v-for="(item, index) in releasedData.updateMsg" :key="index" class="hc-system-announcement-black-card">
                <div class="icon-box">
                    <div class="name">{{ index === 0 ? '前 端' : '后 端' }}</div>
                    <div class="icon">
                        <i class="iconfont iconicon_notice" />
                    </div>
                </div>
                <div class="content">
                    <div class="top-box">
                        <div class="left">
                            <span class="name">待发布：</span>
                            <span class="num">{{ item.awaitMsgTotal }}</span>
                        </div>
                        <div class="right">
                            <span class="name">创建人：</span>
                            <span class="user">{{ item.creatUserName }}</span>
                        </div>
                    </div>
                    <div class="time-box">
                        <span class="name">发布时间：</span>
                        <span class="time">{{ item.pushDateTime }}</span>
                    </div>
                </div>
            </div>
            <el-divider v-if="releasedData.systemMsg.length > 0" content-position="left" class="hc-system-announcement-black-divider">普通公告</el-divider>
            <div v-for="(item, index) in releasedData.systemMsg" :key="index" class="hc-system-announcement-black-card">
                <div class="icon-box">
                    <div class="name">公 告</div>
                    <div class="icon">
                        <i class="iconfont iconicon_notice" />
                    </div>
                </div>
                <div class="content">
                    <div class="top-box">
                        <div class="left">
                            <span class="name">待发布：</span>
                            <span class="num">{{ item.awaitMsgTotal }}</span>
                        </div>
                        <div class="right">
                            <span class="name">创建人：</span>
                            <span class="user">{{ item.creatUserName }}</span>
                        </div>
                    </div>
                    <div class="time-box">
                        <span class="name">发布时间：</span>
                        <span class="time">{{ item.pushDateTime }}</span>
                    </div>
                </div>
            </div>
        </hc-dialog>


        <!-- 发布普通公告 -->
        <hc-dialog v-model="isGeneralShow" widths="700px" ui="hc-system-announcement-dialog" is-footer-center title="发布普通公告" @close="generalCancel">
            <el-form ref="generalFormRef" :model="generalFormModel" :rules="generalFormRules" class="hc-system-announcement-form" label-width="auto">
                <el-form-item label="公告内容：" prop="msgContent">
                    <el-input v-model="generalFormModel.msgContent" type="textarea" :rows="5" />
                </el-form-item>
                <el-form-item label="发布备注：" prop="pushRemark">
                    <el-input v-model="generalFormModel.pushRemark" type="textarea" />
                </el-form-item>
                <el-form-item label="发布配置：" prop="pushDateTime">
                    <el-date-picker v-model="generalFormModel.pushDateTime" type="datetime" placeholder="选择日期时间" :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
                <el-form-item label="停留时间：" prop="msgShowTime">
                    <el-select v-model="generalFormModel.msgShowTime" clearable filterable style="width: 190px;">
                        <el-option v-for="i in 60" :key="i" :label="`${i}分钟`" :value="i" />
                    </el-select>
                </el-form-item>
                <el-form-item label="涉及系统：" prop="pushSystem">
                    <el-checkbox-group v-model="generalFormModel.pushSystem">
                        <el-checkbox v-for="item in systemClinet" :key="item.clientId" :value="item.clientId">{{ item.name || item.clientId }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="generalCancel">取消</el-button>
                <el-button hc-btn type="primary" @click="generalFormSubmit">提交</el-button>
            </template>
        </hc-dialog>

        <!-- 发布系统公告 -->
        <hc-dialog v-model="isSystemUpdateShow" widths="700px" ui="hc-system-announcement-dialog" is-footer-center title="发布系统公告" @close="systemUpdateCancel">
            <el-form ref="updateFormRef" :model="updateFormModel" :rules="updateFormRules" class="hc-system-announcement-form" label-width="auto">
                <el-form-item label="公告内容：" prop="msgContent">
                    <el-input v-model="updateFormModel.msgContent" type="textarea" :rows="5" />
                </el-form-item>
                <el-form-item label="发布备注：" prop="pushRemark">
                    <el-input v-model="updateFormModel.pushRemark" type="textarea" />
                </el-form-item>
                <el-form-item label="更新类型：" prop="updateServerType">
                    <el-checkbox-group v-model="updateFormModel.updateServerType">
                        <el-checkbox value="1">前端页面</el-checkbox>
                        <el-checkbox value="2">后端接口</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="更新原因：" prop="updateCodeType">
                    <el-radio-group v-model="updateFormModel.updateCodeType">
                        <el-radio value="1">新功能需求</el-radio>
                        <el-radio value="2">bug修复</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="发布配置：" prop="pushDateTime">
                    <el-date-picker v-model="updateFormModel.pushDateTime" type="datetime" placeholder="选择日期时间" :picker-options="pickerOptions" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
                <el-form-item label="时间配置：" prop="msgWarnTime">
                    <span>剩余</span>
                    <span style="margin-left: 5px">
                        <el-select v-model="updateFormModel.msgWarnTime" clearable filterable size="small" style="width: 90px;" placeholder="分钟">
                            <el-option v-for="i in 60" :key="i" :label="`${i}分钟`" :value="i" />
                        </el-select>
                    </span>
                    <span style="margin-left: 5px">进行提醒，</span>
                    <span style="margin-left: 5px">
                        <el-select v-model="updateFormModel.msgCountDownTime" clearable filterable size="small" style="width: 90px;" placeholder="时间">
                            <el-option v-for="i in 60" :key="i" :label="`${i}分钟`" :value="i" />
                        </el-select>
                    </span>
                    <span style="margin-left: 5px">开始进入倒计时</span>
                </el-form-item>
                <el-form-item label="涉及系统：" prop="pushSystem">
                    <el-checkbox-group v-model="updateFormModel.pushSystem">
                        <el-checkbox v-for="item in systemClinet" :key="item.clientId" :value="item.clientId">{{ item.name || item.clientId }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="systemUpdateCancel">取消</el-button>
                <el-button hc-btn type="primary" @click="updateFormSubmit">发布</el-button>
            </template>
        </hc-dialog>
    </hc-card>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { arrToId, deepClone, formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { reloadPage } from '~uti/tools'
import { HcDelMsg } from 'hc-vue3-ui'
import mainApi from '~api/system/notice'

//激活
onActivated(() => {
    searchForm.value.current = 1
    getTableData()
    getAwaitMsgApi()
})

//获取待发布的数据
const releasedNum = ref(0)
const releasedData = ref({
    systemMsg: [],
    updateMsg: [],
})
const getAwaitMsgApi = async () => {
    const { data } = await mainApi.getAwaitMsg()
    const { msgTotal, systemMsg, updateMsg } = getObjValue(data)
    releasedData.value = {
        systemMsg: systemMsg,
        updateMsg: updateMsg,
    }
    releasedNum.value = msgTotal
}

//搜索表单
const searchForm = ref({
    msgType: null, pushStatus: null,
    current: 1, size: 30, total: 0,
})

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'msgType', name: '公告类型', width: 100 },
    { key: 'pushSystem', name: '推送系统', minWidth: 220 },
    { key: 'msgContent', name: '公告内容', minWidth: 240 },
    { key: 'pushRemark', name: '发布备注' },
    { key: 'pushDateTime', name: '发布时间', width: 240, align: 'center' },
    { key: 'pushDateTime', name: '时间配置', width: 340, align: 'center' },
    { key: 'creatUserName', name: '创建人', width: 100, align: 'center' },
    { key: 'cancelDateTime', name: '取消时间', width: 160, align: 'center' },
    { key: 'pushStatus', name: '发布状态', width: 80, align: 'center' },
    { key: 'action', name: '操作', width: 120, align: 'center', fixed: 'right' },
])

//获取表格数据
const tableLoading = ref(true)
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.getList(searchForm.value)
    tableLoading.value = false
    tableData.value = getArrValue(data?.records)
    searchForm.value.total = data?.total || 0
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows
}

//修改
const handleEdit = (row) => {
    const form = deepClone(row)
    if (form.msgType === 1) {
        form.updateServerType = form.updateServerType.split(',')
        form.pushSystem = form.pushSystem.split(',')
        updateFormModel.value = form
        systemUpdateShow()
    } else {
        form.pushSystem = form.pushSystem.split(',')
        generalFormModel.value = form
        generalShow()
    }
}

//取消发布
const handleCancel = async (row) => {
    const { isRes } = await mainApi.remove(row.id)
    if (!isRes) return
    getTableData().then()
}

//待发布
const isReleasedShow = ref(false)
const releasedShow = () => {
    isReleasedShow.value = true
}
const releasedCancel = () => {
    isReleasedShow.value = false
}

const isGeneralShow = ref(false)
const generalFormRef = ref(null)
const generalFormModel = ref({})
const generalFormRules = {
    msgContent: { required: true, trigger: 'blur', message: '请填写公告内容' },
    pushDateTime: { required: true, trigger: 'blur', message: '请选择发布配置' },
    msgShowTime: { required: true, trigger: 'blur', message: '请选择停留时间' },
    pushSystem: { required: true, trigger: 'blur', message: '请选择涉及系统' },
}

//获取应用列表
const systemClinet = ref([])
const getClinetAllApi = async () => {
    const { data } = await mainApi.getClinetAll()
    systemClinet.value = getArrValue(data)
}

//发布普通公告
const generalShow = () => {
    isGeneralShow.value = true
    getClinetAllApi()
}

const generalFormSubmit = async () => {
    const formRes = await formValidate(generalFormRef.value)
    if (!formRes) return false
    let form = deepClone(generalFormModel.value)
    form.pushSystem = form.pushSystem.join(',')
    form.msgType = 2
    if (form.id) {
        const { isRes, msg } = await mainApi.update(form)
        if (!isRes) return
        this.$message.success(msg || '操作成功')
        reloadPage()
    } else {
        const { isRes, msg } = await mainApi.add(form)
        if (!isRes) return
        this.$message.success(msg || '操作成功')
        reloadPage()
    }
}

const generalCancel = () => {
    isGeneralShow.value = false
    generalFormModel.value = {}
}

const isSystemUpdateShow = ref(false)
const updateFormRef = ref(null)
const updateFormModel = ref({})
const updateFormRules = {
    msgContent: { required: true, trigger: 'blur', message: '请填写公告内容' },
    updateServerType: { required: true, trigger: 'blur', message: '请选择更新类型' },
    updateCodeType: { required: true, trigger: 'blur', message: '请选择更新原因' },
    pushDateTime: {
        required: true,
        validator: (rule, value, callback) => {
            const { msgWarnTime } = updateFormModel.value
            if (!value) {
                callback(new Error('请选择发布配置'))
            } else if (!msgWarnTime) {
                callback(new Error('请选择时间配置'))
            } else {
                callback()
            }
        },
    },
    msgWarnTime: { required: true, trigger: 'blur', message: '请选择时间配置' },
    pushSystem: { required: true, trigger: 'blur', message: '请选择涉及系统' },
}


//发布系统公告
const systemUpdateShow = () => {
    isSystemUpdateShow.value = true
    getClinetAllApi()
}

const updateFormSubmit = async () => {
    const formRes = await formValidate(updateFormModel.value)
    if (!formRes) return false
    let form = deepClone(updateFormModel.value)
    form.pushSystem = form.pushSystem.join(',')
    form.updateServerType = form.updateServerType.join(',')
    form.msgType = 1
    if (form.id) {
        const { isRes, msg } = await mainApi.update(form)
        if (!isRes) return
        this.$message.success(msg || '操作成功')
        reloadPage()
    } else {
        const { isRes, msg } = await mainApi.add(form)
        if (!isRes) return
        this.$message.success(msg || '操作成功')
        reloadPage()
    }
}

const systemUpdateCancel = () => {
    isSystemUpdateShow.value = false
    updateFormModel.value = {}
}

//日期时间
const pickerOptions = {
    shortcuts: [{
        text: '三分钟',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3 * 60 * 1000)
            picker.$emit('pick', date)
        },
    }, {
        text: '五分钟',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 5 * 60 * 1000)
            picker.$emit('pick', date)
        },
    }, {
        text: '十分钟',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 10 * 60 * 1000)
            picker.$emit('pick', date)
        },
    }, {
        text: '三十分钟',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 30 * 60 * 1000)
            picker.$emit('pick', date)
        },
    }],
}

//批量删除公告
const handleDelete = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选数据')
        return false
    }
    //判断是否满足条件
    const result = rows.every(({ pushStatus }) => {
        return pushStatus === 3
    })
    if (!result) {
        window.$message.warning('请选择已取消的数据')
        return
    }
    //确认删除
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(rows)
        const { isRes } = await mainApi.remove(ids)
        resolve() //关闭弹窗的回调
        if (!isRes) return
        window.$message.success('删除成功')
        reloadPage()
    })
}
</script>

<style lang="scss">
@import "~src/styles/view/notice";
</style>
