<template>
    <view class="container">
        <MBCard>
            <uni-forms ref="baseForm" :modelValue="queryParams">
                <uni-forms-item label="货主">
                    <uni-data-select
                        v-model="queryParams.companyId"
                        :clear="true"
                        :localdata="companyOptions"
                        text-field="deptName"
                        value-field="deptId"
                        @change="getTableData"
                    />
                </uni-forms-item>
				<uni-forms-item label="状态">
				    <uni-data-select
				        v-model="queryParams.state"
				        :clear="true"
				        :localdata="stateList"
				        @change="getTableData"
				    ></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="合同编号" v-if="userType === '01'  || userType === '02'" >
				    <input
				        v-model="queryParams.contractcode"
				        class="uni-input custom-input"
				        placeholder="请输入合同编号"
				        @confirm="getTableData"/>
				</uni-forms-item>
				<uni-forms-item label="商业公司" v-if="userType === '00'" >
<!--				    <input-->
<!--				        v-model="queryParams.businessCompany"-->
<!--				        class="uni-input custom-input"-->
<!--				        placeholder="请输入商业公司"-->
<!--				        @confirm="getTableData"/>-->
                    <BusinessCompany v-model="queryParams.businessCompany" @change="getTableData"/>
				</uni-forms-item>
            </uni-forms>
			 <button 
			 type="primary" 
			 @click="gotoNewAdd"
			 v-if="userType === '01' || userType === '02'"
			 >
			 新增
			 </button>
        </MBCard>
        
        <MBLoading v-if="loading"/>
        <view v-else>
            <ListItem :items="tableData" @refresh="getTableData" />
            <MBPagination
                v-if="total > 0"
                v-model:limit="paging.pageSize"
                v-model:page="paging.pageNum"
                :total="total"
                @pagination="handleQuery"
            />
        </view>
    </view>
</template>

<script setup>
import {listproductList, listsalemain} from "../../../api/orderManager/index.js"
import {computed, getCurrentInstance, onMounted, ref} from "vue"
import {getDicts} from "../../../api/system/dict/data.js"
import {useOrderManagerStore} from "../../../store/modules/orderManager.js"

import MBCard from "../../../components/MB/MBCard.vue";
import MBPagination from "../../../components/MB/MBPagination.vue";
import MBLoading from "../../../components/MB/MBLoading.vue";
import ListItem from "./ListItem.vue";
import { getUserProfile } from "@/api/system/user"
import BusinessCompany from "../../../components/BusinessCompany.vue";

  
const userType = ref()

const {proxy} = getCurrentInstance()
// 表单数据
const baseFormData = ref({})
//订单类型
const orderTypeList = ref([])
const paymentValue = ref(0)
const companyValue = ref(0)

// 添加加载状态
const loading = ref(true)
const total = ref(0)
const paging = ref({
    // 页码
    pageNum: 1,
    // 分页数量
    pageSize: 20,
    isAsc: 'descending',
    orderByColumn: 'adddate'
})
const queryParams = ref({
    params: {
        state: "0,1,-1,2,-2,3,-3,9,10,11,12,-12,13,-13,14,15,16",
    }
})

const stateList = ref([])
const companyOptions = ref([])

// 合同数据
const tableData = ref([])

// 初始化数据
onMounted(async () => {
    try {
        loading.value = true
        await getDictData()
		await getDeptLists()
		await getUser()
        await getTableData()
    } finally {
        loading.value = false
    }
})
  function getUser() {
    getUserProfile().then(response => {
      userType.value = response.data.userType
    })
  }

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '未知日期'
    return dateString.split(' ')[0]
}

//获取字典数据
const getDictData = async () => {
    try {
        const [stateRes, typeRes] = await Promise.all([
            getDicts("order_state"),
            getDicts("dazhong_dingdan_type")
        ])
        stateList.value = stateRes.data.map(item => {
            return {
                value: item.dictValue,
                text: item.dictLabel
            }
        })
        
        orderTypeList.value = typeRes.data
    } catch (error) {
        console.error('获取字典数据失败:', error)
    }
}

//获取列表数据
const getTableData = async () => {
    try {
		loading.value = true
		const data = await listsalemain(queryParams.value, paging.value)
		total.value = data.total
		tableData.value = data.rows
    } catch (error) {
        console.error('获取数据失败:', error)
    } finally {
        loading.value = false
    }
}

const getDeptLists = async () => {
    try {
        const res = await listproductList()
        companyOptions.value = res.data.map(item => {
            return {
                value: item.deptId,
                text: item.deptName
            }
        })
    } catch (error) {
        console.error('获取部门列表失败:', error)
    }
}

// 筛选合同
function filtertableData(e) {
    console.log("筛选条件变化:", e)
    // 计算属性会自动更新，无需额外操作
}

//编号输入框事件
const handleInput = (e) => {
    console.log('handleInput', e.detail.value)
}

// 跳转到详情页
function gotoDetail(contract) {
    console.log("查看合同详情:", contract)
    //存储要传的值到pinia
    useOrderManagerStore().addOrder(contract)
    console.log('数据', useOrderManagerStore().orders)
    if (contract.state == '0') {
        uni.navigateTo({
            url: "/pages/work/OrderManager/components/EditData?"
        });
    } else {
        uni.navigateTo({
            url: "/pages/work/OrderManager/components/LookData"
        });
    }
}

const gotoNewAdd = () => {
    uni.navigateTo({
        url: "/pages/work/OrderManager/components/NewAdd"
    });
}
const handleQuery = async () => {
    try {
    	loading.value = true
    	const data = await listsalemain(queryParams.value, paging.value)
    	total.value = data.total
    	tableData.value = data.rows
    } catch (error) {
        console.error('获取数据失败:', error)
    } finally {
        loading.value = false
    }
}
</script>

<style lang="scss" scoped>
/* 加载动画容器 */
.loading-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    min-height: 300px;
}

.loading-text {
    margin-top: 10px;
    color: #666;
    font-size: 14px;
}

.custom-input {
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 5px;
    height: 35px;
	font-size: 12px;
}

.container {
    padding: 10px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.example {
    padding: 10px;
    background: #fff;
    border-radius: 8px;
    margin-bottom: 15px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

:deep(.uni-section .uni-section-header) {
    padding: 0;
}

:deep(.uni-card) {
    padding: 0 !important;
    margin: 10px 0 !important;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.uni-card__content) {
    padding: 12px !important;
}

.demo-uni-row {
    padding: 5px 0;
    font-size: 14px;
}

.demo-uni-col {
    padding: 2px 0;

    &.dark {
        color: #333;
        font-weight: 500;
    }

    &.light {
        color: #666;
    }
}

.card-even {
    border-left: 4px solid #2979ff;
}

.card-odd {
    border-left: 4px solid #19be6b;
}

.no-data {
    text-align: center;
    padding: 40px 0;
    color: #999;
    font-size: 16px;
}
uni-button{
	font-size: 14px;
}
</style>