<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>
                    <el-form ref="formRef" :model="detailsData" :rules="formRules" label-position="top" size="large">
                        <el-form-item label="用车事由：">
                            <el-input type="textarea" v-model="detailsData.ucDesc" :autosize="{ minRows: 2, maxRows: 3 }"/>
                        </el-form-item>
                        <div class="hc-form-item">
                            <el-form-item label="始发地点：">
                                <el-input v-model="detailsData.startLocations"/>
                            </el-form-item>
                            <el-form-item label="返回地点：">
                                <el-input v-model="detailsData.endLocations"/>
                            </el-form-item>
                        </div>
                        <div class="hc-form-item">
                            <el-form-item label="用车日期：" prop="useStartDate">
                                <el-date-picker type="date" class="block" v-model="detailsData.useStartDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                            </el-form-item>
                            <el-form-item label="返回日期：" prop="useEndDate">
                                <el-date-picker type="date" class="block" v-model="detailsData.useEndDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                            </el-form-item>
                        </div>
                    </el-form>
                    <template v-for="(item, index) in detailsData.details">
                        <HcCardItem :title="'车辆明细' + (index + 1)" ui="hac-bg-grey" class="mt-6">
                            <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="formItemRules" label-position="top" size="large">
                                <div class="hc-form-item">
                                    <el-form-item label="车辆类型：" prop="carType">
                                        <el-input v-model="item.carType"/>
                                    </el-form-item>
                                    <el-form-item label="数量：" prop="carCount">
                                        <el-input v-model="item.carCount">
                                            <template slot="append">辆</template>
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item label="其它要求：">
                                        <el-input v-model="item.otherRequirements"/>
                                    </el-form-item>
                                </div>
                            </el-form>
                        </HcCardItem>
                    </template>
                    <div class="text-gray text-sm mt-6">如需多种车型，请点击增加车辆</div>
                    <div class="record-form-action-box mt-8">
                        <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 :model="detailsData" label-position="top" size="large">
                            <el-form-item label="备注：">
                                <el-input type="textarea" v-model="detailsData.remarks" :autosize="{ minRows: 3, maxRows: 5 }"/>
                            </el-form-item>
                            <el-form-item label="图片：">
                                <HcFormUpload type="preview" :src="detailsData.photoUrl" @upload="formItemUpload" @change="formItemChange"/>
                            </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" @item="HcUploadFileItem" @success="HcUploadFileSuccess"/>

    </HcCard>
</template>

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

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

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

onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    getApi()
})

const getApi = () => {
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

//基础详情
const detailsObj = {
    ucDesc: '',                 // 用车事由
    startLocations: '',         // 始发地点
    endLocations: '',           // 返回地点
    useStartDate: null,         // 用车日期
    useEndDate: null,           // 返回日期
    remarks: '',                // 备注
    photoUrl: '',               // 图片
    cashierUser: {},            // 出纳人
    ccUserList: {},             // 抄送人列表
    finalConfirmationUser: {},  // 最终确认付款人
    financeUser: {},            // 财务人员
    responsibleUser: {},        // 部门负责人
    //details: [detailsObj1],
}

//明细
const detailsObj1 = {
    carType: '',            // 车辆类型
    carCount: '',           // 车辆数量
    otherRequirements: '',  // 其它要求
}

//基础详情表单
const formRef = ref(null)
const formRules = {
    useStartDate: [{required: true, message: '请选择用车日期', trigger: 'change'}],
    useEndDate: [{required: true, message: '请选择返回日期', trigger: 'change'}]
}

//明细表单
const formItemRules = {
    carType: [{required: true, message: '请输入车辆类型', trigger: 'blur'}],
    carCount: [{required: true, message: '请输入车辆数量', trigger: 'blur'}]
}
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 addDetailsData = () => {
    detailsData.value?.details.push({})
}

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

//获取详情数据
const totalFrMoney = ref('')
const detailsData = ref({})
const getDetailsData = async () => {
    const {error, code, data} = await mainApi.detail({
        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?.carCount)
        })
        newDetails.details = newDetailsArr
        totalFrMoney.value = frMoney
        detailsData.value = newDetails
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

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

//图片上传
const formItemUpload = () => {
    HcUploadFileRef.value?.selectFile();
}

//文件数据改变
const formItemChange = (src) => {
    detailsData.value.photoUrl = src
}

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

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

//设置上传后的数据
const setUploadFileData = (resData) => {
    const {photoUrl} = detailsData.value, {link} = resData
    let url = photoUrl
    if (url) {
        url += `,${link}`
    } else {
        url = link
    }
    detailsData.value.photoUrl = 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 () => {
    const res = await formValidate(formRef.value)
    if (!res) return false;
    //处理明细表单效验
    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>
