<template>
    <div class="p-3">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln">
            <div class="pd-16 pb-4 border-bottom">
                <div class="f-s-20 c-333 f-w-7 mb-16">套餐管理</div>
                <div class="d-flex">
                    <div class="mr-40">
                        <el-button @click="router.push({ path: 'menus-form' })" type="primary">新增套餐</el-button>
                    </div>
                    <div class="flex1 ov-hd d-flex j-ed">
                        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto">
                            <el-form-item label="套餐名称：" prop="name">
                                <el-input v-model="queryParams.name" placeholder="请输入套餐名称关键字" clearable style="width: 180px"
                                    @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="套餐状态" prop="status">
                                <el-select style="width: 160px" v-model="queryParams.status" clearable placeholder="请选择套餐状态"
                                    @change="handleQuery">
                                    <el-option label="未上架" value="0"></el-option>
                                    <el-option label="在售" value="1"></el-option>
                                    <el-option label="已下架" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="制定规则" prop="permitType">
                                <el-select style="width: 160px" v-model="queryParams.permitType" clearable
                                    placeholder="请选择制定规则" @change="handleQuery">
                                    <el-option v-for="item in dm_permit_type" :key="item.value" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="创建人" prop="createByName">
                                <el-input v-model="queryParams.createByName" placeholder="请输入创建人关键字" clearable
                                    style="width: 160px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
            <div class="flex1 ov-hd pd-16 d-flex flex-cln">
                <searchTabs v-model="queryParams.publicFlag" @change="handleQuery" :list="tabs" key-label="name"
                    key-value="type" key-count="num"></searchTabs>
                <div class="pd-8"></div>
                <div class="flex1 ov-hd">
                    <vxe-table :loading="loading" border :data="list" min-height="0" max-height="100%">
                        <!-- 序号 -->
                        <vxe-column type="seq" fixed="left" width="60" title="序号" align="center" />
                        <vxe-column title="套餐名称" fixed="left" align="center" field="name" min-width="100"
                            :formatter="colNoData" />
                        <vxe-column title="适用对象" field="applyType" min-width="100">
                            <template #default="{ row }">
                                <view class="d-flex flex-cln" v-if="row?.permitType == '1'">
                                    <template v-for="(item, index) in row?.priceDetail" :key="index">
                                        <view>
                                            {{ item?.memberLevelName }}-{{ NP.times(item?.memberDiscount, 10) }}折
                                            <span class="c-333 f-w-5">（{{ item?.price }}）</span>
                                        </view>
                                    </template>
                                </view>
                                <view class="d-flex flex-cln" v-if="row?.permitType == '2'">
                                    <view>
                                        {{ row?.permitCpyNames?.join(',') }}-{{
                                            NP.times(row?.priceDetail[0]?.memberDiscount, 10) }}折
                                        <span class="c-333 f-w-5">（{{ row?.priceDetail[0]?.price }}）</span>
                                    </view>
                                </view>
                            </template>
                        </vxe-column>
                        <vxe-column title="检测项目" min-width="140">
                            <template #default="{ row }">
                                <view v-if="row?.items">
                                    {{ row?.items }}
                                    <el-button @click="queryRowItems(row)" type="primary" text>点击查看详情{{ '>' }}</el-button>
                                </view>
                                <view v-else>-</view>
                            </template>
                        </vxe-column>
                        <vxe-column title="检测周期" width="120">
                            <template #default="{ row }">{{ row?.period }}个工作日</template>
                        </vxe-column>
                        <vxe-column title="上架数量" field="totalCount" width="80" :formatter="colNoData"></vxe-column>
                        <vxe-column title="销量" field="orderedCount" width="80" :formatter="colNoData"></vxe-column>
                        <vxe-column title="开始时间" field="validFrom" width="160">
                            <template #default="{ row }">{{ row?.validFrom }}</template>
                        </vxe-column>
                        <vxe-column title="结束时间" field="validUntil" width="160">
                            <template #default="{ row }">{{ row?.validUntil }}</template>
                        </vxe-column>
                        <vxe-column title="剩余时间" field="restDay" width="100">
                            <template #default="{ row }">
                                <span v-if="row.status == 0">未上架</span>
                                <span v-if="row.status == 2"></span>
                                <span v-if="row.status == 1 && new Date(row?.validUntil ) > new Date()">
                                    {{Math.floor((new Date(row?.validUntil).getTime()-new Date().getTime())/(3600*24*1000))+1 }}天</span>
                                <span v-else>已过期</span>
                            </template>
                        </vxe-column>
                        <vxe-column title="创建人" field="createName" width="100"></vxe-column>
                        <vxe-column title="创建时间" field="createTime" width="160"></vxe-column>
                        <vxe-column title="套餐状态" align="center" width="90" fixed="right">
                            <template #default="{ row }">
                                <span v-if="+row?.status === 0" class="c-danger">未上架</span>
                                <span v-else-if="+row?.status === 1" class="c-primary">在售</span>
                                <span v-else-if="+row?.status === 2" class="c-999">已下架</span>
                            </template>
                        </vxe-column>
                        <vxe-column title="操作" fixed="right" width="260">
                            <template #default="{ row }">
                                <template v-if="+row?.status === 0">
                                    <el-button @click="putaway(row)" text type="primary">上架</el-button>
                                    <span></span>
                                    <el-button @click="router.push({ path: 'menus-form', query: { id: row?.id } })" text
                                        type="primary">编辑</el-button>
                                </template>
                                <template v-if="+row?.status === 1">
                                    <el-button @click="soldOut(row)" text type="danger">下架</el-button>
                                    <span></span>
                                    <el-button text type="primary" @click="showShareImg(row)">分享</el-button>
                                </template>
                                <template v-if="+row?.status === 2">
                                    <el-button @click="putaway(row)" text type="primary">上架</el-button>
                                    <span></span>
                                    <el-button text style="color: #999;" disabled>分享</el-button>
                                </template>
                                <span></span>
                                <el-button @click="copyItem(row)" text type="primary">复制</el-button>
                                <span></span>
                                <el-button @click="router.push({ path: 'menus-detail', query: { id: row?.id } })" text
                                    type="primary">详情</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
            </div>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />

        </div>
    </div>
    <el-dialog title="套餐分享" v-model="shareDialog" width="350px">
        <div class="d-flex flex-cln">
            {{ sharePkgName }}
            <el-button type="primary" @click="download">下载</el-button>
        </div>
        <vue-qr ref="qrCode" :text="shareText" v-if="shareText" :size="300"></vue-qr>
    </el-dialog>
    <rowItems v-if="showRowItems" v-model:show="showRowItems" :packageId="rowId"></rowItems>
