<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="560px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
                <el-form-item label="日期" prop="cost_date">
                    <el-date-picker
                        v-model="formData.cost_date"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期"
                        :disabled="mode === 'edit'"
                    />
                </el-form-item>
                <el-form-item label="自媒体渠道" prop="media_channel_code">
                    <el-select
                        v-model="formData.media_channel_code"
                        placeholder="请选择自媒体渠道"
                        class="account-cost-channel-select w-full"
                        filterable
                    >
                        <el-option-group
                            v-for="g in mediaChannelGroups"
                            :key="g.group_name"
                            :label="g.group_name"
                        >
                            <el-option
                                v-for="ch in g.channels"
                                :key="ch.channel_code"
                                :label="ch.channel_name"
                                :value="ch.channel_code"
                            >
                                <div class="channel-opt-row">
                                    <span class="opt-name">{{ ch.channel_name }}</span>
                                </div>
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="dept_id">
                    <el-tree-select
                        v-model="formData.dept_id"
                        :data="deptOptions"
                        node-key="id"
                        :props="treeProps"
                        :default-expand-all="true"
                        check-strictly
                        placeholder="请选择绑定部门"
                        clearable
                        filterable
                        class="w-full"
                    />
                </el-form-item>
                <el-form-item label="账户消耗" prop="amount">
                    <el-input-number
                        v-model="formData.amount"
                        :min="0"
                        :step="0.01"
                        :precision="2"
                        class="w-full"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="formData.remark"
                        type="textarea"
                        :autosize="{ minRows: 4, maxRows: 6 }"
                        maxlength="255"
                        show-word-limit
                        placeholder="请输入备注"
                    />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'

import { accountCostAdd, accountCostDetail, accountCostEdit } from '@/api/finance'
import Popup from '@/components/popup/index.vue'

interface MediaChannelGroup {
    group_name: string
    channels: { channel_code: string; channel_name: string }[]
}

interface DeptOption {
    id: number
    name: string
    children?: DeptOption[]
}

const props = defineProps<{
    mediaChannelGroups: MediaChannelGroup[]
    deptOptions: DeptOption[]
    defaultMediaChannelCode: string
}>()

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref<'add' | 'edit'>('add')

const popupTitle = computed(() => (mode.value === 'edit' ? '编辑账户消耗' : '新增账户消耗'))
const treeProps = {
    value: 'id',
    label: 'name',
    children: 'children',
}

const formData = reactive({
    id: '',
    cost_date: '',
    media_channel_code: '',
    dept_id: '' as string | number,
    amount: 0,
    remark: '',
})

const formRules = {
    cost_date: [
        {
            required: true,
            message: '请选择日期',
            trigger: ['change'],
        },
    ],
    media_channel_code: [
        {
            required: true,
            message: '请选择自媒体渠道',
            trigger: ['change'],
        },
    ],
    dept_id: [
        {
            required: true,
            message: '请选择绑定部门',
            trigger: ['change'],
        },
    ],
    amount: [
        {
            required: true,
            message: '请输入账户消耗金额',
            trigger: ['blur', 'change'],
        },
    ],
}

const resetForm = () => {
    formData.id = ''
    formData.cost_date = ''
    formData.media_channel_code = props.defaultMediaChannelCode || ''
    formData.dept_id = ''
    formData.amount = 0
    formData.remark = ''
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    if (mode.value === 'edit') {
        await accountCostEdit(formData)
    } else {
        await accountCostAdd(formData)
    }
    popupRef.value?.close()
    emit('success')
}

const open = (type: 'add' | 'edit' = 'add') => {
    mode.value = type
    resetForm()
    popupRef.value?.open()
}

const setFormData = (data: Record<string, any>) => {
    formData.id = data.id ?? ''
    formData.cost_date = data.cost_date ?? ''
    formData.media_channel_code = data.media_channel_code ?? ''
    formData.dept_id = data.dept_id ? Number(data.dept_id) : ''
    formData.amount = Number(data.amount ?? 0)
    formData.remark = data.remark ?? ''
}

const getDetail = async (row: Record<string, any>) => {
    const data = await accountCostDetail({ id: row.id })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail,
})
</script>

<style scoped lang="scss">
.account-cost-channel-select {
    :deep(.channel-opt-row) {
        display: flex;
        align-items: center;
        width: 100%;
        min-width: 0;
        padding-right: 4px;
    }
    :deep(.opt-name) {
        flex: 1;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>
