<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">请款总额(元)：{{formModel.afMoney}}</div>
        </template>
        <div class="hac-expense-record-body">
            <div class="record-form-box">
                <el-scrollbar>
                    <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" size="large">
                        <el-form-item label="申请时间：" prop="afDate">
                            <el-date-picker type="date" class="block" v-model="formModel.afDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                        </el-form-item>
                        <div class="hc-form-item">
                            <el-form-item label="申请人：" prop="afUserId">
                                <el-select block v-model="formModel.afUserId">
                                    <el-option label="暂无接口1" value="1" />
                                    <el-option label="暂无接口2" value="2" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否为项目提成申请：" prop="isProjectBonus">
                                <el-select block v-model="formModel.isProjectBonus">
                                    <el-option label="否" :value="0"/>
                                    <el-option label="是" :value="1"/>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="hc-form-item" v-if="formModel.isProjectBonus === 1">
                            <el-form-item label="关联项目：" prop="projectId">
                                <el-select block v-model="formModel.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" style="margin-top: 34px;" @click="budgetModalShow">
                                    <HcIcon name="add"/>
                                    <span>关联合同数据</span>
                                </el-button>
                            </div>
                        </div>
                        <el-form-item label="回款时间：" prop="collectionDate" v-if="formModel.isProjectBonus === 1">
                            <el-input v-model="formModel.collectionDate" disabled/>
                        </el-form-item>
                        <el-form-item label="回款金额：" prop="collectionMoney" v-if="formModel.isProjectBonus === 1">
                            <el-input v-model="formModel.collectionMoney" disabled>
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="申请比例：" prop="afProportion" v-if="formModel.isProjectBonus === 1">
                            <el-input v-model="formModel.afProportion">
                                <template #append>%</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="请款金额：" prop="afMoney">
                            <el-input v-model="formModel.afMoney" :disabled="formModel.isProjectBonus === 1">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="收款人：" prop="payeeUserName">
                            <el-input v-model="formModel.payeeUserName"/>
                        </el-form-item>
                        <el-form-item label="收款人开户行：" prop="payeeUserBankName">
                            <el-input v-model="formModel.payeeUserBankName"/>
                        </el-form-item>
                        <el-form-item label="收款账号：" prop="payeeUserBankId">
                            <el-input v-model="formModel.payeeUserBankId"/>
                        </el-form-item>
                        <el-form-item label="请款用途：" prop="payeeUseInfo" v-if="formModel.isProjectBonus !== 1">
                            <el-input type="textarea" v-model="formModel.payeeUseInfo" :autosize="{ minRows: 3, maxRows: 5 }"/>
                        </el-form-item>
                        <el-form-item label="关联项目：" v-if="formModel.isProjectBonus !== 1">
                            <el-select block v-model="formModel.projectId">
                                <el-option v-for="items in projectData" :label="items.projectName" :value="items.projectId"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注：">
                            <el-input type="textarea" v-model="formModel.remarks" :autosize="{ minRows: 3, maxRows: 5 }"/>
                        </el-form-item>
                    </el-form>
                </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" hc-btn :loading="tempLoading" @click="tempDraftData">
                        <HcIcon name="draft"/>
                        <span>暂存草稿</span>
                    </el-button>
                    <el-button type="primary" hc-btn :loading="submitLoading" @click="submitFormData">
                        <HcIcon name="check-double"/>
                        <span>提交申请</span>
                    </el-button>
                </div>
            </div>
        </div>

        <!--关联合同回款数据-->
        <HcDialog bgColor="#ffffff" isToBody isTable title="关联合同回款数据" widths="80%" saveText="保存"
                  :show="relatedModal" @close="relatedCloseClick" @save="relatedSaveClick"
        >
            <HcTable :column="tableRelatedColumn" :datas="tableRelatedData" :loading="tableRelatedLoading">
                <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 {ref, onActivated} from "vue";
import {useRouter, useRoute} from 'vue-router'
import {getProjectList} from "~api/other";
import mainApi from "~api/expense/paymentRequest";
import {formValidate, getArrValue, getObjValue} from "js-fast-way";

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

//路由参数
const dataId = ref(useRoutes?.query?.id ?? '')

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

//请求接口
const getApi = () => {
    //下拉框相关数据
    getProjectData()
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        formModel.value = {}
    }
}

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

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    afDate: [{required: true, message: '请选择申请时间', trigger: 'change'}],
    afUserId: [{required: true, message: '请选择申请人', trigger: 'change'}],
    isProjectBonus: [{required: true, message: '请选择是否为项目提成申请', trigger: 'change'}],
    projectId: [{required: true, message: '请选择关联项目', trigger: 'change'}],
    collectionDate: [{required: true, message: '请选择回款时间', trigger: 'change'}],
    collectionMoney: [{required: true, message: '请选择回款金额', trigger: 'change'}],
    afProportion: [{required: true, message: '请输入申请比例', trigger: 'blur'}],
    afMoney: [{required: true, message: '请输入请款金额', trigger: 'blur'}],
    payeeUserName: [{required: true, message: '请输入收款人', trigger: 'blur'}],
    payeeUserBankName: [{required: true, message: '请输入收款人开户行', trigger: 'blur'}],
    payeeUserBankId: [{required: true, message: '请输入收款账号', trigger: 'blur'}],
    payeeUseInfo: [{required: true, message: '请输入请款用途', trigger: 'blur'}],
}

//草稿数据详情
const getDetailsData = async () => {
    const {error, code, data} = await mainApi.detail({
        id: dataId.value
    })
    //判断状态
    if (!error && code === 200) {
        formModel.value = getObjValue(data)
    } else {
        formModel.value = {}
    }
}

//关联预算计划
const relatedModal = ref(false)
const relatedIds = ref([])
const budgetModalShow = () => {
    const {projectId, contractCollectionDataId} = formModel.value
    relatedModal.value = true
    relatedIds.value = contractCollectionDataId?.split(',') || []
    getBudgetTableData(projectId)
}

//关联预算计划表格
const tableRelatedLoading = ref(false)
const tableRelatedColumn = [
    {key: 'returnedCondition', name: '回款条件'},
    {key: 'shouldReturnedTime', name: '应收回款时间',  width: '180', align: 'center'},
    {key: 'shouldReturnedMoney', name: '应收回款金额(元)',  width: '140', align: 'center'},
    {key: 'practicalReturnedTime', name: '实际回款时间', width: '180', align: 'center'},
    {key: 'practicalReturnedMoney', name: '实际回款金额(元)', width: '140', align: 'center'},
    {key: 'reminderUserName', name: '催款执行人', width: '100', align: 'center'},
    {key: 'action', name: '操作', width: '100', align: 'center'},
]
const tableRelatedData = ref([])
const getBudgetTableData = async (projectId) => {
    tableRelatedLoading.value = true
    const {error, code, data} = await mainApi.contractList({
        projectId: projectId
    })
    //判断状态
    tableRelatedLoading.value = false
    if (!error && code === 200) {
        tableRelatedData.value = await isRowRelevance(data)
    } else {
        tableRelatedData.value = []
    }
}

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

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

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


//确认关联数据
const relatedSaveClick = () => {
    const ids = relatedIds.value?.join(',')
    console.log('ids', ids)
}

//关闭关联数据
const relatedCloseClick = () => {
    relatedModal.value = false
}


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


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

//提交报销申请
const submitLoading = ref(false)
const submitFormData = async () => {
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        //发起请求
        const {error, code, msg} = await mainApi.submit({
            ...formModel.value,
            submitStatus: 2
        })
        //判断状态
        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";
</style>

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