<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="120px" :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 placeholder="请输入项目名称" />
                        </el-form-item> </el-col>
                    <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 placeholder="请输入直接上级" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合计金额(元)" prop="insurance">
                            <el-input v-model="formData.insurance" clearable type="number" @input="amountinput"
                                placeholder="请输入合计金额(元)" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="合计金额大写(元)" prop="amount_daxie">
                            <el-input v-model="formData.amount_daxie" clearable disabled placeholder="请输入合计金额大写(元)" />
                        </el-form-item> </el-col>
                    <el-col :span="24">
                        <el-form-item label="报销类型" prop="insurance_date">
                            <el-radio-group v-model="formData.insurance_date" placeholder="请选择报销类型">
                                <el-radio v-for="( item, index ) in  dictData.pay_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="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入借款单单号" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="借款金额（未还）" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入借款金额（未还）" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="本次冲抵借款金额" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入本次冲抵借款金额" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="付款金额" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入付款金额" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="报销人" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入报销人" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="报销日期" prop="insurance_date">
                            <el-date-picker class="flex-1 !flex" v-model="formData.insurance_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="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入收款人姓名" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款银行" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入收款银行" />
                        </el-form-item> </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款账号" prop="handler">
                            <el-input v-model="formData.handler" clearable placeholder="请输入收款账号" />
                        </el-form-item> </el-col>


                    <el-col :span="8">
                        <el-form-item label="备注" prop="handler">
                            <el-input v-model="formData.handler" 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="formData.pay_plan">
                        <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="name1">
                            <template #default="{ row }">
                                <el-select v-model="row.period" clearable placeholder="请选择期次">
                                    <el-option v-for="(item, index) in dictData.pay_period " :key="index" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="三级科目" prop="pay_date">
                            <template #default="{ row }">
                                <el-date-picker v-model="row.pay_date" clearable value-format="YYYY-MM-DD "
                                    placeholder="选择签订日期">
                                </el-date-picker>
                            </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.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="remark">
                            <template #default="{ row }">
                                <el-input v-model="row.remark" />
                            </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>
                <div style="margin-bottom: 30px;">发票明细</div>
                <div style="margin-bottom: 30px;">
                    <el-table :data="tablist2">
                        <el-table-column label="序号">
                            <template #default="{ row }">

                                <el-button @click="handleAdd1(row)" size="small">+</el-button>
                                <el-button @click="handleDelete1(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="发票类型" prop="invoice_type">
                            <template #default="{ row }">
                                <el-select v-model="row.invoice_type" clearable placeholder="请选择发票类型">
                                    <el-option v-for="(item, index) in dictData.invoice_type" :key="index"
                                        :label="item.name" :value="item.value" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="发票号" prop="invoice_sn">
                            <template #default="{ row }">
                                <el-input v-model="row.invoice_sn" />
                            </template></el-table-column>
                        <el-table-column label="发票税率" prop="tax_rate">
                            <template #default="{ row }">
                                <el-select v-model="row.tax_rate" clearable placeholder="请选择发票类型">
                                    <el-option v-for="(item, index) in dictData.tax_rate" :key="index" :label="item.name"
                                        :value="item.value" />
                                </el-select> </template>
                        </el-table-column>
                        <el-table-column label="发票形式" prop="invoice_form">
                            <template #default="{ row }">
                                <el-select v-model="row.invoice_form" clearable placeholder="请选择发票类型">
                                    <el-option v-for="(item, index) in dictData.invoice_form" :key="index"
                                        :label="item.name" :value="item.value" />
                                </el-select> </template>
                        </el-table-column>

                        <el-table-column label="发票金额" prop="amount">
                            <template #default="{ row }">
                                <el-input v-model="row.amount" /> </template>
                        </el-table-column>

                        <el-table-column label="发票税额" prop="tax">
                            <template #default="{ row }">
                                <el-input v-model="row.tax" /> </template>
                        </el-table-column>
                        <el-table-column label="发票附件" prop="annex">
                            <template #default="{ row, $index }">
                                <!-- <el-input v-model="row.annex" /> -->
                                <div>
                                    <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="(response, file, fileList) => { return handleAvatarSuccess_four1($index, response, file, fileList) }"
                                        ref="upload">
                                        <el-button type="primary">
                                            上传
                                        </el-button>
                                    </el-upload>
                                    <div v-if="row.annex">
                                        <div v-for="(item, index) in row.annex" style="margin-left: 5px;display: block;">

                                            <a style="margin-left: 10px; color: #4a5dff; align-self: flex-start"
                                                :href="item" target="_blank">{{ item }}</a>
                                            <span style="cursor: pointer;margin-left: 5px;"
                                                @click="delFileFn1(row, index)">x</span>
                                        </div>
                                    </div>
                                </div>

                            </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 { insurancemanagementAdd, insurancemanagementEdit, insurancemanagementDetail } from '@/api/project_insurance_management'
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 tablist2 = reactive([{}])
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 customEvent = (e) => {
    formData.project_id = e.id
    project_name.value = e.name
    project_code.value = e.project_code
    showDialog.value = false

}
const customEvent1 = (e) => {
    formData.project_person_id = e.id
    idcard.value = e.idcard
    person_name.value = e.name
    showDialog1.value = false

}

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

const handleDelete = (row: any) => {
    // 删除 row
    const index = formData.pay_plan.indexOf(row);
    formData.pay_plan.splice(index, 1);
};
// 上传文件
const handleAvatarSuccess_four1 = (index, response, file, fileList) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    if (!tablist2[index].annex) {
        tablist2[index].annex = [];  // 如果 annex 不存在，先创建一个空数组
    }
    console.log(tablist2[index], index, tablist2)
    // console.log(index, response)
    tablist2[index].annex.push({ uri: response.data.uri, name: response.data.name });




    // console.log(response.data.uri, index, tablist2)
    // formDataannex1.push(
    //     { uri: response.data.uri, name: response.data.name }
    // );
};

// 删除上传的文件
const delFileFn1 = (index: number) => {
    // 删除附件文件
    row.annex.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: '',
    project_person_id: '',
    insurance_date: '',
    due_date: '',
    type: '',
    insurance_no: '',
    insurance: '',
    insured_amount: '',
    insurance_company: '',
    insurance_detail: '',
    invoice_no: '',
    handler: '',
    amount_daxie: '',
    annex: [],
})


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

})

//监听金额大写输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = 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 insurancemanagementDetail({
        id: row.id
    })
    setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    await formRef.value?.validate()
    const data = { ...formData, }
    mode.value == 'edit'
        ? await insurancemanagementEdit(data)
        : await insurancemanagementAdd(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>
