<template>
    <div class="page">
        <!-- data-list -->
        <div class="btn" @click="jump('/pages/manage/coupon/form')">
            新增优惠券
        </div>
        <div class="data-list">
            <div class="filter">
                <!-- <div >时间选择</div> -->
                <ul class="date-list">
                    <li @click="tabClick(0)" :class="{ on: activeTab === 0 }">
                        全店优惠券
                    </li>
                    <li @click="tabClick(1)" :class="{ on: activeTab === 1 }">
                        部分优惠券
                    </li>
                </ul>
                <ul class="date-list chart-view">
                    <li
                        :class="{ on: activestatus === 1 }"
                        @click="statusClick(1)"
                    >
                        进行中
                    </li>
                    <li
                        :class="{ on: activestatus === 0 }"
                        @click="statusClick(0)"
                    >
                        未开始
                    </li>
                    <li
                        :class="{ on: activestatus === 2 }"
                        @click="statusClick(2)"
                    >
                        已结束
                    </li>
                </ul>
            </div>
            <ul class="coupon-list">
                <li class="item" v-for="item of dataList" :key="item.id">
                    <div class="val name">
                        活动名称：{{ item.activityName }}
                    </div>
                    <div class="val">
                        <span class="k">优惠内容：</span> {{ item.name }}
                    </div>
                    <div class="val">
                        <span class="k">有效期：</span>
                        {{ item.startReceiveTime }}——{{ item.endReceiveTime }}
                    </div>
                    <div class="con">
                        <div class="val">
                            <span class="k">发放形式：</span
                            >{{ item.grantMethod ? "自行发放" : "公开发放" }}
                        </div>
                        <div class="val">
                            <span class="k">面向人群：</span
                            >{{ item.facingForCrowd | facingForCrowdFilter }}
                        </div>
                        <div class="val">
                            <span class="k">总数量：</span>{{ item.stock }}
                        </div>
                        <div class="val">
                            <span class="k">已发放：</span
                            >{{ item.total - item.stock }}
                        </div>
                        <div class="val">
                            <span class="k">已使用：</span>{{ item.usedCount }}
                        </div>
                        <div class="val">
                            <span class="k">是否有门槛：</span
                            >{{ item.noThreshold ? "无" : "有" }}
                        </div>
                    </div>
                    <div class="oper">
                        <span v-if="activestatus !== 2" @click="edit(item)"
                            >编辑</span
                        >
                        <span v-if="activestatus !== 2" @click="stopGrant(item)"
                            >停止发放</span
                        >
                        <span
                            :class="{ full: activestatus === 2 }"
                            @click="viewData(item)"
                            >查看数据</span
                        >
                        <span v-if="activestatus !== 2" @click="qrCode(item)"
                            >二维码</span
                        >
                        <span
                            v-if="activestatus !== 2 && activeTab === 1"
                            class="full"
                            @click="goodsSelect(item)"
                            >添加商品</span
                        >
                        <span
                            v-if="activestatus !== 2 && activeTab === 0"
                            class="full"
                            @click="goodsSelect(item)"
                            >设置不参与商品</span
                        >
                    </div>
                </li>
            </ul>
            <div class="empty-text" v-if="dataList.length === 0">无数据</div>
        </div>

        <div
            class="canvas"
            v-show="canvasShow"
            @touchmove.stop=""
            @click="closeCanvas"
        >
            <div class="canvas__content">
                <div class="canvas__close">
                    <img
                        class="canvas__img"
                        src="/static/live/close.png"
                        alt=""
                    />
                </div>
                <canvas
                    class="canvas__box"
                    canvas-id="canvas"
                    :disable-scroll="true"
                    @click.stop="viewImg()"
                ></canvas>
            </div>
        </div>
    </div>
</template>

<script>
import MyImage from "../../../components/image/index";

