<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">
                <div style="display: flex; flex-direction: row-reverse; justify-content: flex-start;margin-bottom: 30px;">

                    <el-select class="w-[180px]" v-model="formData.dept_id" clearable placeholder="请选择部门">
                        <el-option v-for="(item, index) in list2" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                    <el-select class="w-[180px]" v-model="formData.org_id" clearable placeholder="请选择组织" @change="deptrmt">
                        <el-option v-for="(item, index) in list1" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
                </div>

                <el-row :gutter="10">


                    <el-col :span="8">
                        <el-form-item label="报销人" prop="reimburser">
                            <el-input v-model="formData.reimburser" clearable placeholder="请输入报销人" />

                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="报销日期" prop="reimbursement_date"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-date-picker class="flex-1 !flex" v-model="formData.reimbursement_date" clearable
                                value-format="YYYY-MM-DD " placeholder="选择报销日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="customer_id" @click="showDialog = true">
                            <el-input v-model="customer_name" readonly clearable placeholder="请输入客户名称" />

                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="付款方式" prop="pay_type"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-radio-group v-model="formData.pay_type" 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="reimbursement_amount">
                            <el-input v-model="formData.reimbursement_amount" clearable placeholder="请输入报销金额"
                                @input="amountinput" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="报销金额大写" prop="invoice_amount_daxie">
                            <el-input v-model="invoice_amount_daxie" readonly clearable placeholder="请输入报销金额大写" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款人姓名" prop="payee_name"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.payee_name" clearable placeholder="请输入收款人姓名" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款银行" prop="payee_bank"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.payee_bank" clearable placeholder="请输入收款银行" />

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="收款账号" prop="payee_account"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="formData.payee_account" clearable placeholder="请输入收款账号" />

                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>


                    <el-col :span="24">

                        <el-form-item label="附件" prop="field87">
                            <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 class="tit">报销明细</div>
                <el-row>

                    <el-table :data="tablist1">
                        <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, $index }">
                                <el-input v-model="row.name1" readonly @click="subjectmu(row, $index)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="二级科目" prop="name2">
                            <template #default="{ row }">
                                <el-input v-model="row.name2" readonly />
                            </template></el-table-column>
                        <el-table-column label="用途" prop="use_to">
                            <template #default="{ row }">
                                <el-input v-model="row.use_to" /> </template>
                        </el-table-column>
                        <el-table-column label="金额" prop="amount">
                            <template #default="{ row }">
                                <el-input v-model="row.amount" type="number" @input="amountnum" /> </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>


                </el-row>
                <br />
                <div class="tit">发票明细</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-dialog v-model="showDialog1" title="选择科目" width="70%">
                    <budgetDialog @customEvent="customEvent1"></budgetDialog>
                </el-dialog>


                <el-dialog v-model="showDialog" title="选择客户" width="70%">
                    <customDialog @customEvent="customEvent"></customDialog>
                </el-dialog>

            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import customDialog from '@/components/custom-dialog/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import budgetDialog from '@/components/budget/index.vue'

import { expensereimbursementAdd, expensereimbursementEdit, expensereimbursementDetail } from '@/api/expense_reimbursement'
import { toChinesNum } from "@/utils/util";
import { getAllProjectTypes } from '@/api/projecttype'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import type { PropType } from 'vue'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import configs from "@/config"
import useUserStore from "@/stores/modules/user";

const base_url = configs.baseUrl + configs.urlPrefix
const userStore = useUserStore();
const active = ref(0)
const formDataannex = reactive([])
const formDataannex1 = reactive([])
const contract_name = ref('')
const invoice_amount_daxie = ref('')
const contract_no = ref('')
const supplier_name = ref('')
const supplier_no = ref('')
const list1 = reactive([])
const list2 = reactive([])
const tablist1 = reactive([{}])
const tablist2 = reactive([{}])
const userInfo = userStore.userInfo
console.log(userInfo, '222222')
// 上传文件
const handleAvatarSuccess_four = (
    response,
    uploadFile
) => {
    if (response.code == 0) {
        ElMessage.error(response.msg);
        return;
    }
    formDataannex.push(
        response.data.uri
    );
};

