<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">报销总额(元)：{{totalFrMoney}}</div>
        </template>
        <div class="hac-expense-record-body">
            <div class="record-form-box">
                <el-scrollbar>
                    <HcCardItem :title="'报销明细' + (index + 1)" v-for="(item, index) in detailsData.details" ui="hac-bg-grey mb-5">
                        <template #extra>
                            <el-button type="danger" size="small" @click="delDetailsData(index)" v-if="index > 0">
                                <HcIcon name="delete-bin"/>
                                <span>删除明细</span>
                            </el-button>
                        </template>
                        <el-form :ref="(el) => setFormItemRefs(el, index)" :model="item" :rules="formRules" label-position="left" label-width="auto" size="large">
                            <div class="hc-form-item">
                                <el-form-item label="所属项目：" prop="projectId">
                                    <el-select block v-model="item.projectId">
                                        <el-option v-for="items in projectData" :label="items.projectName" :value="items.projectId"/>
                                    </el-select>
                                </el-form-item>
                                <div class="ml-2">
                                    <el-button type="default" @click="budgetModalShow(item,index)">
                                        <HcIcon name="add"/>
                                        <span>关联预算计划</span>
                                    </el-button>
                                </div>
                            </div>
                            <div class="hc-form-item">
                                <el-form-item label="报销金额(元)：" prop="frMoney">
                                    <el-input v-model="item.frMoney" placeholder="请输入报销金额" />
                                </el-form-item>
                                <el-form-item label="费用发生日期：" prop="frDate">
                                    <el-date-picker type="date" class="block" v-model="item.frDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                                </el-form-item>
                                <el-form-item label="费用类型：" prop="frType">
                                    <el-select block v-model="item.frType">
                                        <el-option v-for="items in frTypeData" :label="items.dictName" :value="items.dictValue"/>
                                    </el-select>
                                </el-form-item>
                            </div>
                            <el-form-item label="费用说明：">
                                <el-input type="textarea"
                                          v-model="item.frDesc"
                                          :autosize="{ minRows: 3, maxRows: 5 }"
                                          placeholder="请输入费用说明"
                                />
                            </el-form-item>
                            <el-form-item label="电子发票：">
                                <HcFormUpload :src="item.frElectronicInvoiceUrl"
                                              @upload="invoiceItemUpload(index)"
                                              @change="invoiceItemChange($event, index)"
                                />
                            </el-form-item>
                            <el-form-item label="附件文件：">
                                <HcFormUpload :src="item.frAttachmentUrl"
                                              @upload="fileItemUpload(index)"
                                              @change="fileItemChange($event, index)"
                                />
                            </el-form-item>
                        </el-form>
                    </HcCardItem>
                    <div class="record-form-action-box mt-11">
                        <el-divider content-position="right" border-style="dashed">
                            <el-button type="primary" hc-btn @click="addDetailsData">
                                <HcIcon name="add"/>
                                <span>添加明细</span>
                            </el-button>
                        </el-divider>
                        <el-form class="mt-16" inline :model="detailsData" label-position="top">
                            <el-form-item label="归属人">
                                <el-select v-model="detailsData.userIdVesting">
                                    <el-option label="暂无接口1" value="1" />
                                    <el-option label="暂无接口2" value="2" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否抵消借款金额">
                                <el-select v-model="detailsData.isDeductLoan">
                                    <el-option label="否" :value="0" />
                                    <el-option label="是" :value="1" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="选择借款项">
                                <el-select v-model="detailsData.deductLoanId">
                                    <el-option v-for="item in loanListData" :label="item.loanName" :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="冲抵后的实际报销金额">
                                <el-input v-model="detailsData.frMoneyActual" disabled>
                                    <template #append>元</template>
                                </el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-scrollbar>
            </div>
            <div class="record-flow-box">
                <div class="title">流程</div>
                <div class="content">
                    <el-scrollbar>
                        <el-timeline>
                            <el-timeline-item v-for="(item, index) in timeLineData" :key="index">
                                <div class="timeline-title">{{item.title}}</div>
                                <div class="timeline-section">{{item.section}}</div>
                            </el-timeline-item>
                        </el-timeline>
                    </el-scrollbar>
                </div>
                <div class="action">
                    <el-button type="warning" :loading="tempLoading" hc-btn @click="tempDraftData">
                        <HcIcon name="draft"/>
                        <span>暂存草稿</span>
                    </el-button>
                    <el-button type="primary" :loading="submitLoading" hc-btn @click="submitFormData">
                        <HcIcon name="check-double"/>
                        <span>提交报销申请</span>
                    </el-button>
                </div>
            </div>
        </div>

        <!--上传控件-->
        <HcUploadFile ref="HcUploadFileRef"
                      :options="uploadFileOptions"
                      :echoParams="uploadEchoParams"
                      @item="HcUploadFileItem"
                      @success="HcUploadFileSuccess"
        />

        <!--关联预算计划-->
        <HcDialog bgColor="#ffffff" isToBody isTable
                  title="关联预算计划" widths="80%" saveText="保存"
                  :show="budgetModal"
                  @close="budgetCloseClick"
                  @save="budgetSaveClick"
        >
            <HcTable :column="tableBudgetColumn" :datas="tableBudgetData" :loading="tableBudgetLoading">
                <template #action="{row,index}">
                    <el-button size="small" type="danger" @click="rowDisassociate(row)" v-if="row.isRelevance">取消关联</el-button>
                    <el-button size="small" type="primary" @click="rowRelevance(row)" v-else>关联</el-button>
                </template>
            </HcTable>
        </HcDialog>

    </HcCard>