</template>
<script setup name="Menus" lang="ts">
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import { copyTestPackage, testPackageList, testPackageListCount, testPackageSale, testPackageUnSale } from '@/api/cdt/menus';
import { colNoData } from '@/utils/noData';
import { searchTabs } from '@/views/models';
import NP from 'number-precision';
import { rowItems } from '../models';
import { debounce } from 'lodash';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { dm_package_type, dm_permit_type, vip_level } = toRefs<any>(proxy?.useDict('dm_package_type', 'dm_permit_type', 'vip_level'));
const router = useRouter();
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    publicFlag: '1'
});
const queryFormRef = ref<any>();
const showRowItems = ref(false);
const loading = ref(false);
const total = ref(0);
const list = ref<any>([]);
const getList = debounce(async () => {
    loading.value = true;
    const res = await testPackageList(queryParams.value);
    if (!res || res.code !== 200) return;
    list.value = res.rows;
    total.value = res.total;
    loading.value = false;
}, 500);
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
// 获取tabs统计数据
const tabs = ref<any[]>([]);
const getTabsCount = debounce(async () => {
    const params = { ...queryParams.value }
    params.publicFlag = ''
    const res = await testPackageListCount(params);
    if (!res || res.code !== 200) return;
    // this.tabsList = res.rows;
    tabs.value = res.data;
}, 500);
// 上架套餐
const putaway = async (row: any) => {
    console.log(row);
    ElMessageBox({
        title: '上架提示',
        showCancelButton: true,
        confirmButtonText: '确认上架',
        cancelButtonText: '取消',
        message: h('p', null, [h('div', null, `是否确认上架：${row?.name}`), h('div', { style: 'color: #2A6D52;' }, '上架后，即可分享并在小程序上显示该套餐！')]),
        callback: async (action: string) => {
            if (action === 'confirm') {
                proxy.$modal.loading('上架中...');
                const res = await testPackageSale(row?.id).finally(() => proxy.$modal.closeLoading());
                if (!res || res.code !== 200) return;
                proxy.$modal.msgSuccess('上架成功！');
                getList();
            }
        }
    });
};
// 下架套餐
const soldOut = async (row: any) => {
    console.log(row);
    ElMessageBox({
        title: '下架提示',
        showCancelButton: true,
        confirmButtonText: '确认下架',
        cancelButtonText: '取消',
        message: h('p', null, [h('div', null, `是否确认下架：${row?.name}`), h('div', { style: 'color: #F56C6C;' }, '下架后，该套餐将不再小程序上显示，已购买企业不受影响！')]),
        callback: async (action: string) => {
            if (action === 'confirm') {
                proxy.$modal.loading('下架中...');
                const res = await testPackageUnSale(row?.id).finally(() => proxy.$modal.closeLoading());
                if (!res || res.code !== 200) return;
                proxy.$modal.msgSuccess('下架成功！');
                getList();
            }
        }
    });
};
// 复制套餐
const copyItem = async (row: any) => {
    console.log(row);
    proxy.$modal.loading('复制中...');
    const res = await copyTestPackage(row?.id).finally(() => proxy.$modal.closeLoading());
    if (!res || res.code !== 200) return;
    proxy.$modal.msgSuccess('复制成功！');
    getList();
};
const rowId = ref('');
const queryRowItems = (row: any) => {
    rowId.value = row?.id;
    showRowItems.value = true;
};
//二维码分享
const shareText = ref('');
const sharePkgName = ref('');
const shareDialog = ref(false);
const showShareImg = (row) => {
    shareText.value = `http://dm.share.yujin.shuziyunyao.com/package?id=${row?.id}`;
    sharePkgName.value = row?.name;
    shareDialog.value = true;
}
const qrCode = ref<any>(null)
const download = () => {
    const a: any = document.createElement('a')
    // 下载的文件名
    a.download = `${sharePkgName.value}.png`
    // url
    a.href = qrCode.value.$el.src
    // 触发点击
    a.click()
}
onMounted(() => {
    getTabsCount();
    getList();
});
onActivated(() => {
    getTabsCount();
    getList();
});
</script>
