<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.purDesc" :autosize="{ minRows: 2, maxRows: 3 }"/>
                        </el-form-item>
                        <div class="hc-form-item">
                            <!--prop="purType"-->
                            <el-form-item label="采购类型：">
                                <el-select block v-model="detailsData.purType">
                                    <el-option v-for="item in purTypeData" :label="item.dictName" :value="item.dictValue"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="使用单位：" prop="useOrgName">
                                <el-input v-model="detailsData.useOrgName" placeholder="部门使用或者项目使用"/>
                            </el-form-item>
                            <el-form-item label="期望交付日期：" prop="expectedDeliveryDate">
                                <el-date-picker type="date" class="block" v-model="detailsData.expectedDeliveryDate" 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">
                                <el-form-item label="名称：" prop="purName">
                                    <el-input v-model="item.purName"/>
                                </el-form-item>
                                <div class="hc-form-item">
                                    <el-form-item label="规格：" prop="purSpecification">
                                        <el-input v-model="item.purSpecification"/>
                                    </el-form-item>
                                    <el-form-item label="数量：" prop="purCount">
                                        <el-input v-model="item.purCount"/>
                                    </el-form-item>
                                    <el-form-item label="单位：" prop="purOrgName">
                                        <el-input v-model="item.purOrgName"/>
                                    </el-form-item>
                                    <el-form-item label="价格：" prop="purPrice">
                                        <el-input v-model="item.purPrice">
                                            <template slot="append">元</template>
                                        </el-input>
                                    </el-form-item>
                                </div>
                            </el-form>
                        </HcCardItem>
                    </template>

                    <div class="record-form-action-box mt-16">
                        <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-10" :model="detailsData" label-position="top">
                            <el-form-item label="备注：">
                                <el-input type="textarea" v-model="detailsData.remarks" :autosize="{ minRows: 3, maxRows: 5 }"/>
                            </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>
    </HcCard>
</template>

<script setup>
import {onActivated, ref} from "vue";
import {useRoute, useRouter} from 'vue-router'
import {getDictInfo} from "~api/other";
import mainApi from "~api/expense/purchaseRequest";
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 = () => {
    //下拉框相关数据
    getPurType()
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

//采购类型字典
const purTypeData = ref([])
const getPurType = async () => {
    const {error, code, data} = await getDictInfo('purchase_type')
    //判断状态
    if (!error && code === 200) {
        purTypeData.value = getArrValue(data)
    } else {
        purTypeData.value = []
    }
}


//基础详情
const detailsObj = {
    purDesc: '',                // 申请事由
    purType: null,              // 采购类型
    useOrgName: '',             // 使用单位或部门
    remarks: '',                // 备注
    expectedDeliveryDate: null, // 期望交付日期
    cashierUser: {},            // 出纳人
    ccUserList: {},             // 抄送人列表
    finalConfirmationUser: {},  // 最终确认付款人
    financeUser: {},            // 财务人员
    responsibleUser: {},        // 部门负责人
    //details: [detailsObj1],
}

//明细
const detailsObj1 = {
    purName: '',            // 采购名称
    purSpecification: '',   // 采购规格
    purCount: '',           // 采购数量
    purOrgName: '',         // 采购数量单位
    purPrice: '',           // 采购价格
}

//基础详情表单
const formRef = ref(null)
const formRules = {
    purDesc: [{required: true, message: '请输入申请事由', trigger: 'blur'}],
    purType: [{required: true, message: '请选择采购类型', trigger: 'change'}],
    useOrgName: [{required: true, message: '请输入使用单位', trigger: 'blur'}],
    expectedDeliveryDate: [{required: true, message: '请选择期望交付日期', trigger: 'change'}],
}

//明细表单
const formItemRules = {
    purName: [{required: true, message: '请输入名称', trigger: 'blur'}],
    purSpecification: [{required: true, message: '请输入规格', trigger: 'blur'}],
    purCount: [{required: true, message: '请输入数量', trigger: 'blur'}],
    purOrgName: [{required: true, message: '请输入单位', trigger: 'blur'}],
    purPrice: [{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?.purPrice)
        })
        newDetails.details = newDetailsArr
        totalFrMoney.value = frMoney
        detailsData.value = newDetails
    } else {
        totalFrMoney.value = '0'
        detailsData.value = {
            ...detailsObj,
            details: [detailsObj1]
        }
    }
}

//流程数据
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>
