<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="订单号" prop="order_id">
                    <el-input
                        class="w-[280px]"
                        v-model="queryParams.order_id"
                        @keydown.enter="resetPage"
                        clearable
                        placeholder="请输入订单号"
                    />
                </el-form-item>
                <el-form-item label="门店" prop="store_id">
                    <el-select
                        v-model="queryParams.store_id"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="输入门店名称搜索"
                        remote-show-suffix
                        :remote-method="remoteMethod"
                        :loading="storeloading"
                        style="width: 240px"
                        @change="resetPage"
                    >
                        <el-option
                            v-for="item in storeList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户" prop="uid">
                    <!-- <el-input class="w-[280px]" v-model="queryParams.uid" clearable placeholder="请输入用户id" /> -->
                    <el-select
                        v-model="queryParams.uid"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="输入用户名称搜索"
                        remote-show-suffix
                        :remote-method="remoteMethodUser"
                        :loading="userloading"
                        style="width: 240px"
                        @change="resetPage"
                    >
                        <el-option
                            v-for="item in userList"
                            :key="item.id"
                            :label="`${item.real_name}|${item.mobile}  (ID:${item.id})`"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="日期" prop="order_id">
                    <el-date-picker
                        v-model="startEndTime"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        unlink-panels
                        :shortcuts="shortcuts"
                        @change="changeStartEndTime"
                    />
                </el-form-item>
                <el-form-item label="支付方式" prop="pay_type">
                    <el-select
                        class="w-[280px]"
                        v-model="queryParams.pay_type"
                        placeholder="请选择支付方式"
                        @change="resetPage"
                    >
                        <el-option
                            :label="item.name"
                            :value="item.value"
                            v-for="item in dictData.pay_type"
                            :key="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="订单类型" prop="source">
                    <el-select
                        class="w-[280px]"
                        v-model="queryParams.source"
                        placeholder="请选择订单类型"
                        @change="resetPage"
                    >
                        <el-option label="批发订单" value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams()">重置</el-button>
                    <export-data
                        class="ml-2.5"
                        :fetch-fun="apiStoreOrderLists"
                        :params="queryParams"
                        :page-size="pager.size"
                    />
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <el-radio-group v-model="orderStatus" @change="changeOrderStatus">
                <router-link
                    :to="{
                        path: 'store_order/add'
                    }"
                    class="ml-4 mr-4"
                >
                    <el-button type="primary"> 添加订单 </el-button>
                </router-link>
                <el-radio-button label="0">全部</el-radio-button>
                <el-radio-button label="1">待支付</el-radio-button>
                <el-radio-button label="2">待核销</el-radio-button>
                <el-radio-button label="60">已设置配送人员</el-radio-button>
                <el-radio-button label="3">已完成</el-radio-button>
                <el-radio-button label="4">已退款</el-radio-button>
            </el-radio-group>
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column label="ID" prop="id" show-overflow-tooltip width="100" />
                    <el-table-column
                        label="订单号"
                        prop="order_id"
                        show-overflow-tooltip
                        width="200"
                    />
                    <el-table-column
                        label="商品信息"
                        prop="order_id"
                        width="150"
                        show-overflow-tooltip
                    >
                        <template #default="{ row }">
                            <div
                                class="flex items-center mb-2"
                                v-for="(item, index) in row.product?.slice(0, 3)"
                                :key="index"
                            >
                                <el-image
                                    class="w-[30px] h-[30px] mr-2 flex-shrink-0"
                                    :src="item.image"
                                    fit="cover"
                                    :preview-src-list="[item.image]"
                                    :preview-teleported="true"
                                />
                                <p class="truncate text-[12px]">{{ item.store_name }}</p>
                            </div>
                            <div v-if="row.product?.length > 3" style="text-align: left">...</div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="门店"
                        prop="store_name"
                        show-overflow-tooltip
                        width="150"
                    />
                    <el-table-column
                        label="用户"
                        prop="nickname"
                        show-overflow-tooltip
                        width="150"
                    />
                    <el-table-column
                        label="实际支付金额"
                        prop="pay_price"
                        show-overflow-tooltip
                        width="150"
                    />
                    <el-table-column label="订单状态" prop="status_name" width="100">
                        <template #default="{ row }">
                            <div v-if="row.refund_status == 2">
                                <el-tag type="danger">已退款</el-tag>
                            </div>
                            <div v-else>
                                <el-tag v-if="row.status_name == '待收货'" type="success">{{
                                    row.status_name
                                }}</el-tag>
                                <el-tag
                                    v-else-if="
                                        row.status_name == '已收货' || row.status_name == '已完成'
                                    "
                                    type="info"
                                    >{{ row.status_name }}</el-tag
                                >
                                <el-tag
                                    v-else-if="
                                        row.status_name == '待发货' || row.status_name == '待核销'
                                    "
                                    type="warning"
                                    >{{ row.status_name }}</el-tag
                                >
                                <el-tag v-else type="danger">{{ row.status_name }}</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="支付方式"
                        prop="pay_type"
                        show-overflow-tooltip
                        width="100"
                    >
                        <template #default="{ row }">
                            <dict-value
                                :options="dictData.pay_type"
                                :value="row.pay_type"
                            ></dict-value>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="订单类型"
                        prop="source_name"
                        show-overflow-tooltip
                        width="100"
                    />

                    <el-table-column
                        label="支付时间"
                        prop="pay_time"
                        show-overflow-tooltip
                        width="200"
                    />
                    <!-- <el-table-column label="配送人员" prop="delivery_name" show-overflow-tooltip /> -->
                    <el-table-column label="操作" fixed="right">
                        <template #default="{ row }">
                            <!-- <el-button v-perms="['store_order.store_order/edit']" type="primary" link
                                @click="handleEdit(row)">
                                编辑
                            </el-button>
                            <el-button v-perms="['store_order.store_order/delete']" type="danger" link
                                @click="handleDelete(row.id)">
                                删除
                            </el-button> -->
                            <el-button type="primary" link @click="handleDetai(row)"
                                >详情</el-button
                            >
                            <el-button type="primary" link @click="TransferAdvanceOrder(row)"
                                >转预定单</el-button
                            >
                            <!-- <el-button type="primary" link @click="handleDelivery(row)"
                                >设置配送人员</el-button
                            > -->
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <edit-popup
            v-if="showEdit"
            ref="editRef"
            :dict-data="dictData"
            @success="getLists"
            @close="showEdit = false"
        />
        <details-popup
            v-if="showDetails"
            ref="detailsRef"
            @success="getLists"
            @close="showDetails = false"
            :dictData="dictData"
        />
    </div>
