<script setup>
import { ref, reactive } from 'vue'
import { Search } from '@element-plus/icons-vue'
import {apiProductsConfig} from '@/api/products'
import { apiMediaCommon } from '@/api/media'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox  } from 'element-plus'
import editSingle from './components/editSingle.vue'
const router=useRouter()
const tableColumns = [
    {
        label:'产品名称',
        key:'ProductName',
        align: 'center',
        minwidthsty:250
    },
    {
        label:'产品类型',
        key:'ProductType',
        align:'center',
        widthsty:100,
    },
    {
        label:'商品价格',
        key:'Price',
        align: 'center',
        widthsty:120,
    },
    {
        label:'风险等级',
        key:'RiskLevel',
        align: 'center',
        widthsty:100,
    },{
        label:'状态',
        key:'SaleStatus',
        align: 'center',
        widthsty:120,
    },{
        label:'创建人',
        key:'Creator',
        align: 'center'
    },{
        label:'创建时间',
        key:'PublishedTime',
        sortable:true,
        align: 'center'
    },
    {
        label:'更新时间',
        key:'UpdatedTime',
        sortable:true,
        align: 'center'
    },
    {
        label:'操作',
        key:'handle',
        align: 'center'
    }
]
const options = ref([
    {
        value: 'report',
        label: '报告'
    }, {
        value: 'audio',
        label: '音频'
    }, {
        value: 'video',
        label: '视频'
    }
])
const saleStatusList = ref([
    {
        value: 'onSale',
        label: '已上架'
    }, {
        value: 'offSale',
        label: '未上架'
    }
])
const tableData = ref([])
const labelOptions = ref([])
const showModal = ref(false)
const productInfo = ref({})
const tableQuery = reactive({
    keyWord:'',
    currentPage:1,
    pageSize:10,
    totals:0,
    ProductType:'',
    SaleStatus:null,
    CreatedTime:'',
    UpdatedTime:'',
    SortColumn:'created_time',
    sortType:'desc',
})

function getTableData(){
    apiProductsConfig.getproductList({
        IsSingle:true, // 是否是单品
        KeyWord:tableQuery.keyWord,
        CurrentIndex:tableQuery.currentPage,
        PageSize:tableQuery.pageSize,
        ProductType:tableQuery.ProductType,
        CreatedTime:tableQuery.CreatedTime,
        UpdatedTime:tableQuery.UpdatedTime,
        SaleStatus:tableQuery.SaleStatus,
        SortType:tableQuery.sortType,
        SortColumn:tableQuery.SortColumn,
    }).then(res=>{
        if(res.Ret!==200) return 
        tableData.value = res.Data.List||[]
        tableQuery.totals = res.Data.Paging.Totals||0
    })
}

getTableData()
getLableList()

function getLableList(){
    apiMediaCommon.getPermissionList().then(res=>{
        if(res.Ret!==200) return
        labelOptions.value = res.Data.List||[]
    })
}
function handlePageChange(page){
    tableQuery.currentPage = page
    getTableData()
}
function handleSortChange({order,prop}){
    const propMap = {
        'PublishedTime':'created_time',
        'UpdatedTime':'updated_time',
    }
    tableQuery.SortColumn = propMap[prop]
    tableQuery.sortType = order==='ascending' ? 'asc': 'desc'
    getTableData()
}
function handleSelectChange() {
    getTableData();
}

// 操作
function operation(handle, row) {
    switch (handle) {
        case 'stock':
            apiProductsConfig.postUpdateSaleStatus({
                ProductId:row.Id,
                SaleStatus:'onSale'
            }).then(res=>{
                if(res.Ret!==200) return
                ElMessage.success('上架成功')
                getTableData()
            })
            break;
        case 'delist':
            apiProductsConfig.postUpdateSaleStatus({
                ProductId:row.Id,
                SaleStatus:'offSale'
            }).then(res=>{
                if(res.Ret!==200) return
                ElMessage.success('下架成功')
                getTableData()
            })
            break;
        case 'edit':
            console.log(row);
            row.Price = row.Price.split('￥').join("")
            console.log(row);
            
            productInfo.value = row
            showModal.value = true
            break;
        case 'delete':
            ElMessageBox.confirm(
                '删除产品后，该产品转为免费，不影响该产品的历史购买记录，确认删除吗?',
                '提示',
                {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                }
            )
                .then(() => {
                    apiProductsConfig.postDeleteProduct({
                        ProductId:row.Id,
                    }).then(res=>{
                        if(res.Ret!==200) return
                        ElMessage.success('删除成功')
                        getTableData()
                    })
                })
            break;
        default:
            return false;
    }
}
function closeEdit() {
    showModal.value = false
    getTableData();
}
</script>

<template>
    <el-card>
        <div class="temp-user-list-wrap">
            <div class="top-box">
                <div>
                    <el-button type="primary" style="margin-right: 20px;" @click="router.push('/products/addSingle')" v-permission="'single:add'">添加单品</el-button>
                    <el-select clearable v-model="tableQuery.ProductType" @change="handleSelectChange()" placeholder="产品类型" style="width: 200px; margin-right: 20px;">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <el-select v-model="tableQuery.SaleStatus" clearable @change="handleSelectChange()" placeholder="状态" style="width: 200px; margin-right: 20px;">
                        <el-option
                        v-for="item in saleStatusList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                    <el-date-picker
                        v-model="tableQuery.CreatedTime"
                        type="date"
                        placeholder="创建时间"
                        format="YYYY-MM-DD"
                        style="margin-right: 20px;"
                        value-format="YYYY-MM-DD"
                        @change="handlePageChange(1)"
                    />
                    <el-date-picker
                        v-model="tableQuery.UpdatedTime"
                        type="date"
                        placeholder="更新时间"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        @change="handlePageChange(1)"
                    />
                </div>
                <div class="search-box">
                    <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 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" :align="column.align" :width="column.widthsty"
                        :min-width="column.minwidthsty">
                        <template #default="scope" v-if="column.key === 'SaleStatus'">
                            <el-tag :type="scope.row[column.key]=== '已上架' ?'success':'info'">{{ scope.row[column.key] }}</el-tag>
                        </template>
                        <template #default="scope" v-else-if="column.key === 'handle'">
                            <span class="edit" v-if="scope.row.SaleStatus !== '已上架'" @click="operation('stock', scope.row)" v-permission="'single:stock'">上架</span>
                            <span class="edit" v-if="scope.row.SaleStatus === '已上架'"  @click="operation('delist', scope.row)" v-permission="'single:delist'">下架</span>
                            <span class="edit" v-if="scope.row.SaleStatus !== '已上架'" @click="operation('edit', scope.row)" v-permission="'single:edit'">编辑</span>
                            <span class="delete" v-if="scope.row.SaleStatus !== '已上架'" @click="operation('delete', scope.row)" v-permission="'single:delete'">删除</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: 50px;"
                />
            </div>
        </div>
        <editSingle v-model:show="showModal" :productInfo="productInfo" @close="closeEdit()"></editSingle>
    </el-card>
</template>

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