<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="85vw" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item label="项目名称" prop="project_id">
                    <el-input v-model="formData.project_name" clearable placeholder="点击选择" readonle
                        @click="showDialog = true" />
                </el-form-item>

                <!-- <el-form-item label="报销类型" prop="reimbursement_type">
                    <el-radio-group v-model="formData.reimbursement_type" class="ml-4">
                        <el-radio :label="item.value" size="large" v-for="item in dictData.reimbursement_type ">{{ item.name
                        }}</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="报销类型" prop="reimbursement_type">
                    <el-checkbox-group v-model="formData.reimbursement_type" placeholder="报销类型">
                        <el-checkbox v-for="(item, index) in dictData.reimbursement_type" :key="index" :label="item.value">
                            {{ item.name }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <el-form-item label="借款单号" prop="loan_apply_id" v-if="formData.reimbursement_type.includes('1')">
                    <el-input v-model="formData.loan_apply_code" clearable placeholder="点击选择" readonly
                        @click="showDialog1 = true" />
                </el-form-item>
                <el-form-item label="冲抵借款金额" prop="offset_loan_amount" v-if="formData.reimbursement_type.includes('1')">
                    <el-input v-model="formData.offset_loan_amount" clearable placeholder="请输入冲抵借款金额" />
                </el-form-item>
                <el-form-item label="报销人" prop="apply_user">
                    <el-input v-model="formData.apply_user" clearable placeholder="请输入报销人" />
                </el-form-item>
                <el-form-item label="报销日期" prop="apply_date">
                    <el-date-picker class="flex-1 !flex" v-model="formData.apply_date" clearable value-format="YYYY-MM-DD "
                        placeholder="选择日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="收款人姓名" prop="payee_name">
                    <el-input v-model="formData.payee_name" clearable placeholder="请输入收款人姓名" />
                </el-form-item>
                <el-form-item label="收款银行" prop="payee_bank">
                    <el-input v-model="formData.payee_bank" clearable placeholder="请输入收款银行" />
                </el-form-item>
                <el-form-item label="收款账号" prop="payee_account">
                    <el-input v-model="formData.payee_account" clearable placeholder="请输入收款账号" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" clearable 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="bank_account_id">
                    <el-input v-model="formData.account_name" clearable placeholder="点击选择银行" readonly
                        @click="showDialog2 = true" />
                </el-form-item> -->
                <el-form-item label="账户编码" prop="bank_account_id">
                    <el-input v-model="formData.bank_account.account_sn" clearable placeholder="点击选择银行" readonly
                        @click="showDialog2 = true" />
                </el-form-item>
                <el-form-item label="开户银行" prop="bank_account_id">
                    <el-input v-model="formData.bank_account.deposit_bank" clearable readonly />
                </el-form-item>
                <el-form-item label="开户名称" prop="bank_account_id">
                    <el-input v-model="formData.bank_account.account_name" clearable readonly />
                </el-form-item>
                <el-form-item label="开户账号" prop="bank_account_id">
                    <el-input v-model="formData.bank_account.account" clearable readonly />
                </el-form-item>

                <el-col :span="24">
                    <div style="margin-bottom: 30px;">报销明细</div>
                    <div style="margin-bottom: 30px;">
                        <el-table :data="formData.reimbursement_detail">
                            <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="一级科目">
                                <template #default="scope">
                                    <el-input v-model="scope.row.first_level_subject" @click="openDialog1(scope)" readonly
                                        placeholder="点击选择" />
                                </template>
                            </el-table-column>

                            <el-table-column label="金额">
                                <template #default="{ row }"> <el-input v-model="row.amount" type="number" />
                                </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-col>
                <el-col :span="24">
                    <div style="margin-bottom: 30px;">发票明细</div>
                    <div style="margin-bottom: 30px;">
                        <el-table :data="formData.invoice_detail">
                            <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="发票类型">
                                <template #default="{ row }">
                                    <el-select v-model="row.invoice_type" placeholder="请选择">
                                        <el-option :label="item.name" :value="item.value"
                                            v-for="item in dictData.invoice_type"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>

                            <el-table-column label="发票号">
                                <template #default="{ row }"> <el-input v-model="row.invoice_sn" type="number" />
                                </template></el-table-column>
                            <el-table-column label="发票税率">
                                <template #default="{ row }">
                                    <el-select v-model="row.tax_rate" placeholder="请选择">
                                        <el-option :label="item.name" :value="item.value"
                                            v-for="item in dictData.tax_rate"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="发票形式">
                                <template #default="{ row }">
                                    <el-select v-model="row.invoice_form" placeholder="请选择">
                                        <el-option :label="item.name" :value="item.value"
                                            v-for="item in dictData.invoice_form"></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="发票金额" prop="remark">
                                <template #default="{ row }">
                                    <el-input v-model="row.invoice_amount" />
                                </template>
                            </el-table-column>
                            <el-table-column label="发票附件" prop="remark">
                                <template #default="scope">
                                    <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_four1" ref="upload">
                                        <el-button type="primary" @click="invoiceIndex = scope.$index">
                                            上传
                                        </el-button>
                                    </el-upload>
                                    <div>
                                        <div v-for="(item, index) in scope.row.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="scope.row.annex.splice(index, 1)">x</span>
                                        </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-col>
            </el-form>

            <el-dialog v-model="showDialog" title="选择项目" width="70%">
                <project @customEvent="customEvent">
                </project>
            </el-dialog>
            <div v-if="showDialog1">
                <el-dialog v-model="showDialog1" title="选择项目" width="70%">
                    <projectLoanApply @customEvent="customEvent1" :project_id="formData.project_id"></projectLoanApply>
                </el-dialog>
            </div>

            <el-dialog v-model="showDialog2" title="选择账户" width="70%">
                <bankaccount @customEvent="customEvent2"></bankaccount>
            </el-dialog>
            <el-dialog v-model="showDialog3" title="选择科目" width="70%">
                <projectcostTemLists @customEvent="customEvent3"></projectcostTemLists>
            </el-dialog>

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

<script lang="ts" setup name="projectTravelReimbursementEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import type { PropType } from 'vue'
import { apiProjectExpenseReimbursementAdd, apiProjectExpenseReimbursementEdit, apiProjectExpenseReimbursementDetail } from '@/api/project_expense_reimbursement'
import project from "@/components/project/index.vue"
import projectLoanApply from "@/components/project_loan_apply/index.vue"
import bankaccount from "@/components/bankaccount/index.vue"
import projectcostTemLists from '@/components/projectcostTemLists/index.vue'
import { apiProjectExpenseReimbursementDetailLists } from "@/api/project_expense_reimbursement_detail.ts"
import { apiProjectExpenseReimbursementInvoiceDetailLists } from "@/api/project_expense_reimbursement_invoice_detail.ts"


import configs from "@/config"
import useUserStore from "@/stores/modules/user";
const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
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 showDialog2 = ref(false)
const showDialog3 = ref(false)

const customEvent = (e) => {
    formData.project_id = e.id
    formData.project_name = e.name
    console.log(e)
    showDialog.value = false
}
const customEvent1 = (e) => {
    formData.loan_apply_code = e.loan_apply_code
    formData.loan_apply_id = e.id
    showDialog1.value = false
}
const customEvent2 = (e) => {
    formData.account_name = e.account_name
    formData.bank_account_id = e.id
    formData.bank_account = {
        "account_sn": e.account_sn,
        "deposit_bank": e.deposit_bank,
        "account_name": e.account_name,
        "account": e.account
    }
    showDialog2.value = false
}
// 获取点击行的index
let rowIndex = 0
const openDialog1 = (e: any) => {
    rowIndex = e.$index
    showDialog3.value = true
}
const customEvent3 = (e: any) => {
    formData.reimbursement_detail[rowIndex].first_level_subject = e.first_level_subject
    formData.reimbursement_detail[rowIndex].project_cost_temp_id = e.id
    showDialog3.value = false
}


// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑项目财务-差旅报销' : '新增项目财务-差旅报销'
})

