<template>
    <div class="lists">
        <el-card shadow="never" class="!border-none">
            <el-form :model="formData" inline>
                <el-form-item label="服务名称">
                    <el-input class="ls-input" v-model="formData.name" placeholder="请输入服务名称" />
                </el-form-item>
                <el-form-item label="服务分类">
                    <el-cascader
                        ref="cascaderRef"
                        class="ls-input"
                        v-model="formData.categoryId"
                        :options="categoryData"
                        :props="{
                            checkStrictly: true,
                            label: 'name',
                            value: 'id',
                            children: 'sons',
                            emitPath: false
                        }"
                        clearable
                        filterable
                        @change="handleChange"
                    />
                </el-form-item>
                <el-form-item>
                    <div class="m-l-20">
                        <el-button type="primary" @click="resetPage">查询</el-button>
                        <el-button @click="resetParams">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="never" class="mt-4 !border-none">
            <el-tabs class="-mt-2" v-model="formData.status" @tab-change="resetPage">
                <el-tab-pane :label="`全部(${countData?.allCount || '0'})`" name="" />
                <el-tab-pane :label="`销售中(${countData?.inSalesCount || '0'})`" :name="1" />
                <el-tab-pane :label="`仓库中(${countData?.warehouseCount || '0'})`" :name="0" />
            </el-tabs>

            <div class="mt-2">
                <el-button type="primary" @click="$router.push('lists/edit')">添加服务</el-button>
                <el-button @click="handleBatchEdit()">
                    {{ !isEdit ? '批量改价' : '保存' }}
                </el-button>
                <el-button @click="handleChangeStatus(selectionData, 0)" :disabled="!selectionData.length">批量上架</el-button>
                <el-button @click="handleChangeStatus(selectionData, 1)" :disabled="!selectionData.length">批量下架</el-button>
                <el-button @click="handleDelete(selectionData)" :disabled="!selectionData.length">批量删除</el-button>
            </div>

            <div class="mt-4">
                <el-table ref="tableData" :data="pager.lists" style="width: 100%" @selection-change="handleSelectionChange" v-loading="pager.loading">
                    <el-table-column type="selection" max-width="55" />
                    <el-table-column property="name" label="服务名称" min-width="220">
                        <template #default="scope">
                            <div class="flex items-center">
                                <div class="w-[60px] h-[60px]">
                                    <el-image
                                        style="width: 60px; height: 60px"
                                        :src="scope.row.image"
                                        :preview-src-list="[scope.row.image]"
                                        :hide-on-click-modal="true"
                                        :preview-teleported="true"
                                        :fit="'contain'"
                                    />
                                </div>
                                <el-tooltip :content="scope.row.name" placement="top">
                                    <div class="ml-2 truncate">{{ scope.row.name }}</div>
                                </el-tooltip>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="category" label="服务分类" min-width="145" />
                    <el-table-column property="price" label="前台价格" min-width="80">
                        <template #default="scope">
                            <el-input v-if="isEdit" v-model="scope.row.price" placeholder="请输入价格"></el-input>
                            <div v-if="!isEdit">¥{{ scope.row.price }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column property="scribingPrice" label="折前价格" min-width="80">
                        <template #default="scope">
                            <el-input v-if="isEdit" v-model="scope.row.scribingPrice" placeholder="请输入价格"></el-input>
                            <div v-if="!isEdit">{{ scope.row.scribingPrice ? '￥' + scope.row.scribingPrice : '' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column property="unit" label="单位" min-width="80" />
                    <el-table-column property="orderNum" label="预约人数" min-width="80" />
                    <el-table-column property="statusDesc" label="销售状态" min-width="80">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.status == 1">销售中</el-tag>
                            <el-tag type="info" v-if="scope.row.status == 0">仓库中</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="isNewRecommendName" label="新品推荐" min-width="80">
                        <template #default="scope">
                            <el-tag type="success" v-if="scope.row.isNewRecommend == 1">新品</el-tag>
                            <el-tag type="info" v-if="scope.row.isNewRecommend == 0">非新品</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column property="sort" label="排序" min-width="70" />
                    <el-table-column property="createTime" label="添加时间" min-width="160" />
                    <el-table-column property="address" label="操作" width="240" fixed="right">
                        <template #default="scope">
                            <div class="flex items-center">
                                <router-link
                                    class="mr-4"
                                    :to="{
                                        path: 'lists/edit',
                                        query: {
                                            id: scope.row.id
                                        }
                                    }"
                                >
                                    <el-link type="primary" :underline="false">详情</el-link>
                                </router-link>

                                <div class="mr-4">
                                    <el-link type="primary" :underline="false" @click="handleChangeStatus(scope.row.id, scope.row.status)">
                                        {{ !scope.row.status ? '立即上架' : '放入仓库' }}
                                    </el-link>
                                </div>

                                <div class="mr-4">
                                    <el-link
                                        type="primary"
                                        :underline="false"
                                        @click="handleChangeNewRecommend(scope.row.id, scope.row.isNewRecommend)"
                                    >
                                        {{ !scope.row.isNewRecommend ? '新品' : '非新品' }}
                                    </el-link>
                                </div>

                                <el-link type="danger" :underline="false" @click="handleDelete(scope.row.id)">删除</el-link>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists"></pagination>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="serviceList">
import {
    apiServiceLists,
    apiServiceDel,
    apiServiceStatus,
    apiServiceNewRecommend,
    apiServiceStatis,
    apiServicesBatchUpdatePrice
} from '@/api/service/lists'
import { apiCategoryCommonLists } from '@/api/service/category'
import { ref } from 'vue'
import Pagination from '@/components/pagination/index.vue'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'

interface formDataObj {
    name: string //服务名称
    status?: number | string //服务状态:1-销售中;0-仓库中
    categoryId: string
}

const isEdit = ref<boolean>(false)

// 表单数据
const formData = ref<formDataObj>({
    name: '',
    status: '',
    categoryId: ''
})

const getOrderAmount = async () => {
    countData.value = await apiServiceStatis({ ...formData.value, status: '' })
}

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: apiServiceLists,
    params: formData.value,
    nextFetchFun: getOrderAmount
})

