<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="120px" :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" clearable placeholder="系统自动获取" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="甲方签约单位">
                            <el-input v-model="formData.part_a" clearable placeholder="系统自动获取" disabled />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="签订金额(元）">
                            <el-input v-model="formData.money" clearable placeholder="系统自动获取" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合同签订日期">
                            <el-input v-model="formData.create_date" clearable placeholder="系统自动获取" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="预算书名称" prop="name">
                            <el-input v-model="formData.name" clearable placeholder="请输入预算书名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="下达日期" prop="issue_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.issue_date" clearable
                                value-format="YYYY-MM-DD" placeholder="选择下达日期">
                            </el-date-picker>
                        </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>
                    <el-col :span="8">
                        <el-form-item label="附件" prop="annex">
                            <uploadAnnex :formData="formData"></uploadAnnex>
                        </el-form-item>
                    </el-col>
                    <createUserLable flag :formData="formData" />
                </el-row>
            </el-form>
            <el-col :span="24">
                <div style="margin-bottom: 30px;">发票明细</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="formData.detail">
                        <template #empty>
                            暂无数据，点击添加
                            <el-button @click="handleAdd" size="small">+</el-button>
                        </template>
                        <el-table-column label="序号">

                            <template #default="{ row }">
                                <el-button @click="handleAdd" size="small">+</el-button>
                                <el-button @click="handleDelete(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <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>
                        <el-table-column label="预算分成方式">
                            <template #default="{ row }">
                                <el-select v-model="row.type" placeholder="请选择">
                                    <el-option :label="item.name" :value="parseInt(item.value)"
                                        v-for="item in dictData.budget_share_method">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="预算分成金额">
                            <template #default="{ row }">
                                <el-input v-model="row.amount" type="number" />
                            </template>
                        </el-table-column>

                        <el-table-column label="备注" prop="remark">
                            <template #default="{ row }">
                                <el-input v-model="row.remark" />
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>

            <el-dialog v-model="showDialog" title="选择合同" width="70%">
                <dialogTable :config="cost_approved_projects" @customEvent="customEvent" :query="{ status: 1 }">
                </dialogTable>
            </el-dialog>
        </popup>
    </div>
</template>

<script lang="ts" setup name="financialBudgetDocEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiFinancialBudgetDocAdd, apiFinancialBudgetDocEdit, apiFinancialBudgetDocDetail } from '@/api/financial_budget_doc'
import { apiFinancialBudgetDocDetailLists, apiFinancialBudgetDocDetailDelete } from '@/api/financial_budget_doc_detail'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { cost_approved_projects } 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 popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑财务管理--项目预算书' : '新增财务管理--项目预算书'
})

// 表单数据
const formData = reactive({
    id: '',
    contract_id: '',
    contract_name: '',
    code: '',
    name: '',
    issue_date: '',
    remark: '',
    annex: '',
    create_user: '',
    create_time: '',
    detail: [],
    "contract_type_text": "",
    "part_a": "",
    "money": "",
    "create_date": "",
})


const handleAdd = (row) => {
    // 在 row 后面插入一行数据
    formData.detail.push({});
};

const handleDelete = async (row) => {
    if (row.id) await apiFinancialBudgetDocDetailDelete({ id: row.id })
    // 删除 row
    const index = formData.detail.indexOf(row);
    formData.detail.splice(index, 1);
};

const customEvent = (e) => {
    formData.contract_id = e.id
    formData.contract_name = e.contract_name
    formData.contract_type_text = e.contract_type_text
    formData.part_a = e.part_a
    formData.money = e.money
    formData.create_date = e.create_date
    showDialog.value = false
}

// 表单验证
const formRules = reactive<any>({
    contract_id: [{
        required: true,
        message: '请输入合同id',
        trigger: ['blur']
    }],
    code: [{
        required: true,
        message: '请输入预算书编号',
        trigger: ['blur']
    }],
    name: [{
        required: true,
        message: '请输入预算书名称',
        trigger: ['blur']
    }],
    issue_date: [{
        required: true,
        message: '请输入下达日期',
        trigger: ['blur']
    }],
    remark: [{
        required: true,
        message: '请输入备注',
        trigger: ['blur']
    }],
    create_user: [{
        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 apiFinancialBudgetDocDetailLists({ budget_doc_id: data.id })
    formData.detail = res.lists

}

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


// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await apiFinancialBudgetDocEdit(data)
        : await apiFinancialBudgetDocAdd(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>
