<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="110px" :rules="formRules">
                <el-form-item label="差旅报销单号" prop="travel_reimbursement_id">
                    <el-input v-model="formData.trip_reimbursement_code" clearable placeholder="点击选则"
                        @click="showDialog = true" readonly />
                </el-form-item>
                <el-form-item label="发票类型" prop="invoice_type">
                    <el-select v-model="formData.invoice_type" placeholder="请选择" class="flex-1">
                        <el-option :label="item.name" :value="item.value" v-for="item in dictData.invoice_type"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发票号" prop="invoice_sn">
                    <el-input v-model="formData.invoice_sn" clearable placeholder="请输入发票号" />
                </el-form-item>
                <el-form-item label="发票税率" prop="tax_rate">
                    <el-select v-model="formData.tax_rate" placeholder="请选择" class="flex-1">
                        <el-option :label="item.name" :value="item.value" v-for="item in dictData.tax_rate"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发票形式" prop="invoice_form">
                    <el-select v-model="formData.invoice_form" placeholder="请选择" class="flex-1">
                        <el-option :label="item.name" :value="item.value" v-for="item in dictData.invoice_form"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发票金额" prop="invoice_amount">
                    <el-input v-model="formData.invoice_amount" clearable placeholder="请输入发票金额" />
                </el-form-item>
                <el-form-item label="发票税额">
                    <el-input v-model="tax_amount" clearable disabled placeholder="请输入发票税额" />
                </el-form-item>
                <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 formData.annex" 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-form-item label="发票备注" prop="remark">
                    <el-input v-model="formData.remark" clearable placeholder="请输入发票备注" />
                </el-form-item>
            </el-form>


            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <projectTravelReimbursement @customEvent="customEvent"></projectTravelReimbursement>
            </el-dialog>

        </popup>
    </div>
</template>

<script lang="ts" setup name="projectTravelReimbursementInvoiceDetailEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiProjectTravelReimbursementInvoiceDetailAdd, apiProjectTravelReimbursementInvoiceDetailEdit, apiProjectTravelReimbursementInvoiceDetailDetail } from '@/api/project_travel_reimbursement_invoice_detail'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import projectTravelReimbursement from "@/components/project_travel_reimbursement/index.vue"
import configs from "@/config"
import useUserStore from "@/stores/modules/user";
import { computed } from "vue"
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
let props = 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: '',
    "travel_reimbursement_id": "1",
    trip_reimbursement_code: "",
    "invoice_type": "",
    "invoice_sn": "",
    "tax_rate": "",
    "invoice_form": "",
    "invoice_amount": "",
    "annex": [],
    "remark": ""
})

let tax_amount = computed(() => {
    let index = props.dictData.tax_rate.findIndex((item) => item.value == formData.tax_rate)
    console.log(index)
    return (formData.invoice_amount * (props.dictData.tax_rate[index]?.name / 100)).toFixed(2) || 0
})

// let formData.tax_rate
// 上传文件
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)
}
const customEvent = (e: any) => {
    formData.travel_reimbursement_id = e.id
    formData.trip_reimbursement_code = e.trip_reimbursement_code
    showDialog.value = false
}
// 表单验证
const formRules = reactive<any>({
    travel_reimbursement_id: [{
        required: true,
        message: '请输入差旅报销id',
        trigger: ['blur']
    }],
    invoice_type: [{
        required: true,
        message: '请输入发票类型',
        trigger: ['blur']
    }],
    invoice_sn: [{
        required: true,
        message: '请输入发票号',
        trigger: ['blur']
    }],
    tax_rate: [{
        required: true,
        message: '请输入发票税率',
        trigger: ['blur']
    }],
    invoice_form: [{
        required: true,
        message: '请输入发票形式',
        trigger: ['blur']
    }],
    invoice_amount: [{
        required: true,
        message: '请输入发票金额',
        trigger: ['blur']
    }],
    tax_amount: [{
        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]
        }
    }


}

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


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