<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">
                            <el-input v-model="project_code" clearable placeholder="请选择项目编码" @click="showDialog = true"
                                :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="project_id">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </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" clearable type="number" @input="amountinput"
                                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" clearable 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="合同附件" prop="field127">
                            <el-upload
                                accept="doc, docx, xls, xlsx, ppt, pptx, pdf, txt, zip, rar, tar, jpg, png, gif, jpeg, webp, wmv, avi, mpg, mpeg, 3gp, mov, mp4, flv, f4v, rmvb, mkv"
                                class="upload-demo" :show-file-list="false" aria-hidden="true"
                                :headers="{ Token: userStore.token }" :action="base_url + '/upload/file'"
                                :on-success="handleAvatarSuccess_four" ref="upload">
                                <el-button type="primary">
                                    上传
                                </el-button>
                            </el-upload>
                            <div>
                                <div v-for="(item, index) in formDataannex" style="margin-left: 5px;display: block;">
                                    <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start" :href="item.uri"
                                        target="_blank">{{ item.name }}</a>
                                    <span style="cursor: pointer;margin-left: 5px;" @click="delFileFn(index)">x</span>
                                </div>
                            </div>

                        </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.name" @click="paymentdetail(row, $index)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="工种" prop="work_type_text">
                            <template #default="{ row }">
                                <el-input v-model="row.work_type_text" />
                            </template></el-table-column>
                        <el-table-column label="银行卡号" prop="bank_no">
                            <template #default="{ row }"> <el-input v-model="row.bank_no" /> </template></el-table-column>

                        <el-table-column label="总收入" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="总支出" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="未发放" prop="pay_amount">
                            <template #default="{ row }"> <el-input v-model="row.pay_amount" />
                            </template></el-table-column>

                        <el-table-column label="本次申请付款金额" prop="pay_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>
        </popup>
        <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>

    </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 { timeFormat } from '@/utils/util'
import type { PropType } 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 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)
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const formDataannex = reactive([])
import feedback from '@/utils/feedback'
const userInfo = userStore.userInfo
const paymentlist = ref([{}])
//获取值
const customEvent = (e) => {
    formData.project_id = e.id
    project_name.value = e.name
    project_code.value = e.project_code
    showDialog.value = false

}
const customEvent1 = (e) => {
    paymentlist.value[num.value].person_id = e.id
    paymentlist.value[num.value].name = e.name

    paymentlist.value[num.value].bank_no = e.bank_no
    paymentlist.value[num.value].work_type_text = e.work_type_text
    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.value.indexOf(row);
    paymentlist.value.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    const index = paymentlist.value.indexOf(row);
    paymentlist.value.splice(index, 1);
};
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑工资付款' : '新增工资付款'
})
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        { uri: response.data.uri, name: response.data.name }


    );
};
// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.splice(index, 1)
}
// 表单数据
const formData = reactive({
    id: '',
    project_id: '',
    payment_type: '',
    apply_date: '',
    total_amount: '',
    total_amount_uppercase: '',
    payment_detail: [],
    remark: '',
    annex: [],

})


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

})

//监听金额大写输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.total_amount_uppercase = toChinesNum(e)
    }
}


// 获取详情
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

}

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


// 提交按钮
const handleSubmit = async () => {
    if (paymentlist.value.length > 0) {
        const arr1 = paymentlist.value.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()
    formData.handler = userInfo.name
}

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


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