<template>
    <view>
        <uni-section
            :title="form.usernames"
            titleFontSize="16px"
            padding="0 0 5px 10px"
            style="margin-bottom: 20px;"
        />
        
        <MBCard style="margin: 15px">
            <view class="context">
                <view class="label">
                    <text>制单日期:</text>
                    <text>{{ formatDate(form.adddate, 'yyyy-MM-dd') }}</text>
                </view>
                <view class="label">
                    <text>合同编号:</text>
                    <text>{{ form.contractcode }}</text>
                </view>
                <view class="label">
                    <text>订单金额:</text>
                    <text>{{ formatPrice(form.contractmoney) }}</text>
                </view>
                <view class="label">
                    <text>补差金额:</text>
                    <text>{{ formatPrice(form.disCount) }}</text>
                </view>
                <view class="label">
                    <text>签署日期:</text>
                    <text>{{ formatDate(form.piaokou) }}</text>
                </view>
                <view class="label">
                    <text>执行日期:</text>
                    <text>{{ formatDate(form.piaokous) }}</text>
                </view>
                <view class="label">
                    <text>发货仓库:</text>
                    <text>{{ form.warehouseName }}</text>
                </view>
                <view class="label">
                    <text>导入用友日期:</text>
                    <text>{{ form.opdate }}</text>
                </view>
                <view class="label">
                    <text>收货日期:</text>
                    <text>{{ form.getdate }}</text>
                </view>
                <view class="label">
                    <text>发票确认日期:</text>
                    <text>{{ form.getbilldate }}</text>
                </view>
                
                <view class="label">
                    <text>审核表(附件):</text>
					<text
						class="linka" 
						v-if="form.loadfile"
						@click="YuLanfile(form.loadfile)"
					>
						{{ form.loadfile.split('\\').pop() }}
					</text>
                </view>
                <view class="label">
                    <text>审核表(OA):</text>
                    <text>{{ form.oaCode }}</text>
                </view>
                <view class="label">
                    <text style="min-width: 80px;">随货同行单:</text>
                    <text 
						class="linka" 
						v-if="form.billfile"
						@click="YuLanfile(form.billfile)"
					>
						{{ form.billfile.split('\\').pop() }}
					</text>
                </view>
                <view class="label" v-if="form.pdffile">
                    <text>合同(附件):</text>
					<text
						class="linka" 
						v-if="form.form.pdffile"
						@click="YuLanfile(form.form.pdffile)"
					>
						{{ form.form.pdffile.split('\\').pop() }}
					</text>
                    <!-- <text>{{ form.pdffile }}</text> -->
                </view>
            </view>
            <view
                style="display: flex;gap: 4px;font-size: 14px;color: #666;margin-bottom: 4px;margin-top:6px;font-weight: 500;flex-direction: column;
				width: 100%;">
                <view style="width: 100%">发货地址:{{ form.place }}</view>
                <!-- <view></view> -->
            </view>
        </MBCard>
        
        <view class="viewunisection">
            <uni-section>
                <view class="uni-padding-wrap uni-common-mt">
                    <uni-segmented-control 
                        :current="current" 
                        :values="items"
                        style-type="text"
                        @clickItem="onClickItem" 
                    />
                </view>
            </uni-section>
        </view>
        
        <!-- 根据当前标签页显示对应的组件 -->
        <view class="tab-content">
            <!-- 商品信息 -->
            <GoodsInfo 
                v-if="current === 0" 
                :goods-list="goodsList" 
                :loading="loading"
            />
            
            <!-- 实绩发货清单 -->
            <ActualShipmentList 
                v-if="current === 1" 
                :shipment-list="ShopppingListtableData" 
                :loading="loading"
            />
            
            <!-- 发票单 -->
            <InvoiceList 
                v-if="current === 2" 
                :invoice-list="InvoicetableData" 
                :loading="loading"
            />
            
            <!-- 操作日志 -->
            <OperationLog 
                v-if="current === 3" 
                :log-list="OperationLogtableData" 
                :loading="loading"
            />
        </view>
    </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'	
import { onMounted, ref } from 'vue'
import { 
    salemainDetail, 
    businessManagerReviewGoodsList, 
    getsalemaincheckAmount,
    BaseuserBusinessUserDetail,
    getSaleDisDetail,
    salemainlogList,
    listproductList,
    getInvoiceList 
} from '@/api/orderManager/index.js'

import { formatPrice,YuLanfile } from "@/utils/utils.js";
import { formatDate } from "@/uni_modules/uni-dateformat/components/uni-dateformat/date-format";
import MBCard from "@/components/MB/MBCard.vue";
import MBLoading from "@/components/MB/MBLoading.vue";

// 导入子组件
import GoodsInfo from "@/components/SailMainComponents/OrderManagerCom/goodsListC.vue";
import ActualShipmentList from "@/components/SailMainComponents/OrderManagerCom/ActualShipmentList.vue";
import InvoiceList from "@/components/SailMainComponents/OrderManagerCom/InvoiceList.vue";
import OperationLog from "@/components/SailMainComponents/OrderManagerCom/OperationLog.vue";

// 加载状态
const loading = ref(false)

// 商品列表数据
const goodsList = ref([])

// 表单数据
const form = ref({
    companyId: null,
})

// 当前选中的标签页索引
const current = ref(0)

// 标签页选项
const items = ref(['商品信息', '实绩发货清单', '发票单', '操作日志'])

// 生产单位列表
const companyOptions = ref([])

// 公司名称
const companyName = ref('')

// 剩余金额
const remainingMoney = ref(0)

