<script setup>
import { ref, reactive } from 'vue'
import { Search } from '@element-plus/icons-vue'
import {apiOrderConfig} from '@/api/order'
import { apiMediaCommon } from '@/api/media'
import UserDialog from './components/UserDialog.vue'
import { apiSystemCommon } from '@/api/system'

const tableColumns = [
    {
        label:'订单编号',
        key:'OrderID',
        sortable:false
    },
    {
        label:'姓名',
        key:'RealName',
        sortable:false,
        widthsty:90,
    },
    {
        label:'手机号',
        key:'Mobile',
        sortable:false
    },
    {
        label:'商品名称',
        key:'ProductName',
        sortable:false
    },{
        label:'商品类型',
        key:'ProductType',
        sortable:false,
        widthsty:90,
    },{
        label:'商品价格',
        key:'TotalAmount',
        sortable:false,
        widthsty:110,
    },{
        label:'有效期',
        key:'ValidDuration',
        sortable:false
    },{
        label:'订单状态',
        key:'Status',
        sortable:false,
        widthsty:90,
    },{
        label:'支付渠道',
        key:'PaymentWay',
        sortable:false,
        widthsty:90,
    },{
        label:'支付金额',
        key:'PaymentAmount',
        sortable:false,
        widthsty:110,
    },{
        label:'售后状态',
        key:'RefundStatus',
        sortable:false,
        widthsty:90,
    },{
        label:'付款时间',
        key:'PaymentTime',
        sortable:false
    },{
        label:'下单时间',
        key:'CreatedTime',
        sortable:false
    },
    {
        label:'操作',
        key:'handle',
        align: 'center',
        widthsty:100,
    }
]
const productTypeList = ref([
    {
        value: 'report',
        label: '报告'
    }, {
        value: 'audio',
        label: '音频'
    }, {
        value: 'video',
        label: '视频'
    }, {
        value: 'package',
        label: '套餐'
    }
])
const orderStatusList = ref([
    {
        value: 'pending',
        label: '待支付'
    }, {
        value: 'paid',
        label: '已支付'
    }, {
        value: 'closed',
        label: '已关闭'
    }, {
        value: 'refund',
        label: '售后'
    }
])
const refundListStatusList = ref([
    {
        value: 'processing',
        label: '退款中'
    }, {
        value: 'failure',
        label: '退款失败'
    }, {
        value: 'success',
        label: '退款成功'
    }
])

const tableQuery = reactive({
    keyWord:'',
    currentPage:1,
    pageSize:10,
    totals:0,
    sortType:'',
    paymentDate:'',
    paymentWay:'',
    createdDate:'',
    productType:'',
    refundStatus:'',
    orderStatus:''
})

const tableData = ref([])
const show = ref(false)
const showUserDialog = ref(false)
const isRefund = ref(false)
function getTableData(){
    apiOrderConfig.getProductOrderList({
        KeyWord:tableQuery.keyWord,
        CurrentIndex:tableQuery.currentPage,
        PageSize:tableQuery.pageSize,
        SortType:tableQuery.sortType,
        PaymentDate:tableQuery.paymentDate,
        PaymentWay:tableQuery.paymentWay,
        CreatedDate:tableQuery.createdDate,
        ProductType:tableQuery.productType,
        RefundStatus:tableQuery.refundStatus,
        OrderStatus:tableQuery.orderStatus
    }).then(res=>{
        if(res.Ret!==200) return 

        tableData.value = res.Data.List||[]
        tableQuery.totals = res.Data.Paging.Totals||0
    })
}
getTableData()
getLableList()
const labelOptions = ref([])
const refundRow = ref({})
function getLableList(){
    apiSystemCommon.getSysConfig({
        ConfigKey:'paymentWay'
    }).then(res=>{
        if(res.Ret!==200) return
        labelOptions.value = res.Data.paymentWay.map(item => {
            const key = Object.keys(item)[0]; // 获取支付方式的中文名称
            const value = item[key]; // 获取支付方式的英文名称
            return {
                value: value, // 将英文名称设置为 value
                label: key // 将中文名称设置为 label
            };
        })
    })
}

function handlePageChange(page){
    tableQuery.currentPage = page
    getTableData()
}
function handleSortChange({order,prop}){
    // ascending 
    const propMap = {
        0:'CreatedTime',
        1:'ReadCount',
        2:'LastReadTime',
    }
    tableQuery.sortParam = propMap[prop]||2
    tableQuery.sortType = order==='ascending'?1:0
    getTableData()
}

function handleSelectChange() {
    if (tableQuery.orderStatus !== 'refund' && tableQuery.refundStatus !== '') {
        tableQuery.refundStatus = '';
    }
    getTableData();
}