</template>

<script setup>
import {onActivated, ref} from "vue";
import {useRoute, useRouter} from 'vue-router'
import mainApi from "~api/expense/finReimburse";
import {getTokenHeader} from "~src/api/request/header";
import {arrIndex, deepClone, formValidate, getArrValue, getObjValue} from "js-fast-way";
import {getProjectList, getDictInfo} from "~api/other";
import {delMessage} from "~uti/tools";

//初始变量
const router = useRouter()
const useRoutes = useRoute()

//路由参数
const dataId = ref(useRoutes?.query?.id ?? '')
const dataType = ref(useRoutes?.query?.type ?? 'add') // add:新增 view:预览 draft:草稿

//页面被激活
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    dataType.value = useRoutes?.query?.type ?? 'add'
    getApi()
})

//请求接口
const getApi = () => {
    //下拉框相关数据
    getProjectData()
    expenseFrType()
    getLoanListData()
    //获取数据详情
    if (dataId.value > 0 && dataType.value !== 'add') {
        getDetailsData()
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

//获取项目数据
const projectData = ref([])
const getProjectData = async () => {
    const {error, code, data} = await getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectData.value = getArrValue(data)
    } else {
        projectData.value = []
    }
}

//费用类型字典
const frTypeData = ref([])
const expenseFrType = async () => {
    const {error, code, data} = await getDictInfo('expense_fr_type')
    //判断状态
    if (!error && code === 200) {
        frTypeData.value = getArrValue(data)
    } else {
        frTypeData.value = []
    }
}

//获取我的借款列表
const loanListData = ref([])
const getLoanListData = async () => {
    const {error, code, data} = await mainApi.loanList()
    //判断状态
    if (!error && code === 200) {
        loanListData.value = getArrValue(data)
    } else {
        loanListData.value = []
    }
}


//基础详情
const detailsObj = {
    frMoney: 0,             // 报销金额
    frMoneyActual: 0,       // 实际报销金额
    userIdVesting: null,    // 归属人id
    isDeductLoan: 0,        // 是否抵扣借款 0=否 1=是
    deductLoanId: null,     // 借款信息id
    status: null,           // 审批状态 0=未上报 1=待审批 2=已审批 3=已驳回
    //details: [detailsObj1],
}
//明细
const detailsObj1 = {
    projectId: null,    // 所属项目id
    budgetPlanIds: '',  // 预算计划ids
    frMoney: 0,         // 报销金额
    frDate: null,       // 报销时间
    frDesc: '',         // 费用说明
    frType: null,       // 报销类型
    frElectronicInvoiceUrl: '', // 电子发票url地址
    frAttachmentUrl: '',    // 附件url地址
}

//添加明细
const addDetailsData = () => {
    detailsData.value?.details.push({})
}

//删除明细
const delDetailsData = (index) => {
    delMessage(() => {
        detailsData.value?.details.splice(index, 1)
    })
}

//获取详情数据
const totalFrMoney = ref('')
const detailsData = ref({})
const getDetailsData = async () => {
    if (dataType.value === 'view') {
        //预览详情
        let newDetails = {}, newDetails1 = {}
        const {error, code, data, msg} = await mainApi.detail({
            id: dataId.value
        })
        //判断状态
        if (!error && code === 200) {
            const res = getObjValue(data)
            //基础数据
            Object.keys(detailsObj).forEach(key => {
                newDetails[key] = res[key]
            })
            //明细数据
            Object.keys(detailsObj1).forEach(key => {
                newDetails1[key] = res[key]
            })
            newDetails1.id = res?.id
            totalFrMoney.value = res?.frMoney
            newDetails.details = [newDetails1]
        } else {
            newDetails = detailsObj
            newDetails.details = [detailsObj1]
            totalFrMoney.value = '0'
            window.$message?.error(msg)
        }
        detailsData.value = newDetails
    } else if (dataType.value === 'draft') {
        //草稿详情
        const {error, code, data} = await mainApi.draftDetail({
            eMDraftIds: dataId.value
        })
        //判断状态
        const res = getArrValue(data)
        if (!error && code === 200 && res.length > 0) {
            let newDetails = {}, newDetailsArr = [], frMoney = 0
            res.forEach((item, index) => {
                //基础数据
                if (index === 0) {
                    Object.keys(detailsObj).forEach(key => {
                        newDetails[key] = item[key]
                    })
                }
                //明细数据
                let newDetails1 = {}
                Object.keys(detailsObj1).forEach(key => {
                    newDetails1[key] = item[key]
                })
                newDetails1.id = item?.id
                newDetailsArr.push(newDetails1)
                frMoney = Number(frMoney) + Number(item?.frMoney)
            })
            newDetails.details = newDetailsArr
            totalFrMoney.value = frMoney
            detailsData.value = newDetails
        } else {
            totalFrMoney.value = '0'
            detailsData.value = {
                ...detailsObj,
                details: [detailsObj1]
            }
        }
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

//明细表单
const formRefs = ref([])
const setFormItemRefs = (el, index) => {
    if (el) {
        let indexs = arrIndex(formRefs.value, 'index', index)
        if (indexs !== -1) {
            formRefs.value[index].ref = el
        } else {
            formRefs.value.push({
                index: index,
                ref: el
            });
        }
    }
}

//获取表单的ref
const getFormRef = async (index) => {
    const indexs = arrIndex(formRefs.value, 'index', index)
    return formRefs.value[indexs].ref
}

const formRules = {
    projectId: [{required: true, message: '请选择所属项目', trigger: 'change'}],
    frMoney: [{required: true, message: '请输入报销金额', trigger: 'blur'}],
    frDate: [{required: true, message: '请选择费用发生日期', trigger: 'change'}],
    frType: [{required: true, message: '请选择费用类型', trigger: 'change'}],
}

//关联预算计划
const budgetModal = ref(false)
const budgetIds = ref([])
const budgetIndex = ref([])
const budgetModalShow = (item, index) => {
    budgetModal.value = true
    budgetIndex.value = index
    budgetIds.value = item.budgetPlanIds?.split(',') || []
    getBudgetTableData(item.projectId)
}

//关联预算计划表格
const tableBudgetLoading = ref(false)
const tableBudgetColumn = [
    {key: 'projectName', name: '任务所属项目'},
    {key: 'status', name: '状态',  width: '120', align: 'center'},
    {key: 'planTaskDesc', name: '任务描述'},
    {key: 'planTarget', name: '完成指标', width: '120', align: 'center'},
    {key: 'action', name: '操作', width: '100', align: 'center'},
]
const tableBudgetData = ref([])
const getBudgetTableData = async (projectId) => {
    tableBudgetLoading.value = true
    const {error, code, data} = await mainApi.budget({projectId})
    //判断状态
    tableBudgetLoading.value = false
    if (!error && code === 200) {
        tableBudgetData.value = await isRowRelevance(data)
    } else {
        tableBudgetData.value = []
    }
}

//判断是否关联
const isRowRelevance = async (data) => {
    const res = getArrValue(data)
    const ids = budgetIds.value
    res.forEach(item => {
        item.isRelevance = ids.includes(item.id)
    })
    return res
}

//取消关联
const rowDisassociate = (row) => {
    const ids = budgetIds.value
    const index = ids.indexOf(row.id)
    if (index > -1) {
        ids.splice(index, 1)
    }
    budgetIds.value = ids
    row.isRelevance = false
}

//关联
const rowRelevance = (row) => {
    const ids = budgetIds.value
    ids.push(row.id)
    budgetIds.value = ids
    row.isRelevance = true
}


//确认关联预算计划
const budgetSaveClick = () => {
    const index = budgetIndex.value
    const ids = budgetIds.value?.join(',')
    console.log('ids', ids)
    console.log('index', index)
}

//关闭预算计划
const budgetCloseClick = () => {
    budgetModal.value = false
}


//上传配置
const HcUploadFileRef = ref(null)
const uploadEchoParams = ref({})
const uploadFileOptions = {
    headers: getTokenHeader(),
}

//电子发票
const invoiceItemUpload = (index) => {
    uploadEchoParams.value = {
        name: 'frElectronicInvoiceUrl',
        index: index
    }
    HcUploadFileRef.value?.selectFile();
}
//文件列表改变事件
const invoiceItemChange = (src, index) => {
    const res = getObjValue(detailsData.value.details[index])
    res.frElectronicInvoiceUrl = src
}

//附件上传
const fileItemUpload = (index) => {
    uploadEchoParams.value = {
        name: 'frAttachmentUrl',
        index: index
    }
    HcUploadFileRef.value?.selectFile();
}
//文件列表改变事件
const fileItemChange = (src, index) => {
    const res = getObjValue(detailsData.value.details[index])
    res.frAttachmentUrl = src
}

//上传完成
const HcUploadFileSuccess = ({echoParams, resData}) => {
    setUploadFileData(echoParams, resData)
}

//使用某个文件
const HcUploadFileItem = ({item}) => {
    const {name, index} = uploadEchoParams.value, {pdfUrl} = item.resData
    const urls = detailsData.value.details[index][name].split(',')
    if (urls.indexOf(pdfUrl) === -1) {
        setUploadFileData(uploadEchoParams.value, item.resData)
    } else {
        window.$message?.warning('文件已存在')
    }
}

//设置上传后的数据
const setUploadFileData = (echoParams, resData) => {
    const {name, index} = echoParams, {pdfUrl} = resData
    let url = detailsData.value.details[index][name]
    if (url) {
        url += `,${pdfUrl}`
    } else {
        url = pdfUrl
    }
    detailsData.value.details[index][name] = url
}

//流程数据
const timeLineData = ref([
    {title: '审批人', section: '部门负责人'},
    {title: '财务审核', section: '财务'},
    {title: '最终确认付款人', section: '总经理'},
    {title: '出纳付款', section: '出纳'},
    {title: '抄送人', section: '总经理、财务、申请人'},
])

//处理表单数据
const getFormData = (submitStatus = 1) => {
    const res = deepClone(detailsData.value)
    const cashierUser = {userId: ''}            //出纳人
    const ccUserList = [{userId: ''}]           //抄送人列表
    const finalConfirmationUser = {userId: ''}  //最终确认付款人
    const financeUser = {userId: ''}            //财务人员
    const responsibleUser = {userId: ''}        //部门负责人
    //----处理数据----
    let newFormData = [], newDetails = {}
    //基础数据
    Object.keys(detailsObj).forEach(key => {
        newDetails[key] = res[key]
    })
    //组装为数组集合的表单数据
    const list = res?.details
    list.forEach(item => {
        newFormData.push({
            ...newDetails,
            ...item,
            cashierUser,
            ccUserList,
            finalConfirmationUser,
            financeUser,
            responsibleUser,
            submitStatus //提交状态 1=暂存 2=提交审批
        })
    })
    return newFormData
}

//暂存数据
const tempLoading = ref(false)
const tempDraftData = async () => {
    tempLoading.value = true
    const form = getFormData(1)
    const {error, code, msg} = await mainApi.submit(form)
    //判断状态
    tempLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('暂存成功')
    } else {
        window.$message?.error(msg)
    }
}

//提交报销申请
const submitLoading = ref(false)
const submitFormData = async () => {
    submitLoading.value = true
    const form = getFormData(2)
    for (let i = 0; i < form.length; i++) {
        const refs = await getFormRef(i)
        const res = await formValidate(refs)
        if (!res) {
            submitLoading.value = false
            return
        }
    }
    //发起请求
    const {error, code, msg} = await mainApi.submit(form)
    //判断状态
    submitLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('提交成功')
    } else {
        window.$message?.error(msg)
    }
}
</script>

<style scoped lang="scss">
@import "~src/styles/expense/expense.scoped.scss";
.record-form-action-box {
    position: relative;
}
</style>

<style lang="scss">
@import "~src/styles/expense/expense.scss";
</style>
