<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">开票金额(元)：{{formModel.invoiceMoney ?? 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="left" label-width="auto" size="large">
                        <el-form-item label="申请时间：" prop="invoiceDate">
                            <el-date-picker type="date" class="block" v-model="formModel.invoiceDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
                        </el-form-item>
                        <el-form-item label="开票事由：" prop="invoiceDesc">
                            <el-input type="textarea" v-model="formModel.invoiceDesc" :autosize="{ minRows: 3, maxRows: 5 }"/>
                        </el-form-item>
                        <el-form-item label="开票人：" prop="invoiceUserId">
                            <el-select block v-model="formModel.invoiceUserId">
                                 <el-option v-for="item in userList" :label="item.name" :value="item.id"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="发票类型：" prop="invoiceType">
                            <el-select block v-model="formModel.invoiceType">
                                <el-option v-for="item in invoiceTypeData" :label="item.dictName" :value="item.dictValue"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="关联项目：" prop="projectId">
                            <el-select block v-model="formModel.projectId">
                                <el-option v-for="item in projectType" :label="item.projectName" :value="item.projectId"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="开票金额：" prop="invoiceMoney">
                            <!-- <el-input v-model="formModel.invoiceMoney" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)">
                                <template #append>元</template>
                            </el-input> -->
                            <div class="flex"  style="width: 100%;">
                                <el-input-number v-model="formModel.invoiceMoney" :precision="2" :step="0.1" style="width: 100%;">
                                </el-input-number>
                                <span>元</span>
                          </div>
                        </el-form-item>
                        <el-form-item label="开票内容：" prop="invoiceContentType">
                            <el-select block v-model="formModel.invoiceContentType">
                                <el-option v-for="item in invoiceContentList" :label="item" :value="item"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="发票抬头：">
                            <el-input v-model="formModel.invoiceHead" disabled/>
                        </el-form-item>
                        <el-form-item label="纳税人识别号：">
                            <el-input v-model="formModel.key2" disabled/>
                        </el-form-item>
                        <el-form-item label="开户银行：">
                            <el-input v-model="formModel.key2" disabled/>
                        </el-form-item>
                        <el-form-item label="银行账户：">
                            <el-input v-model="formModel.key2" disabled/>
                        </el-form-item>
                        <el-form-item label="收件人：">
                            <el-input v-model="formModel.key2" disabled/>
                        </el-form-item>
                        <el-form-item label="联系电话：">
                            <el-input v-model="formModel.key2" disabled/>
                        </el-form-item>
                        <el-form-item label="邮寄地址：">
                            <el-input v-model="formModel.key2" disabled/>
                        </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 {onActivated, ref} from "vue";
import {useRoute, useRouter} from 'vue-router'
import mainApi from "~api/expense/invoice";
import {getProjectList, getDictInfo,getuserList,getApprovesList} from "~api/other";
import {deepClone, formValidate, getArrValue, getObjValue} from "js-fast-way";
import {useAppStore} from "~src/store";
const useAppState = useAppStore();

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

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

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

const getApi = () => {
    getInvoiceType()
    getProjectData()
    getUserDict()
    getInvoiceContentList()
    getApprovesListData()
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        formModel.value = {}
    }
}

//发票类型字典
const invoiceTypeData = ref([])
const getInvoiceType = async () => {
    const {error, code, data} = await getDictInfo('invoice_type')
    //判断状态
    if (!error && code === 200) {
        invoiceTypeData.value = getArrValue(data)
    } else {
        invoiceTypeData.value = []
    }
}

//项目类型
const projectType = ref([])
const getProjectData = async () => {
    const {error, code, data} = await getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectType.value = getArrValue(data)
    } else {
        projectType.value = []
    }
}
//获取所有员工
const userList=ref([])
const getUserDict=async()=>{
    const {error, code, data} = await getuserList({tenantId:useAppState.tenantId})
    if (!error && code === 200) {
        userList.value = getArrValue(data)

    } else {
        userList.value = []

    }
}
//获取开票内容
const invoiceContentList=ref([])
const getInvoiceContentList=async()=>{
    const {error, code, data} = await mainApi.getInvoiceContentList()
    if (!error && code === 200) {
        invoiceContentList.value = getArrValue(data)

    } else {
        invoiceContentList.value = []

    }
}
//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    invoiceDate: [{required: true, message: '请选择申请时间', trigger: 'change'}],
    invoiceDesc: [{required: true, message: '请输入开票事由', trigger: 'blur'}],
    invoiceUserId: [{required: true, message: '请选择开票人', trigger: 'change'}],
    invoiceType: [{required: true, message: '请选择发票类型', trigger: 'change'}],
    projectId: [{required: true, message: '请选择关联项目', trigger: 'change'}],
    invoiceMoney: [{required: true, message: '请输入开票金额', trigger: 'blur'}],
    invoiceContentType: [{required: true, message: '请选择开票内容', trigger: 'change'}],
}

//草稿数据详情
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 timeLineData = ref([
    {title: '审批人', section: '部门负责人'},
    {title: '财务审批', section: '财务'},
    {title: '抄送人', section: '总经理'},
])
const timeData=ref([])
const getApprovesListData=async()=>{
    const {error, code, data} = await getApprovesList()
    if (!error && code === 200) {
     timeData.value=data['发票管理流程']
     let approveArr=timeData.value['审批人']
     let copyArr=timeData.value['抄送人']
     timeLineData.value.forEach((ele,index)=>{
        if(ele.title!=='抄送人'){
            ele.section=approveArr[index]
        }else{
            ele.section=copyArr.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-invoice'})
        } 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>