/* 下载数据 */
async function downloadExcel() {
    const res = await apiOrderConfig.getExportProductOrder(
        {
            KeyWord:tableQuery.keyWord,
            SortType:tableQuery.sortType,
            PaymentDate:tableQuery.paymentDate,
            PaymentWay:tableQuery.paymentWay,
            CreatedDate:tableQuery.productType,
            ProductType:tableQuery.createdDate,
            RefundStatus:tableQuery.refundStatus,
            OrderStatus:tableQuery.orderStatus
        }
    )
    const blob = new Blob([res], {
        type: "application/vnd.ms-excel;charset=utf-8",
    });
    let fileName = res.fileName;
    const elink = document.createElement("a");
    elink.download = fileName; //命名下载名称
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click(); // 点击下载
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink); // 释放标
}

function operation (handle, row) {
    refundRow.value = row
    switch (handle) {
        case 'details':
            showUserDialog.value = true;
            isRefund.value = false
        break
        case 'refund':
            showUserDialog.value = true;
            isRefund.value = true
        break;
        default:
        return false;
    }
}

function success() {
    showUserDialog.value = false;
    getTableData()
}
</script>

<template>
    <el-card class="box-card">
        <div class="temp-user-list-wrap">
            <div class="top-box">
                <div class="search-box">
                    <el-select clearable v-model="tableQuery.productType" @change="handleSelectChange()" placeholder="产品类型" style="width: 150px; margin-right: 20px;">
                        <el-option
                        v-for="item in productTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select clearable v-model="tableQuery.orderStatus" @change="handleSelectChange()" placeholder="订单状态" style="width: 150px; margin-right: 20px;">
                        <el-option
                        v-for="item in orderStatusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-model="tableQuery.paymentWay" clearable @change="handleSelectChange()" placeholder="支付渠道" style="width: 150px; margin-right: 20px;">
                        <el-option
                            v-for="item in labelOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-model="tableQuery.refundStatus" clearable @change="handleSelectChange()" placeholder="售后状态" style="width: 150px; margin-right: 20px;" :disabled="tableQuery.orderStatus !== 'refund'">
                        <el-option
                        v-for="item in refundListStatusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <el-date-picker
                        v-model="tableQuery.createdDate"
                        type="date"
                        placeholder="付款时间"
                        format="YYYY-MM-DD"
                        style="margin-right: 20px;width: 150px;"
                        value-format="YYYY-MM-DD"
                        @change="handlePageChange(1)"
                    />
                    <el-date-picker
                        v-model="tableQuery.paymentDate"
                        type="date"
                        placeholder="下单时间"
                        style="margin-right: 20px;width: 150px;"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        @change="handlePageChange(1)"
                    />
                </div>
                <div class="search-box">
                    <el-button type="primary" style="margin-right: 20px;" @click="downloadExcel" v-permission="'order:export'">导出表格</el-button>
                    <el-input 
                        v-model="tableQuery.keyWord"
                        :prefix-icon="Search" clearable
                        style="width:400px"
                        placeholder="订单编号/姓名/手机号/商品名称" 
                        @input="handlePageChange(1)"
                        />
                </div>
            </div>
            <div class="table-box">
                <el-table stripe border :data="tableData" @sort-change="handleSortChange">
                    <el-table-column 
                        v-for="column in tableColumns" :key="column.key"
                        :prop="column.key" :label="column.label" :sortable="column.sortable":width="column.widthsty"
                        :min-width="column.minwidthsty">
                        <template #default="scope" v-if="column.key === 'AccountStatus'">
                            <el-tag :type="scope.row[column.key]=== 'Open' ?'success':'info'">{{scope.row[column.key]=== 'Open'?'已开户':'未开户' }}</el-tag>
                        </template>
                        <template #default="scope" v-else-if="column.key === 'handle'">
                            <span v-if="scope.row.Status !== '已支付' && scope.row.RefundStatus !== '退款成功'">-</span>
                            <span class="edit" v-if="scope.row.Status === '售后' && scope.row.RefundStatus === '退款成功'"  @click="operation('details', scope.row)" v-permission="'order:refundDetails'">退款详情</span>
                            <span class="edit" v-if="scope.row.Status === '已支付'" @click="operation('refund', scope.row)" v-permission="'order:refund'">退款</span>
                        </template>
                        <template #default="scope" v-else>
                            {{scope.row[column.key] || '-'}}
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    background
                    layout="total,prev,pager,next,jumper"
                    :current-page="tableQuery.currentPage"
                    :page-size="tableQuery.pageSize"
                    :total="tableQuery.totals"
                    @current-change="handlePageChange"
                    style=" justify-content: flex-end;margin-top: 20px;"
                />
            </div>
        </div>
        <UserDialog v-model:show="showUserDialog" :isRefund="isRefund" :row="refundRow" @success="success"></UserDialog>
    </el-card>
</template>

<style scoped lang="scss">
.temp-user-list-wrap{
    // height: calc(100vh); //layout padding 30*2 headHeight 48
    .top-box{
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search-box{
            text-align: right;
            margin: 10px 0 20px 0;
        }
    }
    .table-box{
    //    .ReadCount {
    //     color: rgba(8, 108, 224, 1);
    //     cursor: pointer;
    //    }
       .edit {
            cursor:pointer;
            color: rgba(8, 108, 224, 1);
            margin-right: 10px;
       }
    }
}
</style>
