<!-- 通知公告-公告通知管理-编辑 -->
<template>
    <app-drawer :title="t('investor.user.open.edit.title')" width="900" v-model:show="show" :refresh="refresh"
        :loading="loading">
        <el-form ref="formRef" class="el-form--vertical" label-width="100px" :model="formData" :rules="formRules"
            :show-message="false">
            <el-form-item label="标题" prop="title">
                <el-input v-model="formData.title" :placeholder="t('common.pleaseenter')" />
            </el-form-item>
            <el-form-item label="消息类型" prop="msgtype">
                <el-select v-model="formData.msgtype" :disabled="!!formData.autoid">
                    <el-option v-for="item in msgtypeEnum.getEnumOptions()" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="发布类型" prop="sendtype">
                <el-select v-model="formData.sendtype" :disabled="!!formData.autoid">
                    <el-option v-for="item in sendtypeEnum.getEnumOptions()" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <template v-if="formData.autoid">
                <el-form-item label="接收会员" v-if="formData.sendtype === 2 || formData.sendtype === 4">
                    <el-input :value="data?.membername" disabled />
                </el-form-item>
                <el-form-item label="接收交易商" v-if="formData.sendtype === 3">
                    <el-input :value="data?.membername" disabled />
                </el-form-item>
            </template>
            <template v-else>
                <el-form-item label="接收会员" prop="memberidlist"
                    v-if="formData.sendtype === 2 || formData.sendtype === 4">
                    <el-input :value="selectedValues.map((e) => e.accountname)" placeholder="请选择" readonly>
                        <template #append>
                            <el-button @click="showSelectMember = true">选择</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="接收交易商" prop="invertorID" v-if="formData.sendtype === 3">
                    <app-select-investor v-model="formData.invertorID" />
                </el-form-item>
            </template>
            <el-form-item label="开始结束" prop="date">
                <el-date-picker v-model="dateValue" type="datetimerange"
                    :disabled-date="(date: Date) => date.getTime() < Date.now() - 8.64e7" start-placeholder="生效时间"
                    end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <app-editor v-model="formData.content" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="onCancel(false)">{{ t('operation.close') }}</el-button>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </template>
        <select-member v-model:show="showSelectMember" @change="onMemberChange" />
    </app-drawer>
</template>

<script lang="ts" setup>
import { ref, PropType, onMounted } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { formatDate } from '@/filters'
import { useRequest } from '@/hooks/request'
import { useEnum } from '@/hooks/enum'
import { noticemsgadd, noticemsgedit, noticeMsgDetail } from '@/services/api/notice'
import { i18n } from '@/stores'
import AppDrawer from '@pc/components/base/drawer/index.vue'
import AppSelectInvestor from '@pc/components/modules/select-investor/index.vue'
import AppEditor from '@pc/components/base/editor/index.vue'
import SelectMember from './select-member.vue'

const props = defineProps({
    record: {
        type: Object as PropType<Notice.QueryRsp>
    }
})

const msgtypeEnum = useEnum('msgtype') // 消息类型
const sendtypeEnum = useEnum('sendtype') // 发布类型

const { global: { t } } = i18n
const formRef = ref<FormInstance>()
const show = ref(true)
const refresh = ref(false)
const showSelectMember = ref(false) // 是否弹出选择接收会员
const selectedValues = ref<Model.OrganSelectRsp[]>([]) // 选中的会员
const dateValue = ref<string[]>([])

const formData = ref<Partial<Notice.NoticeMsgAddReq>>({})

const { data, loading, run } = useRequest(noticeMsgDetail, {
    manual: true,
    onSuccess: ((res) => {
        const { autoid, title, content, endtime, msgtype, scheduletime, sendtype } = res.data
        formData.value = {
            autoid,
            content,
            msgtype,
            sendtype,
            title
        }
        dateValue.value = [formatDate(scheduletime), formatDate(endtime)]
    }),
    onError: (err) => {
        ElMessage.error(err)
    }
})

// 表单验证规则
const formRules: FormRules = {
    title: [{ required: true }],
    msgtype: [{ required: true }],
    sendtype: [{ required: true }],
    memberidlist: [{ required: true, validator: () => !!selectedValues.value.length }],
    invertorID: [{ required: true }],
    date: [{ required: true, validator: () => dateValue.value?.length === 2 }],
    content: [{ required: true }],
}

// 选择接收会员
const onMemberChange = (items: Model.OrganSelectRsp[]) => {
    selectedValues.value = items
    formRef.value?.validateField('memberidlist')
}

const onCancel = (isRefresh = false) => {
    show.value = false
    refresh.value = isRefresh
}

const onSubmit = () => {
    const [startDate, endDate] = dateValue.value
    const rawData = { ...formData.value }
    rawData.scheduletime = startDate
    rawData.endtime = endDate
    rawData.memberidlist = selectedValues.value.map((e) => e.userid).join(',')

    formRef.value?.validate((valid) => {
        if (valid) {
            loading.value = true
            if (rawData.autoid) {
                noticemsgedit({
                    data: rawData
                }).then(() => {
                    ElMessage.success(t('common.tips3'))
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(t('common.tips4') + err)
                }).finally(() => {
                    loading.value = false
                })
            } else {
                noticemsgadd({
                    data: rawData
                }).then(() => {
                    ElMessage.success(t('common.tips3'))
                    onCancel(true)
                }).catch((err) => {
                    ElMessage.error(t('common.tips4') + err)
                }).finally(() => {
                    loading.value = false
                })
            }
        }
    })
}

onMounted(() => {
    const auditid = props.record?.autoid
    if (auditid) {
        run({ auditid })
    }
})
</script>