</template>

<script lang="ts" setup name="storeOrderLists">
import { usePaging } from '@/hooks/usePaging'
import { useDictData } from '@/hooks/useDictOptions'
import { apiStoreOrderLists, apiStoreOrderDelete } from '@/api/store_order'
import { apiPurchaseOrderTransferAdvanceOrder } from '@/api/beforehand_order'
import { timeFormat } from '@/utils/util'
import { apiSystemStoreLists } from '@/api/system_store'
import feedback from '@/utils/feedback'
import moment from 'moment'
import EditPopup from './edit.vue'
import DetailsPopup from './details.vue'
import { apiUserLists } from '@/api/user'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const detailsRef = shallowRef<InstanceType<typeof DetailsPopup>>()
// 是否显示编辑框
const showEdit = ref(false)
const showDetails = ref(false)
const shortcuts = [
    {
        text: '近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 7)
            return [start, end]
        }
    },
    {
        text: '近一月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            return [start, end]
        }
    },
    {
        text: '近三月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 3)
            return [start, end]
        }
    }
]

const startEndTime = ref([])
// 查询条件
const queryParams = reactive({
    order_id: '',
    uid: '',
    pay_type: '',
    store_id: '',
    start_time: '',
    end_time: '',
    paid: null,
    status: null,
    is_writeoff: null,
    source: ''
})
const orderStatus = ref('0')
const changeOrderStatus = (e: any) => {
    if (e == 0) {
        queryParams.paid = null
        queryParams.status = null
        queryParams.is_writeoff = null
    } else if (e == 1) {
        queryParams.paid = 0
        queryParams.status = null
        queryParams.is_writeoff = null
    } else if (e == 2) {
        queryParams.paid = 1
        queryParams.status = 1
        queryParams.is_writeoff = 0
    } else if (e == 3) {
        queryParams.paid = 1
        queryParams.status = 2
        queryParams.is_writeoff = null
    } else if (e == 4) {
        queryParams.paid = null
        queryParams.status = 4
        queryParams.is_writeoff = null
    } else if (e == 60) {
        queryParams.is_delivery = 1
        queryParams.status = null
        queryParams.paid = null
        queryParams.is_writeoff = null
    }
    getLists()
}

const changeStartEndTime = () => {
    if (startEndTime.value[0] && startEndTime.value[1]) {
        queryParams.start_time = moment(startEndTime.value[0]).format('YYYY-MM-DD') + ' 00:00:00'
        queryParams.end_time = moment(startEndTime.value[1]).format('YYYY-MM-DD') + ' 23:59:59'
    } else {
        queryParams.start_time = ''
        queryParams.end_time = ''
    }
    getLists()
}

const storeloading = ref(false)
const storeList = ref([])
const remoteMethod = (e = '') => {
    storeloading.value = true
    apiSystemStoreLists({
        name: e,
        page_size: 50
    })
        .then((res) => {
            storeList.value = res.lists
            setTimeout(() => {
                storeloading.value = false
            }, 300)
        })
        .catch((err) => {
            setTimeout(() => {
                storeloading.value = false
            }, 300)
        })
}

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('pay_type')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiStoreOrderLists,
    params: queryParams
})

// 添加
const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    // editRef.value?.setFormData(data)
}

// 详情
const handleDetai = async (data: any) => {
    showDetails.value = true
    await nextTick()
    detailsRef.value?.open()
    detailsRef.value?.getDetail(data)
}

// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiStoreOrderDelete({ id })
    getLists()
}
const handleDelivery = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}
const userloading = ref(false)
const userList = ref([])
const remoteMethodUser = (e = '') => {
    userloading.value = true
    apiUserLists({
        nickname: e,
        page_size: 50
    })
        .then((res) => {
            userList.value = res.lists
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
        .catch((err) => {
            setTimeout(() => {
                userloading.value = false
            }, 300)
        })
}
/**
 * 订单转预购订单
 */
const TransferAdvanceOrder = (data: any) => {
    apiPurchaseOrderTransferAdvanceOrder(data)
}
onMounted(() => {
    getLists()
})
</script>
