<template>
    <uni-card
        v-for="(item,index) in items"
        :key="item.saleid"
        :class="index % 2 === 0 ? 'card-even' : 'card-odd'"
        :extra="item.contractcode"
        :title="item.usernames"
        style="margin: 0;margin-bottom: 20px"
        @click="handleDetail(item)"
    >
        <view class="context" v-if="userType === '01' || userType === '02'" >
            <view class="label">
                <text>货主:</text>
                <text>{{ item.companyName }}</text>
            </view>
            <view class="label">
                <text>金额:</text>
                <text>{{ formatPrice(item.contractmoney) }}</text>
            </view>
            <view class="label">
                <text>订单类型:</text>
				<view>
				    <dict-tag :options="orderTypeList" :value="item.type"/>
				</view>
            </view>
            <view class="label">
                <text>制单日期:</text>
				<text>{{ formatDate(item.adddate, 'yyyy-MM-dd') }}</text>
            </view>
			<view class="label">
			    <text>状态:</text>
				<text>
					<text>{{ item.stateText }}</text>
				</text>
			</view>
			<view class="label">
			    <text>操作:</text>
					<view  class="action-buttons">
						<button type='primary' 
							:plain="true" 
							@click.stop="Edit(item)" 
							class="btn"
							v-if="item.state == 0 "
						>
							编辑
						</button>
						<button type='warn' 
							:plain="true" 
							@click.stop="deleteData(item)" 
							class="btn"
							v-if="item.state == 0 || item.state == 1 || item.state == -1 || item.state == -2"
						>删除</button>
					</view>
			</view>
        </view>
		<view class="context" v-else >
		    <view class="label">
		        <text>货主:</text>
		        <text>{{ item.companyName }}</text>
		    </view>
			<view class="label">
			    <text>发货仓库:</text>
			    <text>{{ item.warehouseName }}</text>
			</view>
			<view class="label">
			    <text>制单日期:</text>
				<text>{{ formatDate(item.adddate, 'yyyy-MM-dd') }}</text>
			</view>
		    <view class="label">
		        <text>订单金额:</text>
		        <text>{{ formatPrice(item.contractmoney) }}</text>
		    </view>
			<view class="label">
			    <text>补差金额:</text>
			    <text>{{ formatPrice(item.disCount) }}</text>
			</view>
			<view class="label">
			    <text>本月/下月:</text>
			    <text>{{ item.actioninfo }}</text>
			</view>
			<view class="label">
			    <text>支付方式:</text>
				<view>
				    <text>{{ item.creditperiods > 0 ? '非现款' : '现款' }}</text>
				</view>
			</view>
			<view class="label">
			    <text>状态:</text>
				<text>
					<text>{{ item.stateText }}</text>
				</text>
			</view>
			<!-- <view class="label">
			    <text>操作:</text>
					<view  class="action-buttons">
						<button type='primary' 
							:plain="true" 
							@click.stop="Edit(item)" 
							class="btn"
						>
							编辑
						</button>
					</view>
			</view> -->
		</view>
    </uni-card>
</template>

<script setup>
import {defineOptions, defineProps, getCurrentInstance,computed,onMounted, ref} from 'vue'
import UniCard from "../../../uni_modules/uni-card/components/uni-card/uni-card.vue";
import {formatDate} from "../../../uni_modules/uni-dateformat/components/uni-dateformat/date-format";
import {formatPrice} from "../../../utils/utils";
import DictTag from "../../../components/dict-tag/dict-tag.vue";

import {delsalemain} from "../../../api/orderManager/index.js"
import { getUserProfile } from "@/api/system/user"
const {proxy} = getCurrentInstance()

// const {order_state, dazhong_dingdan_type} = proxy.useDict(['order_state', 'dazhong_dingdan_type'])

import {getDicts} from "../../../api/system/dict/data.js"

defineOptions({
    name: 'ListItem'
})

const userType = ref()

const props = defineProps(['items'])

const stateList = ref([])
const orderTypeList = ref([])
// 初始化数据
onMounted(async () => {
    try {
        await getDictData()
		await getUser()
    } finally {
    }
})
  function getUser() {
    getUserProfile().then(response => {
      userType.value = response.data.userType
    })
  }
const Edit = async (row) => {
    try {
		console.log(row,'当前行数据')
        //具体逻辑
		const params = {
			companyId: row.companyId,
			saleid: row.saleid,
			userid: row.userid,
		}
		// 序列化为JSON字符串，再编码
		const paramsStr = encodeURIComponent(JSON.stringify(params))
		proxy.$tab.navigateTo(`/pages/work/OrderManager/components/EditData?data=${paramsStr}`)
		
    } catch (error) {
        console.error('失败:', error)
    }
}
const emit = defineEmits(['refresh'])
// 删除
const deleteData = async (row) => {
    uni.showModal({
        title: '删除确认',
        content: `确定删除 ${row.contractcode || ''} 吗？`,
        confirmText: '确定',
        cancelText: '取消',
        confirmColor: '#DD524D',
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({
                        title: '删除中...',
                        mask: true
                    })
                    
                    await delsalemain(row.saleid)
                    
                    uni.hideLoading()
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                    
                    // 触发父组件刷新
                    proxy.$emit('refresh')
                    
                } catch (error) {
                    uni.hideLoading()
                    console.error('删除失败:', error)
                    uni.showToast({
                        title: '删除失败',
                        icon: 'error'
                    })
                }
            }
        }
    })
}

//获取字典数据
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 handleDetail = (row) => {
	console.log(userType.value,'userType')
	if(userType.value == '01' || userType.value == '02'){
		proxy.$tab.navigateTo(`/pages/work/OrderManager/components/LookDataSY?id=${row.saleid}`)
	}else{
		// uni.showToast({
		//   title: '内部用户查看还在开发完善中！!',
		//   icon: 'none',
		//   duration: 2000
		// })
		// return false;
		proxy.$tab.navigateTo(`/pages/work/OrderManager/components/LookDataNB?id=${row.saleid}`)
	}
}
</script>

<style lang="scss" scoped>
	:deep().uni-app-tag-span{
		font-size:12px
	}
	button{font-size: 12px;margin:0 5px;}
	.btn{
		padding-left:6px;
		padding-right: 6px;
		line-height:2;
	}
	/* 操作按钮 */
	.action-buttons {
	  display: flex;
	  justify-content: center;
	}
</style>