<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">借款总额(元)：{{formModel.loanMoney ?? 0}}</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="loanUserName">
                            <el-input v-model="formModel.loanUserName"/>
                        </el-form-item>
                        <el-form-item label="借款事由：">
                            <el-input type="textarea" v-model="formModel.loanDesc" :autosize="{ minRows: 3, maxRows: 5 }"/>
                        </el-form-item>
                        <el-form-item prop="loanMoney">
                            <template #label>
                                <span>申请金额：</span>
                                <span style="color: #8f8d8d;">{{formModel.loanMoneyText}}</span>
                            </template>
                            <el-input v-model="formModel.loanMoney" @change="loanMoneyChange">
                                <template #append>元</template>
                            </el-input>
                        </el-form-item>
                        <div class="hc-form-item">
                            <el-form-item label="使用日期：" prop="useDate">
                                <el-date-picker type="date" class="block" v-model="formModel.useDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                            </el-form-item>
                            <el-form-item label="归还日期：" prop="returnDate">
                                <el-date-picker type="date" class="block" v-model="formModel.returnDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                            </el-form-item>
                        </div>
                        <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>
    </HcCard>
</template>

<script setup>
import {ref, onActivated} from "vue";
import {useRouter, useRoute} from 'vue-router'
import mainApi from "~api/expense/loanRequest";
import {getNumberToChinese,getApprovesList} from "~api/other";
import {deepClone, formValidate, 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 = () => {
    //清空流程数据
    timeData.value=[]
    timeLineData.value=[]
    getApprovesListData()
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        formModel.value = {}
    }
}

//明细表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    loanUserName: [{required: true, message: '请输入申请人', trigger: 'blur'}],
    loanMoney: [{required: true, message: '请输入申请金额', trigger: 'blur'}],
    useDate: [{required: true, message: '请选择使用日期', trigger: 'change'}],
    returnDate: [{required: true, message: '请选择归还日期', trigger: 'change'}],
}

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

//当输入框失去焦点或用户按Enter时触发
const loanMoneyChange = (val) => {
    getNumberToChineseApi(val)
}

//将数字转换为汉语大写，支持小数点
const getNumberToChineseApi = async (loanMoney) => {
    const {error, code, data} = await getNumberToChinese(loanMoney)
    if (!error && code === 200) {
        formModel.value.loanMoneyText = data
    } else {
        formModel.value.loanMoneyText = ''
    }
}

const timeData=ref({})
//流程数据
const timeLineData = ref([
    // {title: '审批人', section: '部门负责人'},
    // {title: '财务审核', section: '财务'},
    // {title: '最终确认付款人', section: '总经理'},
    // {title: '出纳付款', section: '出纳'},
    // {title: '抄送人', section: '总经理、财务、申请人'},
])
const getApprovesListData=async()=>{
    const {error, code, data} = await getApprovesList()
    if (!error && code === 200) {
     console.log(data,'data');
     timeData.value=data['借款申请流程']
     console.log( timeData.value,' timeData.value');
     for(var i in timeData.value) {
        timeLineData.value.push({
            title:i,
            section:timeData.value[i].join(',')
        })
     }
    } else {
        timeLineData.value=[]

    }
}
//处理表单数据
const getFormData = (submitStatus = 1) => {
    const res = deepClone(formModel.value)
    const cashierUser = {userId: ''}            //出纳人
    const ccUserList = [{userId: ''}]           //抄送人列表
    const finalConfirmationUser = {userId: ''}  //最终确认付款人
    const financeUser = {userId: ''}            //财务人员
    const responsibleUser = {userId: ''}        //部门负责人
    //----处理数据----
    return {
        ...res,
        // cashierUser,
        // ccUserList,
        // finalConfirmationUser,
        // financeUser,
        // responsibleUser,
        submitStatus //提交状态 1=暂存 2=提交审批
    }
}


//暂存数据
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 () => {
    const res = await formValidate(formRef.value)
    if (res) {
        submitLoading.value = true
        //发起请求
        const form = getFormData(2)
        const {error, code, msg} = await mainApi.submit(form)
        //判断状态
        submitLoading.value = false
        if (!error && code === 200) {
            window.$message?.success('提交成功')
            router.push({name: 'expense-loanRequest'})
        } 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>
