<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-option label="未上架/在售" value="10"></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%" :row-class-name="rowClassName">
                        <!-- 序号 -->
                        <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="210">
                            <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?.length && row?.priceDetail[0]?.memberDiscount || 0, 10)}}折
                                        <span class="c-333 f-w-5">（{{ row?.priceDetail?.length && row?.priceDetail[0]?.price }}）</span>
                                    </view>
                                </view>
                            </template>
                        </vxe-column>
                        <vxe-column title="检测项目" min-width="280">
                            <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="检测类型" width="80">
                            <template #default="{ row }">
                                {{ selectDictLabel(dm_test_type, row?.testType) }}
                            </template>
                        </vxe-column>
                        <vxe-column title="销量" field="orderedCount" width="80" :formatter="colNoData"></vxe-column>
                        <vxe-column title="开始时间" field="validFrom" width="110">
                            <template #default="{ row }">{{ row?.validFrom }}</template>
                        </vxe-column>
                        <vxe-column title="结束时间" field="validUntil" width="110">
                            <template #default="{ row }">{{ row?.validUntil }}</template>
                        </vxe-column>
                        <vxe-column title="剩余时间" field="restDay" width="80">
                            <template #default="{ row }">
                                <span v-if="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="90"></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>
                                    <el-button @click="delItem(row)" v-ifv-if 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 ref="codeImgRef" class="d-flex flex-cln j-c a-c">
            <div class="f-s-18 c-333 f-w-5 mb-16">{{ sharePkgName }}</div>
            <vue-qr ref="qrCode" :text="shareText" v-if="shareText" :size="260" margin="0"></vue-qr>
        </div>
        <div class="d-flex flex-cln pt-16">
            <el-button type="primary" @click="downloadQrCode">下载</el-button>
        </div>
    </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, deleteTestPackage } 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';
import html2canvas from 'html2canvas';
const base_url = import.meta.env.VITE_APP_PACKAGE_SHARE_URL;
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { dm_package_type, dm_permit_type, vip_level, dm_test_type } = toRefs<any>(proxy?.useDict('dm_package_type', 'dm_permit_type', 'vip_level', 'dm_test_type'));
const router = useRouter();
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    publicFlag: '1',
    status: '10',
});
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();
                getTabsCount();
            }
        }
    });
};
// 下架套餐
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();
                getTabsCount();
            }
        }
    });
};
// 复制套餐
const copyItem = async (row: any) => {
    await proxy.$modal.confirm('是否确认复制该套餐？')
    proxy.$modal.loading('复制中...');
    const res = await copyTestPackage(row?.id).finally(() => proxy.$modal.closeLoading());
    if (!res || res.code !== 200) return;
    proxy.$modal.msgSuccess('复制成功！');
    getList();
    getTabsCount();
};
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 = `${base_url}?id=${row?.id}`;
    sharePkgName.value = row?.name;
    shareDialog.value = true;
}
const qrCode = ref<any>(null)
const codeImgRef = ref<any>(null)
const downloadQrCode = () => {
    // console.log('下载二维码');
    html2canvas(codeImgRef.value, {
        useCORS: true,
        allowTaint: false,
        scale: 2
    }).then((canvas) => {
        const url = canvas.toDataURL('image/png')
        const a: any = document.createElement('a')
        //下载的文件名
        a.download = `${sharePkgName.value}.png`
        //url
        a.href = url
        //触发点击
        a.click()
    })
}
const rowClassName = ({ row }) => {
    if (new Date(row?.validUntil) <= new Date()) {
        return 'row-expired';
    }
}
const delItem = async (row: any) => {
    await proxy.$modal.confirm('是否确认删除该套餐？')
    proxy.$modal.loading('删除中...');
    await deleteTestPackage(row?.id).finally(() => proxy.$modal.closeLoading());
    proxy.$modal.msgSuccess('删除成功！');
    getList();
    getTabsCount();
};
onMounted(() => {
    getTabsCount();
    getList();
});
onActivated(() => {
    getTabsCount();
    getList();
});
</script>
<style lang="scss" scoped></style>