export default {
    name: "",
    components: { MyImage },
    filters: {
        facingForCrowdFilter(v) {
            switch (v) {
                case 0:
                    return "所有用户";
                case 2:
                    return "所有会员";
                case 3:
                    return "新人专享";

                default:
                    return "";
            }
        },
    },
    // 数据
    data() {
        return {
            activeTab: 0,
            activestatus: 1,
            pageIndex: 1,
            dataList: [],
            dataEnd: false,
            canvasShow: false,
            longPressActions: "",
            shopConfig:{}
        };
    },

    onLoad() {
        this.getConfig();
    },
    async onShow() {
        this.getList();
    },
    onReachBottom() {
        this.getListMore();
    },
    // 函数
    methods: {
        tabClick(v) {
            this.activeTab = v;
            this.getList();
        },
        statusClick(v) {
            this.activestatus = v;
            this.getList();
        },

        getConfig(){
            this.api.get('/Shop/GetConfig')
                .then(res=>{
                    let data = JSON.parse(res.data);
                    this.shopConfig = data;
                })
        },

        getList() {
            this.pageIndex = 1;
            this.dataEnd = false;
            let sendData = {
                storeId: this.user.storeId,
                type: this.activeTab,
                status: this.activestatus,
                pageIndex: this.pageIndex,
                pageSize: 20,
            };
            uni.showLoading({
                title: "加载中...",
            });
            this.api.get("/Coupon/GetList", sendData).then((res) => {
                uni.hideLoading();
                this.dataList = res.data.data;
            });
        },

        getListMore() {
            if (this.dataEnd) {
                return;
            }
            this.pageIndex++;
            let sendData = {
                storeId: this.user.storeId,
                type: this.activeTab,
                status: this.activestatus,
                pageIndex: this.pageIndex,
                pageSize: 20,
            };
            this.api.get("/Coupon/GetList", sendData).then((res) => {
                uni.hideLoading();
                this.dataList = [...this.dataList, ...res.data.data];
                if (res.data.data.length === 0) {
                    this.dataEnd = true;
                }
            });
        },

        edit(val) {
            this.router.push({
                path: "/pages/manage/coupon/edit-form",
                query: {
                    couponId: val.id,
                },
            });
        },

        stopGrant(val) {
            this.fn
                .showModal({
                    content: "确认停止发放该优惠券",
                })
                .then((res) => {
                    if (res.confirm) {
                        uni.showLoading({
                            title: "提交中...",
                            mask: true,
                        });
                        this.api
                            .post(
                                "/Coupon/StopGrant",
                                {
                                    query: true,
                                    id: val.id,
                                },
                                { pass: true }
                            )
                            .then((res) => {
                                uni.hideLoading();
                                if (res.success) {
                                    this.fn.showToast("操作成功");
                                    let arr = [];
                                    for (let item of this.dataList) {
                                        if (item.id !== val.id) {
                                            arr.push(item);
                                        }
                                    }
                                    this.dataList = arr;
                                } else {
                                    this.fn.showToast(
                                        "操作失败：" + res.message
                                    );
                                }
                            });
                    }
                });
        },

        viewData(val) {
            uni.showLoading({
                title: "加载中...",
                mask: true,
            });
            this.api
                .get("/Coupon/GetViewData", { couponId: val.id })
                .then((res) => {
                    uni.hideLoading();
                    this.fn.showActionSheet([
                        `支付订单金额：${res.data.payAmount / 100}`,
                        `支付成功用户数：${res.data.userCount}`,
                        `支付订单数：${res.data.orderCount}`,
                    ]);
                });
        },

        qrCode(val) {
            uni.showLoading({
                title: "加载中...",
                mask: true,
            });
            const self = this;
            const ctx = uni.createCanvasContext("canvas", self);
            let bg = "";
            //判断主题  1:红色  2：绿色
            if (this.shopConfig.theme === 1) {
                bg = "https://oss.ixiaokejia.com/images/common/red_coupon.png";
            } else {
                bg =
                    "https://oss.ixiaokejia.com/images/common/green_coupon.png";
            }
            let appLogo = this.shopConfig.logoUrl;
            let value = parseInt(val.value / 100);
            value = value > 100 ? "99+" : value;
            // let appName = this.user.appName;

            Promise.all([
                uni.getImageInfo({
                    src: bg,
                }),
                uni.getImageInfo({
                    src: appLogo,
                }),
                self.api
                    .get("/Share/GetQRCode", {
                        path: "pages/coupon/detail",
                        paremeters: JSON.stringify({
                            id: val.id,
                        }),
                        width: 355,
                    })
                    .then((res) => {
                        return uni.getImageInfo({
                            src: res.data,
                        });
                    }),
            ]).then((resList) => {
                console.log(resList);
                // 背景
                // ctx.setFillStyle("#fff");
                // ctx.fillRect(0, 0, 750, 1000);
                if (resList[0][1].path) {
                    ctx.drawImage(resList[0][1].path, 0, 0, 750, 1000);
                }

                // appLogo
                if (resList[1][1].path) {
                    ctx.drawImage(resList[1][1].path, 300, 24, 154, 154);
                }

                // // qrcode
                if (resList[2][1].path) {
                    ctx.drawImage(resList[2][1].path, 200, 350, 355, 355);
                }

                // value
                ctx.setFontSize(100);
                ctx.setFillStyle("#de0006");
                if (value === "99+") {
                    ctx.fillText(value, 285, 915);
                } else if (value < 10) {
                    ctx.fillText(value, 335, 915);
                } else {
                    ctx.fillText(value, 310, 915);
                }
                ctx.stroke();

                ctx.draw();
                self.canvasShow = true;
                // 生成临时路径
                setTimeout(() => {
                    uni.canvasToTempFilePath({
                        canvasId: "canvas",
                        fileType: "jpg",
                        success: function (res) {
                            self.canvasShow = false;
                            uni.hideLoading();
                            self.canvasImgPath = res.tempFilePath;
                            uni.previewImage({
                                urls: [self.canvasImgPath],
                                longPressActions: true,
                            });
                        },
                    });
                }, 100);
            });
        },
        viewImg() {
            let self = this;
            //查看图片
            uni.previewImage({
                urls: [self.canvasImgPath],
                longPressActions: true,
            });
        },

        goodsSelect(val) {
            this.router.push({
                path: "/pages/manage/coupon/goods-select",
                query: {
                    couponId: val.id,
                },
            });
        },
        // 关闭海报
        closeCanvas() {
            const self = this;

            self.canvasShow = false;
        },
    },

    // 数据计算
    computed: {
        user() {
            return this.$store.state.user.user;
        },
        token() {
            return this.$store.state.user.token;
        },
        curShop() {
            return this.$store.state.common.curShop;
        },
    },

    // 数据监听
    watch: {},
};
</script>

