<template>
    <HcCard>
        <template #header>
            <div class="hc-expense-total-title">
                请款总额(元)：{{ formModel.afMoney }}
            </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="afDate">
                            <el-date-picker v-model="formModel.afDate" type="date" class="block" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                        </el-form-item>
                        <div class="hc-form-item">
                            <el-form-item label="申请人：" prop="afUserId">
                                <el-select v-model="formModel.afUserId" block>
                                    <el-option v-for="item in userList" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否为项目提成申请：" prop="isProjectBonus">
                                <el-select v-model="formModel.isProjectBonus" block>
                                    <el-option label="否" :value="0" />
                                    <el-option label="是" :value="1" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div v-if="formModel.isProjectBonus === 1" class="hc-form-item">
                            <el-form-item label="关联项目：" prop="projectId">
                                <el-select v-model="formModel.projectId" block>
                                    <el-option v-for="items in projectData" :label="items.projectName" :value="items.projectId" />
                                </el-select>
                            </el-form-item>
                            <div class="ml-2">
                                <el-button type="default" style="margin-top: 34px;" @click="budgetModalShow">
                                    <HcIcon name="add" />
                                    <span>关联合同数据</span>
                                </el-button>
                            </div>
                        </div>
                        <el-form-item v-if="formModel.isProjectBonus === 1" label="回款时间：" prop="collectionDate">
                            <el-input v-model="formModel.collectionDate" disabled />
                        </el-form-item>
                        <el-form-item v-if="formModel.isProjectBonus === 1" label="回款金额：" prop="collectionMoney">
                            <el-input v-model="formModel.collectionMoney" disabled>
                                <template #append>
                                    元
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item v-if="formModel.isProjectBonus === 1" label="申请比例：" prop="afProportion">
                            <el-input v-model="formModel.afProportion">
                                <template #append>
                                    %
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="请款金额：" prop="afMoney">
                            <!-- <el-input v-model="formModel.afMoney" :disabled="formModel.isProjectBonus === 1" 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.afMoney" :precision="2" :step="0.1" style="width: 100%;" />
                                <span>元</span>
                            </div>
                        </el-form-item>
                        <el-form-item label="收款人：" prop="payeeUserName">
                            <el-input v-model="formModel.payeeUserName" />
                        </el-form-item>
                        <el-form-item label="收款人开户行：" prop="payeeUserBankName">
                            <el-input v-model="formModel.payeeUserBankName" />
                        </el-form-item>
                        <el-form-item label="收款账号：" prop="payeeUserBankId">
                            <el-input v-model="formModel.payeeUserBankId" />
                        </el-form-item>
                        <el-form-item v-if="formModel.isProjectBonus !== 1" label="请款用途：" prop="payeeUseInfo">
                            <el-input v-model="formModel.payeeUseInfo" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" />
                        </el-form-item>
                        <el-form-item v-if="formModel.isProjectBonus !== 1" label="关联项目：">
                            <el-select v-model="formModel.projectId" block>
                                <el-option v-for="items in projectData" :label="items.projectName" :value="items.projectId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="备注：">
                            <el-input v-model="formModel.remarks" type="textarea" :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 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>

        <!-- 关联合同回款数据 -->
        <HcDialog
            bg-color="#ffffff" is-to-body is-table title="关联合同回款数据" widths="80%" save-text="保存"
            :show="relatedModal" @close="relatedCloseClick" @save="relatedSaveClick"
        >
            <HcTable :column="tableRelatedColumn" :datas="tableRelatedData" :loading="tableRelatedLoading">
                <template #action="{ row, index }">
                    <el-button v-if="row.isRelevance" size="small" type="danger" @click="rowDisassociate(row)">
                        取消关联
                    </el-button>
                    <el-button v-else size="small" type="primary" @click="rowRelevance(row)">
                        关联
                    </el-button>
                </template>
            </HcTable>
        </HcDialog>
    </HcCard>
</template>

<script setup>
import { onActivated, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getApprovesList, getProjectList, getuserList } from '~api/other'
import mainApi from '~api/expense/paymentRequest'
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 ?? '')
const isshowOver = ref(true)//显示小于1000的流程
//页面被激活
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    getApi()
})

//请求接口
const getApi = () => {
    //清空流程数据
  
    //下拉框相关数据
    getProjectData()
    getUserDict()
    getApprovesListData()
    //获取数据详情
    if (dataId.value > 0) {
        getDetailsData()
    } else {
        isshowOver.value = true
        formModel.value = {}
    }
}

