<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">
                支付总额(元)：{{ formModel.payMoney ?? 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">
                        <div class="hc-form-item">
                            <el-form-item label="关联项目：">
                                <el-select v-model="formModel.projectId" block>
                                    <el-option v-for="item in projectType" :label="item.projectName" :value="item.projectId" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="非项目请输入：">
                                <el-input v-model="formModel.noProjectDesc" />
                            </el-form-item>
                        </div>
                        <el-form-item label="对方单位：">
                            <el-input v-model="formModel.toUnit" />
                        </el-form-item>
                        <el-form-item label="支付金额：" prop="key3">
                            <!-- <el-input v-model="formModel.payMoney" type="number" precision="2" 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.payMoney" :precision="2" :step="0.1" style="width: 100%;" />
                                <span>元</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="申请支付时间：">
                            <el-date-picker v-model="formModel.payDate" type="date" class="block" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                        </el-form-item>
                        <el-form-item label="外包类型：">
                            <el-select v-model="formModel.outsourcingType" block>
                                <el-option v-for="item in outsourcingTypeData" :label="item.dictName" :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-scrollbar>
            </div>
            <div class="record-flow-box">
                <div class="title">
                    流程
                </div>
                <div class="content">
                    <el-scrollbar>
                        <el-timeline v-if="isshowOver">
                            <el-timeline-item v-for="(item, index) in timeLineData1" :key="index">
                                <div class="timeline-title">
                                    {{ item.title }}
                                </div>
                                <div class="timeline-section">
                                    {{ item.section }}
                                </div>
                            </el-timeline-item>
                        </el-timeline>
                        <el-timeline v-else>
                            <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, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import mainApi from '~api/expense/outsourcing'
import { getApprovesList, getDictInfo, getProjectList } from '~api/other'
import { deepClone, formValidate, getArrValue, getObjValue } from 'js-fast-way'

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

//路由参数
const dataId = ref(useRoutes?.query?.id ?? '')
const isshowOver = ref(true)//显示小于1000的流程
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    getApi()
})

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

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

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


//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {}
//深度监听
watch(() => [
    formModel.value.payMoney,
], ([datas]) => {
    if (datas > 1000) {
        isshowOver.value = false
    } else {
        isshowOver.value = true
    }
}, { deep: true })
//草稿数据详情
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: '总经理' },
    // { title: '出纳付款', section: '出纳' },
    // { title: '抄送人', section: '总经理、财务、申请人' },
])
//金额小于1000
const timeLineData1 = ref([
    { title: '审批人', section: '' },
    // { 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['支付申请流程']
//      console.log(timeData.value,timeData.value);
//      let approveArr=timeData.value['审批人']
//      //小于1000
//     let value = '总经理'
//     let newSet = new Set(approveArr)
//     newSet.delete(value)
//     let newArr = [...newSet]
//      let copyArr=timeData.value['抄送人']
//      timeLineData1.value.forEach((ele,index)=>{
//         if(ele.title!=='抄送人'){
//             ele.section=newArr[index]
//         }else{
//             ele.section=copyArr.join(',')
//         }
//      })
//      //大于1000
//      timeLineData.value.forEach((ele,index)=>{
//         if(ele.title!=='抄送人'){
//             ele.section=approveArr[index]
//         }else{
//             ele.section=copyArr.join(',')
//         }
//      })
//     } else {
//         timeLineData.value=[]
//     }
// }
const getApprovesListData = async ()=>{
    timeLineData.value = [ { title: '审批人', section: '' }]
    timeLineData1.value = [ { title: '审批人', section: '' }]
    const { error, code, data } = await getApprovesList()
    if (!error && code === 200) {
        timeData.value = data['支付申请流程']
        console.log(timeData.value, timeData.value)
        let approveArr = timeData.value['审批人']
            //小于1000
        let value = '总经理'
        let newSet = new Set(approveArr)
        newSet.delete(value)
        let newArr = [...newSet]
        let copyArr = timeData.value['抄送人']
        newArr.forEach((ele)=>{
            timeLineData1.value.push({ title:'', section:ele })
        })
        timeLineData1.value.push({ title:'抄送人', section:copyArr.join(',') })

        //大于1000
        approveArr.forEach((ele)=>{
            timeLineData.value.push({ title:'', section:ele })
        })
        timeLineData.value.push({ title:'抄送人', section:copyArr.join(',') })
    } else {
        timeLineData1.value = []
        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-outsourcing' })
        } 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>