<style lang="scss" scoped>
.page {
    padding-bottom: px(50);
}
.data-list {
    background-color: #fff;
}
.filter {
    padding: px(30);
    .date-list {
        display: flex;
        justify-content: space-between;
        font-size: px(44);
        text-align: center;
        li {
            border: 1px solid #f1f1f1;
            padding: px(20) 0;
            width: 50%;
            flex-shrink: 0;
            &:first-child {
                border-radius: px(20) 0 0 px(20);
            }
            &:last-child {
                border-radius: 0 px(20) px(20) 0;
            }
            &.on {
                border-color: rgb(0, 188, 38);
                color: rgb(0, 188, 38);
            }
        }
    }

    .chart-view {
        width: 100%;
        margin: px(30) auto 0;
        border-radius: px(10);
        li {
            width: 33.333333%;
            &:first-child {
                border-radius: px(20) 0 0 px(20);
            }
            &:last-child {
                border-radius: 0 px(20) px(20) 0;
            }
        }
    }
}
.empty-text {
    text-align: center;
    padding: px(30);
    font-size: px(44);
    color: #999;
}
.link {
    color: #4395ff;
}
.coupon-list {
    .item {
        padding: px(35);
        border-bottom: 1px solid #f1f1f1;
    }
    .val {
        font-size: px(40);
        padding: px(5);
    }
    .con {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        .val {
            width: 50%;
        }
    }
    .k {
        color: #999;
    }
    .name {
        font-size: px(44);
        font-weight: 700;
        padding-bottom: px(10);
    }
}
.btn {
    margin: px(20) px(35);
    border-radius: px(20);
    height: px(120);
    background-color: #fff;
    border: 1px solid #f1f1f1;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
}
.oper {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    // border-top: 1px dashed #f1f1f1;
    margin-top: px(20);
    span {
        width: 50%;
        text-align: center;
        color: #1890ff;
        border: 1px dashed #f1f1f1;
        box-sizing: border-box;
        line-height: px(100);
    }
    .full {
        width: 100%;
    }
    span:nth-child(2n) {
        border-left: none;
    }
}
.canvas {
    position: fixed;
    top: -1000%;
    left: -1000%;
    z-index: -11;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    &__content {
        position: relative;
        width: 100%;
        height: 100%;
        padding: px(200) px(80) 0;
        z-index: 10;
    }

    &__close {
        position: absolute;
        top: px(50);
        right: px(120);
        z-index: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        width: px(100);
        height: px(100);
        border-radius: 50%;
        border: solid px(3) #fff;

        &:after {
            content: "";
            position: absolute;
            top: px(100);
            left: 50%;
            z-index: 1;
            display: block;
            width: px(3);
            height: px(50);
            transform: translateX(-50%);
            background-color: #fff;
        }
    }

    &__img {
        width: px(60);
        height: px(60);
    }

    &__box {
        width: 750px;
        height: 1000px;
        background-color: #fff;
    }
}
</style>