<template>
    <hc-card>
        <template #header>
            <div class="w-40">
                <el-select v-model="searchForm.category" placeholder="请选择分类" filterable clearable block>
                    <el-option v-for="item in categoryData" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <div class="ml-2 w-32">
                <el-select v-model="searchType" placeholder="选择搜索类型" filterable block>
                    <el-option label="资源编号" value="smsCode" />
                    <el-option label="模版ID" value="templateId" />
                </el-select>
            </div>
            <div class="ml-2 w-60">
                <hc-search-input v-model="searchName" placeholder="请输入关键词" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" @click="addClick">新增</el-button>
            <el-button hc-btn type="danger" @click="delClick">删除</el-button>
        </template>
        <hc-table
            :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
            :is-index="false" :check-style="{ width: 29 }" @selection-change="tableCheckChange"
        >
            <template #category="{ row }">{{ getCategoryName(row) }}</template>
            <template #status="{ row }">{{ row.statusName ?? '否' }}</template>
            <template #action="{ row }">
                <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
                <el-link type="success" @click="debugRowClick(row)">调试</el-link>
                <el-link v-yes-com:[enableRowClick]="row" type="primary">启用</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增/修改 -->
        <hc-dialog v-model="isDialogShow" widths="55rem" is-footer-center :title="dialogTitle" @close="dialogClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="短信分类：" prop="category">
                            <div class="form-item-div">
                                <el-radio-group v-model="formModel.category">
                                    <el-radio v-for="item in categoryData" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
                                </el-radio-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="资源编号：" prop="smsCode">
                            <el-input v-model="formModel.smsCode" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category !== 1" :span="12">
                        <el-form-item label="模版ID：" prop="templateId">
                            <el-input v-model="formModel.templateId" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-else :span="12">
                        <el-form-item label="模版内容：" prop="templateContent">
                            <el-input v-model="formModel.templateId" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category > 1" :span="12">
                        <el-form-item label="短信签名：" prop="signName">
                            <el-input v-model="formModel.signName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category === 1" :span="12">
                        <el-form-item label="apiKey：" prop="apiKey">
                            <el-input v-model="formModel.accessKey" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-else-if="formModel.category === 4" :span="12">
                        <el-form-item label="appId：" prop="appId">
                            <el-input v-model="formModel.accessKey" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-else :span="12">
                        <el-form-item label="accessKey：" prop="accessKey">
                            <el-input v-model="formModel.accessKey" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category === 4" :span="12">
                        <el-form-item label="appKey：" prop="appKey">
                            <el-input v-model="formModel.secretKey" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-else-if="formModel.category !== 1" :span="12">
                        <el-form-item label="secretKey：" prop="secretKey">
                            <el-input v-model="formModel.secretKey" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category === 3" :span="12">
                        <el-form-item label="regionId：">
                            <el-input v-model="formModel.regionId" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="formModel.category === 1" :span="12">
                        <el-form-item label="短信签名：" prop="signName">
                            <el-input v-model="formModel.signName" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注说明：">
                            <el-input v-model="formModel.remark" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="dialogClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
            </template>
        </hc-dialog>

        <!-- 短信发送调试 -->
        <hc-dialog v-model="isDebugShow" widths="400px" is-footer-center title="短信发送调试" @close="debugClose">
            <el-form ref="debugFormRef" :model="debugForm" :rules="debugFormRules" label-position="top" label-width="auto">
                <el-form-item label="资源编号：" prop="code">
                    <el-input v-model="debugForm.code" disabled />
                </el-form-item>
                <el-form-item label="发送手机：" prop="phones">
                    <el-input v-model="debugForm.phones" />
                </el-form-item>
                <el-form-item label="发送参数：" prop="params">
                    <el-input v-model="debugForm.params" placeholder="例: {'code':2333,'title':'通知标题'}" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="debugClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="debugLoading" @click="debugSubmit">提交</el-button>
            </template>
        </hc-dialog>
    </hc-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { getDictionaryData } from '~uti/tools'
import { arrToId, formValidate, getArrValue, isNullES } from 'js-fast-way'
import { HcDelMsg } from 'hc-vue3-ui'
import mainApi from '~api/resource/sms'

//激活
onActivated(() => {
    getDataApi()
})

const getDataApi = async () => {
    await getCategoryData()
    searchClick()
}

//搜索表单
const searchType = ref('smsCode')
const searchName = ref('')
const searchForm = ref({ category: null, current: 1, size: 30, total: 0 })

