<template>
    <div class="h-full flex p-3 flex-col businessDetail" v-loading="pageLoading">
        <div class="w-full bg-white p-2 mb-2 shadow-md rounded-md flex items-center">
            <div class="icon mr-4">
                <el-link :underline="false" @click="backPath()">
                    <el-icon class="el-icon--right"><icon-view /></el-icon> 返回销售订单列表
                </el-link>
            </div>
            <div class="mr-8">
                <el-select v-model="values" placeholder="请选择" style="width: 300px" @change="getAll('')">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </div>

        <div class="flex-1 flex flex-col overflow-y-auto overflow-x-hidden scroll-bar" v-loading="pageLoading">
            <div class="w-full h-auto flex justify-between">
                <div class="bg-white shadow-md rounded-md" style="width: 46%;">
                    <Information :data="information" @refreshData="getAll" />
                </div>
                <div class="bg-white ml-2 shadow-md rounded-md flex-1">
                    <Attachment :data="attachment" :information="information" @refreshData="getAll" />
                </div>
            </div>

            <div class="w-full h-auto flex justify-between mt-2">
                <div class="bg-white shadow-md rounded-md" style="width: 65%;">
                    <Detailcompinents :data="relatedTasks" :information="information" :formTaskType="2" :filed="'orderId'"
                        :disabled-list="['taskType', 'orderId']" @refreshData="refreshData" />
                </div>
                <div class="bg-white ml-2 shadow-md rounded-md flex-1">
                    <OperationRecord :data="operationRecord" />
                </div>
            </div>

            <div class="w-full h-auto flex justify-between mt-2">
                <div class="bg-white shadow-md rounded-md" style="width: 65%;">
                    <Products :data="relatedProducts" :information="information" @refreshData="getAll" />
                </div>
                <div class="bg-white ml-2 shadow-md rounded-md flex-1" style="width: 33%;">
                    <Rebate :data="paymentCollectionList" :information="information" @refreshData="getAll" />
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import { Edit, ArrowLeft as IconView } from '@element-plus/icons-vue'
import { backPath } from '../../../utils/tools'
import { useRoute } from "vue-router";
import { post } from "@/utils/request";
import { GETTABLELIST, IMPORTMOD, URL_DETEALORDER, URL_FERDETAILTASK, URL_PAYLIST, URL_PRODUTWITHORDER } from "../api";

import Information from '../component/information.vue'
import Attachment from '../component/attachment.vue'
import OperationRecord from '../component/operationRecord.vue'
import Products from '../component/products.vue'
import Rebate from '../component/rebate.vue'
import Detailcompinents from '@/components/detailcompinents/relatedTasks.vue'
import { GETATTACHMENT, GETCENTERLIST } from "@/pages/product/api";

const route = useRoute()
const globalPopup = inject<GlobalPopup>('globalPopup')
const pageLoading = ref(false)
const rowId = ref(+(route.query.id || ''))
const values = ref<number | string>('')
const options = ref<optionType[]>([])
const information = ref({}) // 基本信息
const attachment = ref<any[]>([]) // 附件信息
const relatedTasks = ref<any[]>([]) // 相关任务
const operationRecord = ref<any[]>([]) // 操作记录
const relatedProducts = ref<any[]>([]) // 相关产品
const paymentCollectionList = ref<any[]>([]) // 回款

// 获取基本信息
function getDetail() {
    post(URL_DETEALORDER, { id: values.value }).then(({ data }) => {
        information.value = data
    })
}

// 获取附件
function getFileList() {
    post(GETATTACHMENT, { moduleId: values.value, moduleCode: IMPORTMOD }).then((res) => {
        attachment.value = res.data
    })
}

// 获取所有销售订单
function getAllContacts() {
    post(GETTABLELIST, { pageIndex: -1, pageSize: -1 }).then(({ data }) => {
        options.value = (data.record || []).map((item: any) => ({ value: item.id, label: item.orderName }))
        values.value = rowId.value
    }).catch((err) => {
        globalPopup?.showError(err.msg)
    })
}

// 获取相关任务
function getRelatedTasks() {
    post(URL_FERDETAILTASK, { id: values.value }).then(({ data }) => {
        relatedTasks.value = data
    })
}
function refreshData() {
    getAll('getRelatedTasks')
}

// 获取操作记录
function getOperationRecord() {
    post(GETCENTERLIST, { id: values.value, moduleCode: 'SalesOrder' }).then(({ data }) => {
        operationRecord.value = data
    })
}

function getPaymentCollectionList() {
    post(URL_PAYLIST, { orderId: values.value }).then(({ data }) => {
        paymentCollectionList.value = data || []
    })
}

// 获取相关产品
function getRelatedProducts() {
    post(URL_PRODUTWITHORDER, { id: values.value }).then(({ data }) => {
        const list = (data || []).map((item: any) => {
            const { id, productName, productCode, unit, unitName, typeName, type, price, inventory, orderProductDetail } = item
            return {
                id, productId: id, productName, productCode, unit, unitName, typeName, type, price, inventory,
                quantity: +orderProductDetail?.num,
                discount: +orderProductDetail?.discount,
                sellingPrice: +orderProductDetail?.sealPrice,
                totalPrice: +orderProductDetail?.totalPrice
            }
        })
        relatedProducts.value = list
    })
}

type allTypeStr = 'getDetail' | 'getFileList' | 'getRelatedTasks' | 'getOperationRecord' | 'getRelatedProducts' | 'getPaymentCollectionList' | ''

async function getAll(event: allTypeStr) {
    try {
        pageLoading.value = true
        if (!event) {
            await Promise.all([
                getDetail(),
                getFileList(),
                getRelatedTasks(),
                getOperationRecord(),
                getRelatedProducts(),
                getPaymentCollectionList()
            ])
        } else if (event == 'getDetail') {
            await getDetail()
        } else if (event == 'getFileList') {
            await getFileList()
        } else if (event == 'getRelatedTasks') {
            await getRelatedTasks()
        } else if (event == 'getOperationRecord') {
            await getOperationRecord()
        } else if (event == 'getRelatedProducts') {
            await getRelatedProducts()
        } else if (event == 'getPaymentCollectionList') {
            await getDetail()
            await getPaymentCollectionList()
        }

        pageLoading.value = false
    } catch {
        pageLoading.value = false
    }
}

onMounted(() => {
    values.value = rowId.value
    getAllContacts()
    getAll('')
})

</script>