// 表单数据
const formData = reactive({
    id: '',
    project_id: "",
    project_name: "",
    "reimbursement_type": [], //必填，报销类型
    "loan_apply_id": "", //借款单id，当报销类型包含借款冲抵选项时必填
    "loan_apply_code": "", //借款单id，当报销类型包含借款冲抵选项时必填
    "offset_loan_amount": "", //冲抵借款金额，当报销类型包含借款冲抵选项时必填
    "apply_user": "", //必填，报销人
    "apply_date": "", //必填，报销日期
    "payee_name": "", //必填，收款人姓名
    "payee_bank": "", //必填，收款银行
    "payee_account": "", //必填，收款账号
    "remark": "", //可选，备注
    "annex": [], //可选，附件
    "bank_account_id": "", //必填，付款银行账户id
    account_name: "",
    "reimbursement_detail": [ //必填，报销明细
        {
            "project_cost_temp_id": "", //必填 项目费用模板id
            first_level_subject: "",
            "amount": "", //必填 金额
            "remark": "",//选填 备注,

        }
    ],
    "invoice_detail": [ //必填，发票明细
        {
            "invoice_type": "", //必填，发票类型
            "invoice_sn": "", //必填，发票号
            "tax_rate": "", //必填，发票税率
            "invoice_form": "", //必填，发票形式
            "invoice_amount": "", //必填，发票金额
            "annex": [], //可选，发票附件
            "remark": "" //可选，备注
        }
    ],
    "bank_account": {
        "account_sn": "",
        "deposit_bank": "",
        "account_name": "",
        "account": ""
    }
})
// 上传文件
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 invoiceIndex = ref(0)
// 上传文件
const handleAvatarSuccess_four1 = (response: any) => {
    // @ts-ignore
    response.code != 0 ? formData.invoice_detail[invoiceIndex.value].annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};

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

    project_id: [{
        required: true,
        message: '请输入项目id',
        trigger: ['blur']
    }],
    reimbursement_type: [{
        required: true,
        message: '请输入报销类型',
        trigger: ['blur']
    }],
    loan_apply_id: [{
        required: true,
        message: '请输入借款单id',
        trigger: ['blur']
    }],
    reimbursement_amount: [{
        required: true,
        message: '请输入初始报销金额',
        trigger: ['blur']
    }],
    actual_reimbursement_amount: [{
        required: true,
        message: '请输入实际报销金额',
        trigger: ['blur']
    }],
    offset_loan_amount: [{
        required: true,
        message: '请输入冲抵借款金额',
        trigger: ['blur']
    }],
    apply_user: [{
        required: true,
        message: '请输入报销人',
        trigger: ['blur']
    }],
    apply_date: [{
        required: true,
        message: '请输入报销日期',
        trigger: ['blur']
    }],
    payee_name: [{
        required: true,
        message: '请输入收款人姓名',
        trigger: ['blur']
    }],
    payee_bank: [{
        required: true,
        message: '请输入收款银行',
        trigger: ['blur']
    }],
    payee_account: [{
        required: true,
        message: '请输入收款账号',
        trigger: ['blur']
    }],
    bank_account_id: [{
        required: true,
        message: '请输入付款银行账户id',
        trigger: ['blur']
    }]
})
const handleAdd = (row: any) => {
    // 在 row 后面插入一行数据
    const index = formData.reimbursement_detail.indexOf(row);
    formData.reimbursement_detail.splice(index + 1, 0, {});
};

const handleDelete = (row: any) => {
    // 删除 row
    if (formData.reimbursement_detail.length <= 1) return
    const index = formData.reimbursement_detail.indexOf(row);
    formData.reimbursement_detail.splice(index, 1);
};

const handleAdd1 = (row: any) => {
    // 在 row 后面插入一行数据
    const index = formData.invoice_detail.indexOf(row);
    formData.invoice_detail.splice(index + 1, 0,
        {
            "invoice_type": "1",
            "invoice_sn": "FPSN-0001",
            "tax_rate": "1",
            "invoice_form": "1",
            "invoice_amount": "150",
            "annex": [],
            "remark": "test"
        }
    );
};

const handleDelete1 = (row: any) => {
    // 删除 row
    if (formData.invoice_detail.annex <= 1) return
    const index = formData.invoice_detail.indexOf(row);
    formData.invoice_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.reimbursement_type = formData.reimbursement_type.split(',')
    let res = await apiProjectExpenseReimbursementDetailLists({ expense_reimbursement_id: data.id })
    formData.reimbursement_detail = res.lists
    let res2 = await apiProjectExpenseReimbursementInvoiceDetailLists({ expense_reimbursement_id: data.id })
    formData.invoice_detail = res2.lists

}

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


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