<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @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="contract_name">
                            <el-input v-model="formData.contract_name" clearable placeholder="点击选择合同"
                                @click="showDialog = true" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同类型">
                            <el-input v-model="formData.contract_type_text" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="费用申请单">
                            <el-input v-model="formData.fee_application_theme" clearable placeholder="点击选择费用申请单"
                                @click="showDialog1 = true" readonly />
                        </el-form-item>
                    </el-col>
                    <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="bill_num">
                            <el-input v-model="formData.bill_num" clearable placeholder="请输入单据张数" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="支付方式" prop="pay_type">
                            <el-select v-model="formData.pay_type" class=" flex-1">
                                <el-option v-for="item in dictData.financial_pay_type" :key="item.value" :label="item.name"
                                    :value="parseInt(item.value)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="事由" prop="content">
                            <el-input v-model="formData.content" clearable placeholder="请输入事由" type="textarea" />
                        </el-form-item>
                    </el-col>
                    <CreateUserLable :form-data="formData" flag name="申请"></CreateUserLable>
                    <el-col :span="8">
                        <el-form-item label="附件" prop="annex">
                            <UploadAnnex :form-data="formData"></UploadAnnex>
                        </el-form-item>
                    </el-col>
                </el-row>

                <FormTable :form-data="formData.detail" :config="tableConfig" :dict-data="dictData">
                    <el-table-column label="部门">
                        <template #default="{ row }">
                            <el-select v-model="row.dept_id" placeholder="请选择部门">
                                <el-option :label="item.name" :value="item.id" v-for="item in deptList">
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <template #accumulate>
                        <el-col :span="8">
                            <el-form-item label="报销总金额:">
                                {{ total_amount }}
                            </el-form-item>
                        </el-col>
                    </template>

                </FormTable>
            </el-form>

            <el-dialog v-model="showDialog" title="选择合同" width="70%">
                <dialogTable :config="cost_approved_projects" @customEvent="customEvent">
                </dialogTable>
            </el-dialog>
            <el-dialog v-model="showDialog1" title="选择费用申请单" width="70%">
                <dialogTable :config="financial_fee_application" @customEvent="customEvent1">
                </dialogTable>
            </el-dialog>
        </popup>
    </div>
</template>

<script lang="ts" setup name="financialExpenseReimbursementEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiFinancialExpenseReimbursementAdd, apiFinancialExpenseReimbursementEdit, apiFinancialExpenseReimbursementDetail, apiFinancialExpenseReimbursementDetailLists, apiFinancialExpenseReimbursementDetailDelete } from '@/api/financial_expense_reimbursement'
import type { PropType } from 'vue'
import { cost_approved_projects, financial_fee_application } from "@/components/dialogTable/dialogTableConfig";
import { deptLists } from "@/api/org/department"


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 showDialog = ref(false)
const showDialog1 = ref(false)


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

// 表单数据
const formData = reactive({
    id: '',
    contract_id: '',
    contract_name: '',
    fee_application_id: '',
    contract_type_text: "",
    fee_application_theme: '',
    theme: '',
    code: '',
    bill_num: '',
    pay_type: '',
    content: '',
    annex: '',
    create_user: '',
    create_time: '',
    detail: [{
        "dept_id": '',
        "date": "",
        "subject_name": '',
        "amount": '',
        "abstract": ""
    }]
})


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


const tableConfig = reactive(
    {
        title: "报销明细",
        tableConfig: [
            {
                label: "发生日期",
                value: 'date',
                date: true

            },
            {
                label: "科目名称",
                value: 'subject_name',
                select: "subject_category"
            },
            {
                label: "金额",
                value: 'amount',
            },
            {
                label: "摘要",
                value: 'abstract',
            },

        ],
        deleteApi: apiFinancialExpenseReimbursementDetailDelete,
    }
)

const customEvent = (e) => {
    formData.contract_id = e.id
    formData.contract_name = e.contract_name
    formData.contract_type_text = e.contract_type_text
    showDialog.value = false
}
const customEvent1 = (e) => {
    formData.fee_application_id = e.id
    formData.fee_application_theme = e.theme
    showDialog1.value = false
}


// 表单验证
const formRules = reactive<any>({
    contract_id: [{
        required: true,
        message: '请输入合同id',
        trigger: ['blur']
    }],
    fee_application_id: [{
        required: true,
        message: '请输入费用申请id',
        trigger: ['blur']
    }],
    theme: [{
        required: true,
        message: '请输入单据主题',
        trigger: ['blur']
    }],
    code: [{
        required: true,
        message: '请输入单据编号',
        trigger: ['blur']
    }],
    bill_num: [{
        required: true,
        message: '请输入单据张数',
        trigger: ['blur']
    }],
    pay_type: [{
        required: true,
        message: '请输入支付方式',
        trigger: ['blur']
    }],
    content: [{
        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 apiFinancialExpenseReimbursementDetailLists({ expense_reimbursement_id: data.id })
    formData.detail = res.lists

}

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


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

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

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

const deptList = ref([])
const getDeptList = async () => {
    let res = await deptLists()
    deptList.value = res.lists
}

getDeptList()

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