// 删除上传的文件
const delFileFn = (index: number) => {
    formDataannex.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 = (row, index: number) => {
    // 删除附件文件
    row.annex.splice(index, 1);
}

//金额计算

const amountnum = () => {
    // console.log(tablist1)
    formData.reimbursement_amount = tablist1.reduce((total, item) => {
        return total + parseInt(item.amount);
    }, 0);

    setTimeout(() => {
        toChinesNum(formData.reimbursement_amount)
    }, 10)
}
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 amount_daxie = ref('')
const showDialog = ref(false)
const showDialog1 = ref(false)
const customer_name = ref('')
const tabnum = ref(0)
const customEvent = (e: any) => {
    formData.customer_id = e.id;
    customer_name.value = e.name;
    showDialog.value = false;
};

const customEvent1 = (e: any) => {
    tablist1[tabnum.value].name1 = e.subject1;
    tablist1[tabnum.value].name2 = e.subject2;
    showDialog1.value = false;
};

//报销明细赋值
const subjectmu = (a: any, b: number) => {
    tabnum.value = b
    showDialog1.value = true
}

//获取所有组织
const getlist = () => {
    getAll().then((res) => {
        Object.assign(list1, res)
        if (res.length > 0 && !formData.org_id) {
            formData.org_id = res[0].id
            deptAll({ 'org_id': res[0].id }).then((res) => {
                if (res.length > 0) {
                    Object.assign(list2, res)
                    formData.dept_id = res[0].id
                }

            })
        }
    })
}
//获取部门
const deptrmt = (e: any) => {
    formData.dept_id = ''
    getlist1(e)

}
//获取所有部门
const getlist1 = (id: any) => {
    deptAll({ 'org_id': id }).then((res) => {
        list2.splice(0, list2.length, ...res)
    })
}

//监听输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        invoice_amount_daxie.value = toChinesNum(e)
    }
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑日常费用报销表' : '新增日常费用报销表'
})
// 删除上传的文件
const delFileFn2 = (index: number) => {
    formDataannex2.splice(index, 1)
}

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

const handleDelete = (row: any) => {
    // 删除 row
    const index = tablist1.indexOf(row);
    tablist1.splice(index, 1);
};
const handleAdd1 = (row: any) => {
    // 在 row 后面插入一行数据
    const index = tablist2.indexOf(row);
    tablist2.splice(index + 1, 0, {});
};

const handleDelete1 = (row: any) => {
    // 删除 row
    const index = tablist2.indexOf(row);
    tablist2.splice(index, 1);
};
// 表单数据
const formData = reactive({
    id: '',
    org_id: 0,
    dept_id: 0,
    approve_id: 0,
    reimburser: '',
    reimbursement_date: "",
    customer_id: "",
    pay_type: 0,
    reimbursement_amount: 0,
    payee_name: "",
    payee_bank: "",
    payee_account: "",
    remark: "",
    annex: [],
    detail: [
        {
            cost_subject_id: 0,
            use_to: "",
            amount: 0,
            remark: ""
        }
    ],
    invoice: [
        {
            invoice_type: '',
            invoice_sn: "",
            tax_rate: "",
            invoice_form: '',
            amount: '',
            tax: "",
            annex: "",
            remark: ""
        }
    ]

})


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

})


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

        }
    }
    if (data.detail && data.detail.length > 0) {
        const arry1 = data.detail.map((item, i) => {
            if (item.subject && item.subject.subject1) {
                item.name1 = item.subject.subject1
            }
            if (item.subject && item.subject.subject2) {
                item.name2 = item.subject.subject2
            }

            return item
        })

        Object.assign(tablist1, arry1)
        console.log(arry1, '22222222')
    }
    if (data.invoice && data.invoice.length > 0) {
        Object.assign(tablist2, data.invoice)
    }

    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    customer_name.value = data.custom.name
    if (formData.reimbursement_amount) {
        toChinesNum(Number(formData.reimbursement_amount))
    }




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


// 提交按钮
const handleSubmit = async () => {
    if (formDataannex.length > 0) {
        formData.annex = formDataannex.map((item: any) => item.uri)
    }
    if (tablist1.length > 0) {
        const arr1 = tablist1.map(({ name1, name2, ...rest }) => rest)
        Object.assign(formData.detail, arr1)
    }
    if (tablist2.length > 0) {



        Object.assign(formData.invoice, tablist2)
    }




    console.log(formRef.value?.validate(), '22222222')
    await formRef.value?.validate()


    const data = { ...formData }
    mode.value == 'edit'
        ? await expensereimbursementEdit(data)
        : await expensereimbursementAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()

    getlist()
}

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

formData.reimburser = userInfo.name

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