//获取项目数据
const projectData = ref([])
const getProjectData = async () => {
    const { error, code, data } = await getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectData.value = getArrValue(data)
    } else {
        projectData.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 formRef = ref(null)
const formModel = ref({
    afMoney:0,
})
//深度监听
watch(() => [
    formModel.value.afMoney,
], ([datas]) => {
    if (datas > 1000) {
        isshowOver.value = false
    } else {
        isshowOver.value = true
    }
}, { deep: true })
const formRules = {
    afDate: [{ required: true, message: '请选择申请时间', trigger: 'change' }],
    afUserId: [{ required: true, message: '请选择申请人', trigger: 'change' }],
    isProjectBonus: [{ required: true, message: '请选择是否为项目提成申请', trigger: 'change' }],
    projectId: [{ required: true, message: '请选择关联项目', trigger: 'change' }],
    collectionDate: [{ required: true, message: '请选择回款时间', trigger: 'change' }],
    collectionMoney: [{ required: true, message: '请选择回款金额', trigger: 'change' }],
    afProportion: [{ required: true, message: '请输入申请比例', trigger: 'blur' }],
    afMoney: [{ required: true, message: '请输入请款金额', trigger: 'blur' }],
    payeeUserName: [{ required: true, message: '请输入收款人', trigger: 'blur' }],
    payeeUserBankName: [{ required: true, message: '请输入收款人开户行', trigger: 'blur' }],
    payeeUserBankId: [{ required: true, message: '请输入收款账号', trigger: 'blur' }],
    payeeUseInfo: [{ required: true, message: '请输入请款用途', trigger: 'blur' }],
}

//草稿数据详情
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 relatedModal = ref(false)
const relatedIds = ref([])
const budgetModalShow = () => {
    const { projectId, contractCollectionDataId } = formModel.value
    relatedModal.value = true
    
    relatedIds.value = contractCollectionDataId?.split(',') || []
    getBudgetTableData(projectId)
}

//关联预算计划表格
const tableRelatedLoading = ref(false)
const tableRelatedColumn = [
    { key: 'returnedCondition', name: '回款条件' },
    { key: 'shouldReturnedTime', name: '应收回款时间', width: '180', align: 'center' },
    { key: 'shouldReturnedMoney', name: '应收回款金额(元)', width: '140', align: 'center' },
    { key: 'practicalReturnedTime', name: '实际回款时间', width: '180', align: 'center' },
    { key: 'practicalReturnedMoney', name: '实际回款金额(元)', width: '140', align: 'center' },
    { key: 'reminderUserName', name: '催款执行人', width: '100', align: 'center' },
    { key: 'action', name: '操作', width: '100', align: 'center' },
]
const tableRelatedData = ref([])
const getBudgetTableData = async (projectId) => {
    tableRelatedLoading.value = true
    const { error, code, data } = await mainApi.contractList({
        projectId: projectId,
    })
    //判断状态
    tableRelatedLoading.value = false
    if (!error && code === 200) {
        tableRelatedData.value = await isRowRelevance(data)
    } else {
        tableRelatedData.value = []
    }
}

//判断是否关联
const isRowRelevance = async (data) => {
    const res = getArrValue(data)
    const ids = relatedIds.value
    res.forEach(item => {
        item.isRelevance = ids.includes(item.id)
    })
    return res
}

//取消关联
const rowDisassociate = (row) => {
    const ids = relatedIds.value
    const index = ids.indexOf(row.id)
    if (index > -1) {
        ids.splice(index, 1)
    }
    relatedIds.value = ids
    row.isRelevance = false


}

//关联
const rowRelevance = (row) => {
    // const ids = relatedIds.value
 
    // ids.push(row.id)
    // relatedIds.value = ids

    // row.isRelevance = true
  
    tableRelatedData.value.forEach((ele)=>{
        ele.isRelevance = false
        rowDisassociate(ele)
    })
    const ids = relatedIds.value
    console.log(relatedIds.value, 'relatedIds.value')
    ids.push(row.id)
    relatedIds.value = ids
    row.isRelevance = true
}


//确认关联数据
const relatedSaveClick = () => {
    const ids = relatedIds.value?.join(',')
    formModel.value.contractCollectionDataId = ids
    tableRelatedData.value.forEach((ele)=>{
       if (ele.id === relatedIds.value[relatedIds.value.length - 1]) {
            formModel.value.collectionDate = ele.practicalReturnedTime
            formModel.value.collectionMoney = ele.shouldReturnedMoney
            formModel.value.contractCollectionDataId = ele.id
           
       }
     
    })
    if (!ids) {
        formModel.value.collectionDate = ''
        formModel.value.collectionMoney = ''
        formModel.value.contractCollectionDataId = ''
    }
    console.log(ids, 'isd')
    window.$message.success('操作成功')
   
    relatedModal.value = false
}

//关闭关联数据
const relatedCloseClick = () => {
    relatedModal.value = false
}


//流程数据
const timeData = ref({})
//流程数据
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 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-paymentRequest' })
        } 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>

<style>
.el-input-number .el-input__inner {
    text-align: left;
    line-height: 1;
    padding-left: 32px;
}
</style>