//获取字典数据
const categoryData = ref([])
const getCategoryData = async () => {
    categoryData.value = await getDictionaryData('sms')
}
const getCategoryName = ({ category }) => {
    if (isNullES(category)) return '-'
    const item = categoryData.value.find((item) => item.value === category)
    if (isNullES(item)) return category
    return item.label ?? category
}

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

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

//表格数据
const tableColumn = ref([
    { key: 'category', name: '分类', width: 80, align: 'center' },
    { key: 'smsCode', name: '资源编号', width: 120 },
    { key: 'templateId', name: '模版ID' },
    { key: 'accessKey', name: 'accessKey' },
    { key: 'secretKey', name: 'secretKey' },
    { key: 'regionId', name: 'regionId' },
    { key: 'signName', name: '短信签名' },
    { key: 'remark', name: '备注' },
    { key: 'status', name: '是否启用', width: 80, align: 'center' },
    { key: 'action', name: '操作', width: 160, align: 'center' },
])

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

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

//新增/修改 弹窗
const isDialogShow = ref(false)
const dialogTitle = ref('')

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    category: {
        required: true,
        trigger: 'blur',
        message: '请选择短信分类',
    },
    smsCode: {
        required: true,
        trigger: 'blur',
        message: '请输入资源编号',
    },
    templateId: {
        required: true,
        trigger: 'blur',
        message: '请输入模版ID',
    },
    templateContent: {
        required: true,
        trigger: 'blur',
        message: '请输入模版内容',
    },
    signName: {
        required: true,
        trigger: 'blur',
        message: '请输入短信签名',
    },
    apiKey: {
        required: true,
        trigger: 'blur',
        message: '请输入apiKey',
    },
    appId: {
        required: true,
        trigger: 'blur',
        message: '请输入appId',
    },
    accessKey: {
        required: true,
        trigger: 'blur',
        message: '请输入accessKey',
    },
    appKey: {
        required: true,
        trigger: 'blur',
        message: '请输入appKey',
    },
    secretKey: {
        required: true,
        trigger: 'blur',
        message: '请输入secretKey',
    },
}

//新增
const addClick = () => {
    dialogTitle.value = '新增短信配置'
    formModel.value = { category: 1, regionId: 'cn-hangzhou' }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//修改
const editRowClick = (row) => {
    formModel.value = {}
    dialogTitle.value = '修改短信配置'
    formModel.value = { ...row }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //发起请求
    const { isRes } = await mainApi.submit(formModel.value)
    submitLoading.value = false
    if (!isRes) return
    dialogClose()
    window?.$message?.success('操作成功')
    getTableData().then()
}

//关闭弹窗
const dialogClose = () => {
    isDialogShow.value = false
    submitLoading.value = false
    formModel.value = {}
}

//短信发送调试
const isDebugShow = ref(false)
const debugFormRef = ref(null)
const debugForm = ref({})
const debugFormRules = {
    code: {
        required: true,
        trigger: 'blur',
        message: '资源编号不能为空',
    },
    phones: {
        required: true,
        trigger: 'blur',
        message: '请输入手机号',
    },
    params: {
        required: true,
        trigger: 'blur',
        message: '请输入发送参数',
    },
}
const debugRowClick = (row) => {
    debugForm.value = {
        code: row.smsCode,
        phones: '',
        params: '',
    }
    isDebugShow.value = true
}

//提交调试
const debugLoading = ref(false)
const debugSubmit = async () => {
    const formRes = await formValidate(debugFormRef.value)
    if (!formRes) return false
    debugLoading.value = true
    //发起请求
    const { isRes, msg } = await mainApi.send(debugForm.value)
    if (!isRes) return
    debugClose()
    window?.$message?.success(msg)
}

const debugClose = () => {
    isDebugShow.value = false
    debugLoading.value = false
    debugForm.value = {}
}


//启用
const enableRowClick = async ({ item }, resolve) => {
    const { isRes } = await mainApi.enable(item.id)
    resolve() //关闭弹窗
    if (!isRes) return
    window.$message.success('启用成功')
    getTableData().then()
}

//删除
const delRowClick = async ({ item }, resolve) => {
    const { isRes } = await mainApi.del(item.id)
    resolve() //关闭弹窗
    if (!isRes) return
    window.$message.success('删除成功')
    getTableData().then()
}

//批量删除
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的数据')
        return false
    }
    //确认删除菜单
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(rows)
        const { isRes } = await mainApi.del(ids)
        resolve() //关闭弹窗
        if (!isRes) return
        window.$message.success('删除成功')
        getTableData().then()
    })
}
</script>
