<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit"
            @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules" inline>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="project_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_code" clearable placeholder="请选择项目编码" @click="showDialog = true"
                                :disabled="project" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称">
                            <el-input v-model="project_name" clearable placeholder="系统自动填写" disabled />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="付款类型" prop="payment_type">
                            <el-radio-group v-model="formData.payment_type" placeholder="请选择付款类型">
                                <el-radio v-for="( item, index ) in  dictData.salary_payment_type " :key="index"
                                    :label="parseInt(item.value)">
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="申请日期" prop="apply_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.apply_date" clearable type="date"
                                value-format="YYYY-MM-DD" placeholder="选择申请日期">
                            </el-date-picker>
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合计金额(元)" prop="total_amount">
                            <el-input v-model="formData.total_amount" type="number" disabled placeholder="系统自动计算" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合计金额大写(元)" prop="total_amount_uppercase">
                            <el-input v-model="formData.total_amount_uppercase" disabled placeholder="系统自动计算" />
                        </el-form-item> </el-col>

                    <el-col :span="8">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" clearable placeholder="请输入备注" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="合同附件">
                            <uploadAnnex :formData="formData"></uploadAnnex>

                        </el-form-item>
                    </el-col>
                </el-row>
                <div style="margin-bottom: 30px;">工资支付明细</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="paymentlist">
                        <el-table-column label="序号">
                            <template #default="{ row }">

                                <el-button @click="handleAdd(row)" size="small">+</el-button>
                                <el-button @click="handleDelete(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="姓名" prop="name">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.person_name" :disabled="!formData.project_id"
                                    @click="paymentdetail(row, $index)" readonly placeholder="点击选择人员" />
                            </template>
                        </el-table-column>
                        <el-table-column label="工种" prop="work_type_text">
                            <template #default="{ row }">
                                <el-input v-model="row.person_work_type_text" disabled placeholder="系统自动获取" />
                            </template></el-table-column>
                        <el-table-column label="银行卡号" prop="bank_no">
                            <template #default="{ row }"> <el-input v-model="row.person_idcard" placeholder="系统自动获取"
                                    disabled />
                            </template></el-table-column>

                        <el-table-column label="总收入" prop="total_income">
                            <template #default="{ row }"> <el-input v-model="row.total_income" placeholder="系统自动获取"
                                    disabled />
                            </template></el-table-column>

                        <el-table-column label="总支出" prop="pay_out">
                            <template #default="{ row }"> <el-input v-model="row.pay_out" placeholder="系统自动获取"
                                    disabled />
                            </template></el-table-column>

                        <el-table-column label="未发放" prop="balance">
                            <template #default="{ row }"> <el-input v-model="row.balance" placeholder="系统自动获取"
                                    disabled />
                            </template></el-table-column>

                        <el-table-column label="本次申请付款金额" prop="apply_amount">
                            <template #default="{ row }"> <el-input v-model="row.apply_amount" />
                            </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-form>
            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectDialog @customEvent="customEvent"></projectDialog>
            </el-dialog>
            <div v-if="showDialog1">
                <el-dialog v-model="showDialog1" title="选择项目人员" width="70%">
                    <customDialog @customEvent="customEvent1" :project_id="formData.project_id"></customDialog>
                </el-dialog>
            </div>
        </popup>

    </div>
</template>

<script lang="ts" setup name="procurementContractEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import projectDialog from '@/components/project/index.vue'
import { toChinesNum } from "@/utils/util";
import { projectsalarypaymentAdd, projectsalarypaymentEdit, projectsalarypaymentDetail } from '@/api/project_salary_payment'
import customDialog from '@/components/project_personnel/index.vue'
import type { PropType } from 'vue'
import feedback from '@/utils/feedback'
import { watch } from "vue"
import { projectsalaryDetailLists } from "@/api/project_salary_detail.ts"

// 上传文件
import annexUpload from "@/components/annexUpload/index.vue"
const handleAvatarSuccess_four = (response: any) => {
    // @ts-ignore
    response.code != 0 ? formData.annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};

// 删除上传的文件
const delFileFn = (index: number) => { formData.annex.splice(index, 1) }
import { useDictData } from '@/hooks/useDictOptions'

const { dictData } = useDictData('salary_payment_type')

let props = defineProps({
    project: Object
})
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 project_name = ref('')
const project_code = ref('')
const person_name = ref('')
const idcard = ref('')
const num = ref(0)
const formDataannex = reactive([])
const paymentlist = reactive([{}])
// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    payment_type: '',
    apply_date: '',
    total_amount: '',
    total_amount_uppercase: '',
    payment_detail: [],
    remark: '',
    annex: [],

})
//获取值
const customEvent = (e) => {
    formData.project_id = e.id
    project_name.value = e.name
    project_code.value = e.project_code
    paymentlist.splice(0, 1, {});
    paymentlist.splice(1, 99999);
    // paymentlist = [{}]
    showDialog.value = false

}

if (props.project) customEvent(props.project);


const customEvent1 = (e) => {
    paymentlist[num.value].person_id = e.id
    paymentlist[num.value].person_name = e.name
    paymentlist[num.value].person_idcard = e.bank_no
    paymentlist[num.value].person_work_type_text = e.work_type_text
    paymentlist[num.value].total_income = e.total_income
    paymentlist[num.value].balance = e.balance
    paymentlist[num.value].pay_out = e.pay_out
    showDialog1.value = false
}

//打开人员弹窗
const paymentdetail = (row, index) => {
    if (formData.project_id) {
        num.value = index
        showDialog1.value = true
    } else {
        feedback.msgError('请选择项目后，在选择人员信息')
    }


}
const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = paymentlist.indexOf(row);
    paymentlist.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    const index = paymentlist.indexOf(row);
    paymentlist.splice(index, 1);
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑工资付款' : '新增工资付款'
})


//金额计算
watch(
    paymentlist,
    () => {
        formData.total_amount = 0
        paymentlist.forEach(item => {
            // item.balance = (item.total_income - item.total_pay_out) || 0
            formData.total_amount += (+item.apply_amount)
        })
        formData.total_amount_uppercase = toChinesNum(formData.total_amount)
    },
)

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

})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.annex && data.annex.length > 0) {
        const arry1 = data.annex.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)


    }
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    project_name.value = data.project_name
    project_code.value = data.project_code
    idcard.value = data.person_idcard
    person_name.value = data.person_name
    let res = await projectsalaryDetailLists({ payment_salary_id: data.id })
    Object.assign(paymentlist, res.lists)

}

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


// 提交按钮
const handleSubmit = async () => {
    if (paymentlist.length > 0) {
        const arr1 = paymentlist.map(({ name, bank_no, work_type_text, ...rest }) => rest)
        formData.payment_detail = arr1
    }
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await projectsalarypaymentEdit(data)
        : await projectsalarypaymentAdd(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>