// 选中的服务项目
const selectionData = ref<number[]>([])

// 服务分类下拉数据
const categoryData = ref([])
const cascaderRef = ref()

// 表格多选选择的数据
const handleSelectionChange = (val: Event | any) => {
    selectionData.value = val.map((item: Event | any) => item.id)
}

// 服务状态 存放仓库 || 立即上架
const handleChangeStatus = async (ids: number | Array<number>, status: number) => {
    status = status === 0 ? 1 : 0
    ids = Array.isArray(ids) ? ids : [ids]
    if (status === 0) {
        await feedback.confirm('确认放入仓库？请谨慎操作。')
    } else if (status === 1) {
        await feedback.confirm('确认上架？请谨慎操作。')
    }
    await apiServiceStatus({ ids, status })
    feedback.msgSuccess('操作成功')
    getLists()
    getOrderAmount()
}

// 服务状态 非新品 || 新品推荐
const handleChangeNewRecommend = async (ids: number | Array<number>, status: number) => {
    status = status === 0 ? 1 : 0
    ids = Array.isArray(ids) ? ids : [ids]
    if (status === 0) {
        await feedback.confirm('确认非新品？请谨慎操作。')
    } else if (status === 1) {
        await feedback.confirm('确认新品推荐？请谨慎操作。')
    }
    await apiServiceNewRecommend({ ids, status })
    feedback.msgSuccess('操作成功')
    getLists()
    getOrderAmount()
}

// 删除服务
const handleDelete = async (ids: number | Array<number>) => {
    ids = Array.isArray(ids) ? ids : [ids]
    await feedback.confirm('如果该服务已被师傅关联，此次操作也会同时删除师傅关联的服务项目，请谨慎操作。')
    await apiServiceDel({ ids })
    feedback.msgSuccess('操作成功')
    getLists()
    getOrderAmount()
}

// 批量编辑服务
const handleBatchEdit = async () => {
    console.log('isEdit:' + isEdit.value)
    // 如果当前为编辑状态则先发请求保存数据
    if (isEdit.value) {
        console.log('批量保存')
        console.log(pager.lists)
        await apiServicesBatchUpdatePrice({ goodsParams: pager.lists })
    }
    getLists()
    getOrderAmount()
    isEdit.value = !isEdit.value
}

// 获取分类通用列表
const getCategoryLists = async (): Promise<void> => {
    const res = await apiCategoryCommonLists()
    categoryData.value = res
}

// 记录级联选择器所选中的最后一个元素的id
const handleChange = () => {
    const node = cascaderRef.value.getCheckedNodes()
    console.log('id:', node[0])

    formData.value.categoryId = node[0]?.data.id
}

const countData = ref<any>({})

// getOrderAmount()
getLists()
getCategoryLists()

/**页面缓存 */
onActivated(() => {
    getLists()
})
</script>

<style lang="scss" scoped>
.lists {
    .el-radio-button__inner {
        padding: 8.5px 40px;
    }
}

.ls-input {
    width: 280px;
}

.el-tabs__nav-wrap::after {
    height: 1px !important;
}

:deep() .el-tabs__content {
    padding: 0;
}
</style>
