<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="60vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="单据主题" prop="theme">
                            <el-input v-model="formData.theme" clearable placeholder="请输入单据主题" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单据编号">
                            <el-input v-model="formData.code" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="借款天数" prop="days">
                            <el-input v-model="formData.days" clearable placeholder="请输入借款天数" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="备注">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" type="textarea" />
                        </el-form-item>
                    </el-col>
                    <create-user-lable flag :form-data='formData' name="申请"></create-user-lable>
                </el-row>
                <form-table :form-data="formData.detail" :config="tableConfig" :dict-data="dictData">
                    <template #accumulate>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="票据总张数:">
                                    {{ total_bill_num }}
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="申请金额:">
                                    {{ total_amount }}
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </template>

                </form-table>

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="financialFeeApplicationEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiFinancialFeeApplicationAdd, apiFinancialFeeApplicationEdit, apiFinancialFeeApplicationDetail, apiFinancialFeeApplicationDetailLists, apiFinancialFeeApplicationDetailDelete } from '@/api/financial_fee_application'
import type { PropType } from 'vue'
import { computed } from "vue"

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑财务管理--费用申请' : '新增财务管理--费用申请'
})

const total_amount = computed(() => {
    return (formData.detail.reduce(
        (accumulator, currentValue) => (accumulator) + Number(currentValue.amount), 0
    )).toFixed(2);
})

const total_bill_num = computed(() => {
    return formData.detail.reduce(
        (accumulator, currentValue) => (accumulator) + Number(currentValue.bill_num), 0
    );
})



// 表单数据
const formData = reactive({
    id: '',
    theme: '',
    code: '',
    days: '',
    remark: '',
    create_user: '',
    create_time: '',
    detail: [
        {
            "subject_category": '',
            "bill_num": '',
            "amount": '',
            "remark": ""
        }
    ]
})


const tableConfig = reactive(
    {
        title: "申请明细",
        tableConfig: [
            {
                label: "科目类别",
                value: 'subject_category',
                select: 'subject_category'

            },
            {
                label: "票据张数",
                value: 'bill_num',
                type: 'number'
            },
            {
                label: "申请金额",
                type: 'number',
                value: 'amount',
            },
            {
                label: "备注",
                value: 'remark',
            },

        ],
        deleteApi: apiFinancialFeeApplicationDetailDelete,
    }
)


// 表单验证
const formRules = reactive<any>({
    theme: [{
        required: true,
        message: '请输入单据主题',
        trigger: ['blur']
    }],
    code: [{
        required: true,
        message: '请输入单据编号',
        trigger: ['blur']
    }],
    days: [{
        required: true,
        message: '请输入借款天数',
        trigger: ['blur']
    }],
    create_user: [{
        required: true,
        message: '请输入申请人',
        trigger: ['blur']
    }],
    create_time: [{
        required: true,
        message: '请输入申请日期',
        trigger: ['blur']
    }]
})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    let res = await apiFinancialFeeApplicationDetailLists({ fee_application_id: data.id })
    formData.detail = res.lists


}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiFinancialFeeApplicationEdit(data)
        : await apiFinancialFeeApplicationAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}



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