// 订单金额
const orderAmount = ref(0.00)

// 存储参数
const saleId = ref('')

// 订单下面商品信息列表
const CommodityInfortableData = ref([])

// 订单下面实际发货清单列表
const ShopppingListtableData = ref([])

// 订单下面发票信息列表
const InvoicetableData = ref([])

// 订单下面操作日志列表
const OperationLogtableData = ref([])

// 页面加载时获取参数
onLoad((options) => {
    // 获取跳转传递的参数
    saleId.value = options.id || ''
    console.log('接收到的 saleId:', saleId.value)
    
    if (saleId.value) {
        // 先获取部门列表，然后获取详情数据
        getDeptLists().then(() => {
            getAllData()
        })
    } else {
        uni.showToast({
            title: '参数错误',
            icon: 'error'
        })
    }
})

// 获取部门列表
const getDeptLists = () => {
    return listproductList().then(res => {
        if (res.code === 200 && res.data) {
            companyOptions.value = res.data
            console.log('获取到部门列表:', companyOptions.value)
        }
        return res
    })
}

// 获取所有数据
const getAllData = () => {
    // 获取详情数据
    GetsalemainDetail()
}

// 点击标签页
const onClickItem = (e) => {
    if (current.value !== e.currentIndex) {
        current.value = e.currentIndex
    }
}

// 获取详情数据
async function GetsalemainDetail() {
    loading.value = true
    
    try {
        // 并行执行所有请求
        await Promise.all([
            getSaleMainDetail().catch(err => {
                console.error('获取订单详情失败:', err)
                return null
            }),
            getsalemainlogList().catch(err => {
                console.error('获取操作日志失败:', err)
                return null
            })
        ])
        
    } finally {
        // 使用 setTimeout 避免 loading 闪烁
        setTimeout(() => {
            loading.value = false
        }, 300)
    }
}

// 获取订单详情和商品信息
const getSaleMainDetail = async () => {
    // 获取商品列表
    await salemainDetail(saleId.value).then(res => {
        form.value = res.data
        goodsList.value = form.value.saledetailList || []
        setCompanyName()
        
        // 获取发货地址
        BaseuserBusinessUserDetail(res.data.userid).then(res => {
            form.value.place = res.data.BaseUserBus?.place || ''
        })
    })
    
    // 获取实绩发货清单
    await getSaleDisDetailData()
    
    // 获取发票信息
    await getInvoiceListData()
}

// 获取实绩发货清单
const getSaleDisDetailData = async () => {
    await getSaleDisDetail(saleId.value).then(res => {
        ShopppingListtableData.value = res.data || []
    })
}

// 获取发票信息
const getInvoiceListData = async () => {
    await getInvoiceList(saleId.value).then(res => {
        InvoicetableData.value = res.data || []
    })
}

// 获取操作日志
const getsalemainlogList = async () => {
    const query = {
        pageNum: 1,
        pageSize: 1000,
        isAsc: 'ascending',
        orderByColumn: 'editdate'
    }
    const data = {
        saleid: saleId.value
    }
    
    await salemainlogList(data, query).then(res => {
        OperationLogtableData.value = res.rows || []
        // 处理editdate字段：提取前19个字符，将T替换为空格（精确到时分秒）
        OperationLogtableData.value.forEach(item => {
            if (item.editdate && typeof item.editdate === 'string') {
                item.editdate = item.editdate.substring(0, 19).replace('T', ' ');
            }
        })
    })
}

// 根据 companyId 设置公司名称
function setCompanyName() {
    if (!form.value.companyId || !companyOptions.value.length) {
        console.log('companyId 为空或部门列表为空')
        companyName.value = ''
        return
    }
    
    console.log('查找公司名称，companyId:', form.value.companyId)
    
    // 在部门列表中查找对应的公司
    const company = companyOptions.value.find(item => item.deptId === form.value.companyId)
    
    if (company) {
        companyName.value = company.deptName
        console.log('找到公司名称:', companyName.value)
    } else {
        companyName.value = '未知公司'
        console.log('未找到对应的公司')
    }
}

// 计算订单金额
function calculateOrderAmount() {
    if (!goodsList.value.length) {
        orderAmount.value = 0
        return
    }
    
    // 将所有商品的 allmoney 相加
    const total = goodsList.value.reduce((sum, item) => {
        const money = parseFloat(item.allmoney) || 0
        return sum + money
    }, 0)
    
    orderAmount.value = total
    console.log('计算订单金额:', orderAmount.value)
}

// 查询额度
function getEdu() {
    const Amountform = {
        companyId: form.value.companyId,
        saleId: form.value.saleid,
    }
    
    console.log('查询额度参数:', Amountform)
    
    // 查询剩余额度
    getsalemaincheckAmount(Amountform).then(res => {
        if (res.code === 200) {
            remainingMoney.value = res.data.amounts || 0
            console.log('获取到剩余额度:', remainingMoney.value)
        }
    }).catch(error => {
        console.error('获取额度失败:', error)
    })
}

// 取消
const goCancel = () => {
    uni.navigateTo({
        url: '/pages/work/OrderManager/index'
    })
}
</script>

<style>
	.linka{
		color: #409eff;
		text-decoration: underline;
	}
	a, a:focus, a:hover{
	    color: #409eff;
	    text-decoration: underline;
	}
.context {
    font-size: 14px;
}
.context .label {
    font-size: 14px;
}
.uni-section .uni-section-header__content .distraction {
    font-weight: bold;
}
.viewunisection :deep().uni-section .uni-section-header {
    padding: 0;
}
.tab-content {
    margin-top: 10px;
}
</style>