<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="num">
                            <el-input v-model="formData.num" clearable placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project">
                            <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" readonly
                                @click="showDialog = true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编号" prop="project_num">
                            <el-input v-model="formData.project_num" clearable placeholder="请输入项目编号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="登记人" prop="djr">
                            <el-input v-model="formData.djr" disabled clearable placeholder="请输入登记人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="登记日期" prop="djrq">
                            <el-date-picker class="flex-1 !flex" v-model="formData.djrq" clearable type="date"
                                value-format="YYYY-MM-DD" disabled placeholder="请选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="进度申报造价合计" prop="sbhj" label-width="160px">
                            <el-input v-model="formData.sbhj" clearable placeholder="系统自动计算" disabled type='number' />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="进度审核造价合计" prop="shhj" label-width="160px">
                            <el-input v-model="formData.shhj" clearable placeholder="系统自动计算" disabled type='number' />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="累计应付工程款合计" prop="ljhj" label-width="160px">
                            <el-input v-model="formData.ljhj" clearable placeholder="系统自动计算" disabled type='number' />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="附件" prop="annex">
                    <uploadAnnex :formData="formData"></uploadAnnex>
                </el-form-item>
                <el-dialog v-model="showDialog" title="选择项目" width="70%">
                    <dialogTable :config="cost_project" @customEvent="customEvent">
                    </dialogTable>
                </el-dialog>
            </el-form>
            <div style="margin-bottom: 30px;">进度明细</div>
            <div style="margin-bottom: 30px;">
                <el-table :data="formData.project_progress_payment_detail">

                    <template #empty>
                        <span class="cursor-pointer">暂无数据，点击添加 <el-button @click="handleAdd">+</el-button></span>
                    </template>
                    <el-table-column label="序号" width="150px">
                        <template #default="{ row }">
                            <el-button @click="handleAdd">+</el-button>
                            <el-button @click="handleDelete(row)">-</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="所在目录" width="200px">
                        <template #default="scope">
                            <el-input v-model="scope.row.directory" />
                        </template>
                    </el-table-column>
                    <el-table-column label="单位工程名称" prop="unit_project_name" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.unit_project_name" />
                        </template>
                    </el-table-column>
                    <el-table-column label="合同工程款总额" prop="contract_total_amount" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.contract_total_amount" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="合同付款比例（%）(%)" prop="dcntract_payment_rate" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.dcntract_payment_rate" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="时间" prop="time" width="200px">

                        <template #default="{ row }">
                            <el-date-picker class="flex-1 !flex" v-model="row.time" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="请选择日期">
                            </el-date-picker>
                        </template>
                    </el-table-column>
                    <el-table-column label="形象进度" prop="image_progress" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.image_progress" />
                        </template>
                    </el-table-column>
                    <el-table-column label="申报造价(土建)" prop="declared_cost_tj" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.declared_cost_tj" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="申报造价(安装)" prop="declared_cost_az" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.declared_cost_az" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="申报造价(其他)" prop="declared_cost_other" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.declared_cost_other" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="进度申报造价小计" prop="jdsbzj_xiaoji" width="200px">

                        <template #default="scope">
                            <el-input v-model="scope.row.jdsbzj_xiaoji" placeholder="系统自动计算" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column label="审核造价(土建)" prop="audit_cost_tj" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.audit_cost_tj" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="审核造价(安装)" prop="audit_cost_az" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.audit_cost_az" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="审核造价(其他)" prop="audit_cost_other" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.audit_cost_other" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="进度审核造价小计" prop="jdshzj_xiaoji" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.jdshzj_xiaoji" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="审减额(元)" prop="deduction_amount" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.deduction_amount" type="number" placeholder="系统自动计算" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column label="完成产值比例（%）(%)" prop="completed_rate" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.completed_rate" type="number" />
                        </template>
                    </el-table-column>
                    <el-table-column label="累计完成工程款" prop="ljwc_funds" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.ljwc_funds" type="number" placeholder="系统自动计算" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column label="当期应付工程款(元)" prop="current_payable_funds" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.current_payable_funds" type="number" placeholder="系统自动计算" disabled />
                        </template>
                    </el-table-column>

                    <el-table-column label="付款比例（%）(%)" prop="payment_rate" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.payment_rate" type="number" placeholder="系统自动计算" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" width="200px">

                        <template #default="{ row }">
                            <el-input v-model="row.remark" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </popup>
    </div>
</template>

<script lang="ts" setup name="projectProgressPaymentEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectProgressPaymentAdd, apiProjectProgressPaymentEdit, apiProjectProgressPaymentDetail } from '@/api/project_progress_payment'
import { apiProjectProgressPaymentDetailDelete } from '@/api/project_progress_payment_detail'

import type { PropType } from 'vue'
import { cost_project } from "@/components/dialogTable/dialogTableConfig"
import { timeFormat } from '@/utils/util'
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore().userInfo;

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: '',
    dataid: '',
    num: '',
    project_id: '',
    project_name: "",
    project_num: '',
    djr: userStore.account,
    djrq: timeFormat('', 'yyyy-mm-dd'),
    sbhj: '',
    shhj: '',
    ljhj: '',
    annex: [],
    projectInfo: {},
    project_progress_payment_detail: []

})

// 监听计算
watch(
    () => formData.project_progress_payment_detail,
    (value) => {
        formData.sbhj = 0
        formData.shhj = 0
        formData.ljhj = 0
        value.forEach(item => {
            item.jdsbzj_xiaoji = Number(item.declared_cost_tj) + Number(item.declared_cost_az) + Number(item.declared_cost_other)
            item.jdshzj_xiaoji = Number(item.audit_cost_tj) + Number(item.audit_cost_az) + Number(item.audit_cost_other)
            item.payment_rate = item.dcntract_payment_rate
            item.deduction_amount = item.jdsbzj_xiaoji - item.jdshzj_xiaoji
            item.ljwc_funds = item.jdshzj_xiaoji
            item.current_payable_funds = (Number(item.ljwc_funds) * Number(item.payment_rate)) || 0
            formData.sbhj += item.jdsbzj_xiaoji
            formData.shhj += item.jdshzj_xiaoji
            formData.ljhj += item.current_payable_funds
        })
    },
    {
        deep: true
    }
)




const customEvent = (e: any) => {
    formData.project_id = e.id
    formData.project_name = e.project_name
    formData.project_num = e.project_num
    showDialog.value = false
}

// 表单验证
const formRules = reactive<any>({

})
const handleAdd = () => {
    formData.project_progress_payment_detail.push({
        project_progress_payment_id: '',
        directory: '',
        unit_project_name: '',
        time: '',
        image_progress: '',
        declared_cost_tj: '',
        declared_cost_az: '',
        declared_cost_other: '',
        jdsbzj_xiaoji: '',
        audit_cost_tj: '',
        audit_cost_az: '',
        audit_cost_other: '',
        jdshzj_xiaoji: '',
        deduction_amount: '',
        completed_rate: '',
        contract_total_amount: '',
        ljwc_funds: '',
        current_payable_funds: '',
        payment_rate: '',
        dcntract_payment_rate: '',
        remark: '',

    })
}


const handleDelete = async (row: any) => {
    if (row.id) {
        await apiProjectProgressPaymentDetailDelete({ id: row.id })
    }
    const index = formData.project_progress_payment_detail.indexOf(row);
    formData.project_progress_payment_detail.splice(index, 1);
}



// 获取详情
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]
        }
    }
    formData.project_id = formData.projectInfo.id
    formData.project_name = formData.projectInfo.project_name
    formData.project_num = formData.projectInfo.project_num


}

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


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