<template>
    <div class="page shop-cart-page" :class="{ page_red: theme === 1 }">
        <div class="page__top">
            <span class="quick-add" @click="jump('/pages/manage/add-good-form')"
                >新增</span
            >
            <div class="search">
                <i class="iconfont icontubiao- search__icon"></i>
                <input
                    class="search__text"
                    v-model="searchVal"
                    @confirm="search()"
                    type="text"
                    placeholder="搜索你想要的商品"
                />
                <i
                    class="iconfont iconclose_icon search__icon remove-icon"
                    @click="closeSearchVal"
                ></i>
            </div>
        </div>
        <div class="page__content">
            <div class="page__box">
                <scroll-view class="category" :scroll-y="true">
                    <ul class="category__list">
                        <li class="category__item item_one">
                            <!-- 未上架 -->
                            <switch
                                :checked="typeStatus === 1"
                                class="switch"
                                type="switch"
                                @change="switchChange"
                            />
                            <span>已上架</span>
                        </li>
                        <li
                            class="category__item"
                            :class="{
                                'category__item--active': categoryId === '',
                            }"
                            @click="setCategory('')"
                        >
                            全部
                        </li>
                        <li
                            class="category__item"
                            :class="{
                                'category__item--active':
                                    categoryId === item.id,
                            }"
                            v-for="(item, index) in categoryList"
                            :key="index"
                            @click="setCategory(item)"
                        >
                            {{ item.abbreviation || item.name }}
                        </li>
                    </ul>
                </scroll-view>
                <div class="page__right">
                    <div class="category-sub" v-if="subCategoryList.length">
                        <div class="category-sub__main">
                            <scroll-view
                                class="category-sub__scroll"
                                :scroll-x="true"
                            >
                                <ul class="category-sub__list">
                                    <li
                                        class="category-sub__item"
                                        :class="{
                                            'category-sub__item--active':
                                                subCategoryId === '',
                                        }"
                                        @click="setSubCategory('')"
                                    >
                                        全部
                                    </li>
                                    <li
                                        class="category-sub__item"
                                        :class="{
                                            'category-sub__item--active':
                                                subCategoryId === item.id,
                                        }"
                                        v-for="(item, index) in subCategoryList"
                                        :key="index"
                                        @click="setSubCategory(item)"
                                    >
                                        {{ item.abbreviation || item.name }}
                                    </li>
                                </ul>
                            </scroll-view>
                        </div>
                        <i
                            class="iconfont iconyoujiantou category-sub__toggle"
                            :class="{ active: categoryAllVisible }"
                            @click="categoryToggle"
                        ></i>
                    </div>
                    <div class="category-sub-all" v-if="categoryAllVisible">
                        <div
                            class="category-sub-all__bg"
                            @click="categoryToggle"
                        ></div>
                        <scroll-view
                            class="category-sub-all__scroll"
                            :scroll-y="true"
                        >
                            <ul class="category-sub-all__list">
                                <li
                                    class="category-sub-all__item"
                                    @click="setSubCategory('')"
                                    :class="{
                                        'category-sub-all__item--active':
                                            subCategoryId === '',
                                    }"
                                >
                                    全部
                                </li>
                                <li
                                    class="category-sub-all__item"
                                    v-for="(item, index) in subCategoryList"
                                    :key="index"
                                    @click="setSubCategory(item)"
                                    :class="{
                                        'category-sub-all__item--active':
                                            subCategoryId === item.id,
                                    }"
                                >
                                    {{ item.name }}
                                </li>
                            </ul>
                        </scroll-view>
                    </div>
                    <div class="goods">
                        <scroll-view
                            class="goods__scroll"
                            :scroll-y="true"
                            @scrolltolower="getMoreGoods"
                        >
                            <ul class="menu">
                                <li
                                    class="menu__item"
                                    :class="{
                                        'menu__item--active':
                                            sort === 'SaleDesc',
                                    }"
                                    @click="setSort('SaleDesc')"
                                >
                                    <div class="menu__text">销量</div>
                                </li>
                                <li
                                    class="menu__item"
                                    :class="{
                                        'menu__item--active':
                                            sort === 'NewDesc',
                                    }"
                                    @click="setSort('NewDesc')"
                                >
                                    <div class="menu__text">新品</div>
                                </li>
                                <li
                                    class="menu__item"
                                    :class="{
                                        'menu__item--active':
                                            sort === 'Price' ||
                                            sort === 'PriceDesc',
                                    }"
                                    @click="setSort('Price')"
                                >
                                    <div class="menu__text">价格</div>
                                    <div
                                        class="menu__sort"
                                        :class="{
                                            'menu__sort--up': sort === 'Price',
                                            'menu__sort--down':
                                                sort === 'PriceDesc',
                                        }"
                                    ></div>
                                </li>
                            </ul>
                            <ul class="goods__list">
                                <li
                                    class="goods__item"
                                    v-for="(item, index) in goodsList"
                                    :key="index"
                                >
                                    <div class="main">
                                        <my-image
                                            class="goods__img"
                                            :src="item.mainImage"
                                            @click="edit(item)"
                                        ></my-image>
                                        <div class="goods__info">
                                            <div class="goods__box">
                                                <div
                                                    class="goods__title"
                                                    @click="edit(item)"
                                                >
                                                    {{ item.name }}
                                                </div>
                                                <div
                                                    class="goods__sale"
                                                    @click="edit(item)"
                                                >
                                                    <span v-if="item.price">
                                                        价格：￥{{
                                                            item.price / 100
                                                        }}
                                                    </span>

                                                    <span v-if="item.stock">
                                                        库存：{{ item.stock }}
                                                    </span>
                                                </div>
                                            </div>
                                            <!-- <div
                                            class="goods__price"
                                            @click="edit(item)"
                                        >
                                            <div class="goods__present">
                                                价格：{{ "¥" + item.price / 100 }}
                                            </div>
                                            <div
                                                class="goods__original"
                                                v-if="item.stock !== 0"
                                            >
                                                库存：{{ "¥" + item.stock }}
                                            </div>
                                        </div> -->
                                            <!-- 登录 -->
                                        </div>
                                    </div>

                                    <div class="btns">
                                        <div class="btn" @click="sharePoster(item)">
                                            {{
                                                item.shareLoading
                                                    ? "生成中"
                                                    : "海报"
                                            }}
                                        </div>
                                        <div
                                            class="btn"
                                            @click="sendProduct(item, 'text')"
                                        >
                                            
                                            推荐链接
                                        </div>
                                        <div
                                            class="btn"
                                            @click="sendProduct(item, 'product')"
                                        >
                                            推荐商品
                                        </div>
                                        <div
                                            class="btn"
                                            @click="openMore(item)"
                                        >
                                            更多
                                        </div>
                                        <!-- <div
                                            class="btn"
                                            v-if="item.status === 0"
                                            @click="setStatus(item, 1)"
                                        >
                                            上架
                                        </div>
                                        <div
                                            class="btn"
                                            v-if="item.status === 1"
                                            @click="setStatus(item, 0)"
                                        >
                                            下架
                                        </div> -->
                                    </div>
                                </li>
                            </ul>
                            <div
                                class="more-text"
                                v-if="goodsList.length && !isHaveMore"
                            >
                                - 没有更多商品了 -
                            </div>
                            <div
                                class="null"
                                v-if="loading && !goodsList.length"
                            >
                                <img
                                    class="null__img"
                                    src="/static/common/goods_null.jpg"
                                    alt
                                />
                                <div class="null__title">
                                    抱歉！没有找到相关商品~
                                </div>
                            </div>
                        </scroll-view>
                    </div>
                </div>
            </div>
        </div>
        <!-- 单商品价格 -->
        <uni-popup ref="popup" type="dialog">
            <uni-popup-dialog
                mode="input"
                :title="'修改价格'"
                :content="rePriceText"
                :value="rePriceValue"
                placeholder="请输入修改后的价格"
                @confirm="setPriceConfirm"
            ></uni-popup-dialog>
        </uni-popup>
        <!-- 多规格商品价格 -->
        <uni-popup ref="popupPriceSkus" type="dialog">
            <uni-popup-spec
                mode="input"
                :title="'修改价格'"
                :content="rePriceText"
                :skuData="rePriceSkuData"
                :nameType="'price'"
                placeholder="请输入修改后的价格"
                @confirm="setSkusPriceConfirm"
            ></uni-popup-spec>
        </uni-popup>
        <!-- 单规格库存 -->
        <uni-popup ref="dialogPopup" type="dialog">
            <uni-popup-dialog
                mode="input"
                :title="'修改库存'"
                :content="reStockText"
                :value="reStockValue"
                placeholder="请输入修改后的库存"
                @confirm="setStockConfirm"
            ></uni-popup-dialog>
        </uni-popup>
        <!-- 多规格商品库存 -->
        <uni-popup ref="popupStockSkus" type="dialog">
            <uni-popup-spec
                mode="input"
                :title="'修改库存'"
                :content="reStockText"
                :skuData="reStockSkuData"
                :nameType="'stock'"
                placeholder="请输入修改后的库存"
                @confirm="setSkusStockConfirm"
            ></uni-popup-spec>
        </uni-popup>

        <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>

        <shop-select ref="shopSelect"></shop-select>
        
    </div>
</template>

<script>
import MyImage from "../../components/image/index";
import uniPopup from "../../components/uni-popup/uni-popup";
import uniPopupDialog from "../../components/uni-popup/uni-popup-dialog";
import uniPopupSpec from "../../components/uni-popup/uni-popup-spec";
import config from "../../common/js/config";
import MyShare from "../../components/share/index";
import ShopSelect from "./shop-select";
export default {
    name: "",
    components: { MyImage, uniPopup, uniPopupDialog, MyShare, uniPopupSpec,ShopSelect },
    // 数据
    data() {
        return {
            storeId: "",
            categoryId: "",
            categoryList: [],
            subCategoryId: "",
            subCategoryList: [],
            sort: "SaleDesc", // 排序
            page: 1, // 页码
            goodsList: [],
            isHaveMore: true, // 是否有更多数据
            loading: false, // 是否加载完成
            cartList: [],

            goods: null, // 详情数据 加入购物车时用
            cartNum: 0, // 购物车数量
            categoryAllVisible: false, // 分类全部显示
            shopId: "", //店铺id

            // 修改价格文字
            rePriceText: "",
            rePriceValue: "",
            rePriceData: {},
            rePriceSkuData: {},
            // 修改库存文字
            reStockText: "",
            reStockValue: "",
            reStockData: {},
            reStockSkuData: {},
            // 上下架状态
            typeStatus: 1,
            // 搜索
            searchVal: "",

            // 分享
            canvasShow: false,
            shareGood: {},
            shareRootLoading: false,
            shareLoadList: [],

            // other
            otherUrl: "https://bot.ixiaokejia.com/",
            shopList: null,

            curGood: null,
        };
    },

    onLoad() {
        const self = this;
        if (this.user.storeId) {
            this.storeId = this.user.storeId;
        }
    },

    async onShow() {
        this.getCategory();
    },

    onPullDownRefresh() {
        this.getCategory();
        this.getGoodsList();
    },

    onShareAppMessage() {
        const self = this;
        let obj = {
            ...self.$mp.query,
            storeId: self.$store.state.common.storeId,
        };
        return {
            path: self.router.getPath(self.$mp.page.route, obj),
        };
    },

    // 函数
    methods: {
        // 设置排序
        setSort(val) {
            const self = this;

            if (val === "Price") {
                self.sort = self.sort === "Price" ? "PriceDesc" : "Price";
            } else {
                self.sort = val;
            }

            self.getGoodsList();
        },

        // 获取商品分类
        getCategory() {
            const self = this;

            self.api
                .get("/Product/GetProductType", {
                    storeId: this.storeId,
                })
                .then((res) => {
                    if (res.data.length) {
                        self.categoryList = res.data;
                        for (let item of self.categoryList) {
                            if (item.name.length > 4) {
                                item.name = item.name.substr(0, 4) + "...";
                            }
                        }
                    }
                    this.getGoodsList();
                });
        },

        // 设置商品分类
        setCategory(val) {
            const self = this;
            this.categoryAllVisible = false;
            // this.searchVal = "";
            if (val === "") {
                // 仓库
                self.categoryId = "";
            } else {
                self.categoryId = val.id;
            }
        },

        // 设置商品二级分类
        setSubCategory(val) {
            const self = this;
            if (val === "") {
                self.subCategoryId = "";
            } else {
                self.subCategoryId = val.id;
            }

            self.getGoodsList();
        },

        // 获取商品列表
        getGoodsList() {
            const self = this;
            self.page = 1;
            let sendData = {
                storeId: this.storeId,
                sort: self.sort,
                pageIndex: self.page,
                pageSize: 20,
                type: self.subCategoryId || self.categoryId,
                status: this.typeStatus,
                keyword: this.searchVal || "",
            };

            uni.showLoading({
                title: "加载中...",
            });
            self.api.get("/Product/GetList", sendData).then((res) => {
                uni.hideLoading();
                uni.stopPullDownRefresh();
                if (res.data.data.length) {
                    self.page++;
                    self.isHaveMore = true;
                } else {
                    self.isHaveMore = false;
                }

                self.goodsList = res.data.data;
                self.loading = true;
                uni.hideLoading();
            });
        },

        // 获取更多商品
        getMoreGoods() {
            const self = this;
            if (!this.isHaveMore) {
                return;
            }
            let sendData = {
                storeId: this.storeId,
                sort: self.sort,
                pageIndex: self.page,
                pageSize: 20,
                type: self.subCategoryId || self.categoryId,
                status: this.typeStatus,
            };
            self.api.get("/Product/GetList", sendData).then((res) => {
                if (res.data.data.length) {
                    self.page++;
                } else {
                    self.isHaveMore = false;
                }

                self.goodsList = self.goodsList.concat(res.data.data);
            });
        },

        // 分类展开切换
        categoryToggle() {
            this.categoryAllVisible = !this.categoryAllVisible;
        },

        // 获取二级分类
        getSubCategory(id) {
            let flag = true;
            for (let item of this.categoryList) {
                if (item.id === id && item.children) {
                    flag = false;
                    this.subCategoryList = item.children;
                }
            }
            if (flag) {
                this.subCategoryList = [];
            }
            this.subCategoryId = "";
            this.getGoodsList();
        },

        // 搜索
        search() {
            if (this.searchVal) {
                // this.categoryId = "";
                // this.subCategoryId = "";
                // this.subCategoryList = [];
                this.getGoodsList();
            }
        },

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

        // 上下架状态切换
        switchChange(e) {
            this.typeStatus = e.detail.value ? 1 : 0;
            this.getGoodsList();
        },

        // 上下架
        setStatus(val, status) {
            this.api
                .post("/Product/EditStatus", {
                    id: val.id,
                    status,
                })
                .then((res) => {
                    if (res.success) {
                        for (let item of this.goodsList) {
                            if (item.id === val.id) {
                                item.status = status;
                            }
                        }
                        this.goodsList = [...this.goodsList];
                    } else {
                        this.fn.showModal({
                            content: "修改失败：" + res.message,
                            showCancel: false,
                        });
                    }
                });
        },

        // 改价
        setPrice(val) {
            uni.showLoading({
                title: "加载中...",
            });
            this.api.get("/Product/Detail", { id: val.id }).then((res) => {
                uni.hideLoading();
                console.log(res.data);
                if (!res.data.skuInfo) {
                    // 单商品
                    this.rePriceText = val.name;
                    this.rePriceValue = val.price / 100;
                    this.rePriceData = val;
                    this.$refs.popup.open({
                        type: "dialog",
                    });
                } else {
                    // 多商品
                    this.rePriceData = res.data;
                    this.rePriceText = val.name;
                    let data = JSON.parse(res.data.skuInfo);
                    for (let item of data.skus) {
                        item.price /= 100;
                    }
                    this.rePriceSkuData = data;
                    this.$refs.popupPriceSkus.open({
                        type: "dialog",
                    });
                }
            });
        },

        setPriceConfirm(done, value) {
            if (value) {
                let num = Number(value);
                if (isNaN(num)) {
                    this.fn.showToast("请输入正确的价格");
                    return;
                }
                num *= 100;
                num = parseInt(num);
                this.api
                    .post("/Product/UpPrice", {
                        id: this.rePriceData.id,
                        price: num,
                    })
                    .then((res) => {
                        if (res.success) {
                            this.fn.showToast("修改成功");
                            for (let item of this.goodsList) {
                                if (item.id === this.rePriceData.id) {
                                    item.price = num;
                                }
                            }
                            done();
                        } else {
                            this.fn.showToast("修改失败");
                        }
                    });
            } else {
                this.fn.showToast("请输入修改后的价格");
            }
        },

        setSkusPriceConfirm(done, value) {
            console.log(value);
            for (let item of value.skus) {
                item.price = parseInt(Number(item.price) * 100);
            }
            this.rePriceData.skuInfo = JSON.stringify(value);
            this.api.post("/product/SaveEdit", this.rePriceData).then((res) => {
                if (res.success) {
                    this.fn.showToast("修改成功");
                    done();
                } else {
                    this.fn.showToast("修改失败");
                }
            });
        },

        // 改库存
        setStock(val) {
            uni.showLoading({
                title: "加载中...",
            });
            this.api.get("/Product/Detail", { id: val.id }).then((res) => {
                uni.hideLoading();
                console.log(res.data);
                if (!res.data.skuInfo) {
                    // 单商品
                    this.reStockText = val.name;
                    this.reStockValue = val.stock;
                    this.reStockData = val;
                    this.$refs.dialogPopup.open({
                        type: "dialog",
                    });
                } else {
                    // 多商品
                    this.reStockData = res.data;
                    this.reStockText = val.name;
                    let data = JSON.parse(res.data.skuInfo);
                    this.reStockSkuData = data;
                    this.$refs.popupStockSkus.open({
                        type: "dialog",
                    });
                }
            });
        },

        setStockConfirm(done, value) {
            if (value) {
                let num = Number(value);
                if (isNaN(num)) {
                    this.fn.showToast("请输入正确的库存");
                    return;
                }
                this.api
                    .post("/Product/UpStock", {
                        id: this.reStockData.id,
                        stock: num,
                    })
                    .then((res) => {
                        if (res.success) {
                            this.fn.showToast("修改成功");
                            for (let item of this.goodsList) {
                                if (item.id === this.reStockData.id) {
                                    item.stock = num;
                                }
                            }
                            done();
                        } else {
                            this.fn.showToast("修改失败");
                        }
                    });
            } else {
                this.fn.showToast("请输入修改后的库存");
            }
        },

        setSkusStockConfirm(done, value) {
            // console.log(value);
            for (let item of value.skus) {
                item.stock = Number(item.stock);
            }
            this.reStockData.skuInfo = JSON.stringify(value);
            this.api.post("/product/SaveEdit", this.reStockData).then((res) => {
                if (res.success) {
                    this.fn.showToast("修改成功");
                    done();
                } else {
                    this.fn.showToast("修改失败");
                }
            });
        },

        shareLoading(id, status) {
            for (let item of this.goodsList) {
                if (item.id === id) {
                    item.shareLoading = status;
                }
            }
            this.goodsList = [...this.goodsList];
        },

        // 分享
        sharePoster(val) {
            console.log(val,111)
            if (val.shareLoading) {
                return;
            }
            if (this.shareRootLoading) {
                this.shareLoadList.push(val);
            }
            this.shareRootLoading = true;
            const self = this;
            this.shareLoading(val.id, true);
            // uni.showLoading({
            //     title: "加载中...",
            //     mask:true
            // });
            this.api.get("/Product/Detail", { id: val.id }).then((res) => {
                this.shareGood = res.data;
                // uni.hideLoading();
                // self.$refs.share.open("", "", "", () => {
                //     self.canvasShow = false;
                // });
                this.saveImage("single");
            });
        },
        // 获取换算成画布使用的像素
        getPx(size) {
            let windowWidth = uni.getSystemInfoSync().windowWidth || 414;
            let multiple = (windowWidth / 1080) * (920 / 670);
            size = size * multiple;

            return Number(size.toFixed(2));
        },
        // 创建分享图
        creationShare() {
            const self = this;
            const ctx = uni.createCanvasContext("canvas", self);

            // uni.showLoading({
            //     title: "正在生成海报",
            //     mask:true
            // });
            return new Promise((resolve) => {
                self.router.getScene(self.$mp.query).then((res) => {
                    Promise.all([
                        uni.getImageInfo({
                            src:
                                this.user.appLogo ||
                                self.config.imageResourceUrl +
                                    "images/common/avatar.png",
                        }),
                        uni.getImageInfo({
                            src: self.shareGood.baseInfo.mainImage,
                        }),
                        // 获取小程序吗
                        self.api
                            .get("/Share/GetQRCode", {
                                path: "pages/goods/detail",
                                paremeters: JSON.stringify({
                                    goodsId: self.shareGood.baseInfo.id,
                                    storeId: self.shareGood.baseInfo.storeId,
                                }),
                            })
                            .then((res) => {
                                return uni.getImageInfo({
                                    src: res.data,
                                });
                            }),
                    ]).then((res) => {
                        // 背景
                        ctx.setFillStyle("#fff");
                        ctx.fillRect(0, 0, self.getPx(670), self.getPx(1080));

                        // 头像
                        if (res[0][1].path) {
                            let avatarurl_width = self.getPx(70);
                            let avatarurl_heigth = self.getPx(70);
                            let avatarurl_x = self.getPx(30);
                            let avatarurl_y = self.getPx(40);
                            ctx.save();
                            ctx.beginPath();
                            ctx.arc(
                                avatarurl_width / 2 + avatarurl_x,
                                avatarurl_heigth / 2 + avatarurl_y,
                                avatarurl_width / 2,
                                0,
                                Math.PI * 2,
                                true
                            );
                            ctx.clip();
                            ctx.drawImage(
                                res[0][1].path,
                                avatarurl_x,
                                avatarurl_y,
                                avatarurl_width,
                                avatarurl_heigth
                            );
                            ctx.restore();
                        }

                        // 昵称
                        ctx.setFontSize(self.getPx(28));
                        ctx.setFillStyle("#333");
                        ctx.fillText(
                            self.user.appName,
                            self.getPx(115),
                            self.getPx(90)
                        );
                        ctx.stroke();

                        // 商品图片
                        ctx.drawImage(
                            res[1][1].path,
                            self.getPx(0),
                            self.getPx(145),
                            self.getPx(670),
                            self.getPx(670)
                        );

                        // 商品标题，第一行
                        let goodsName = self.shareGood.baseInfo.name;

                        if (goodsName.length > 12) {
                            goodsName = goodsName.substr(0, 12);
                        }
                        ctx.setFontSize(self.getPx(28));
                        ctx.setFillStyle("#333");
                        ctx.fillText(
                            goodsName,
                            self.getPx(50),
                            self.getPx(880)
                        );
                        ctx.stroke();

                        // 商品标题，第二行
                        let goodsName2 = self.shareGood.baseInfo.name;
                        if (goodsName2.length > 12) {
                            goodsName2 = goodsName2.substr(12, 10) + "...";

                            ctx.setFontSize(self.getPx(28));
                            ctx.setFillStyle("#333");
                            ctx.fillText(
                                goodsName2,
                                self.getPx(50),
                                self.getPx(920)
                            );
                            ctx.stroke();
                        }

                        // 商品描述，第一行
                        let descName =
                            self.shareGood.baseInfo.description || "";

                        if (descName.length > 14) {
                            descName = descName.substr(0, 14);
                        }
                        ctx.setFontSize(self.getPx(24));
                        ctx.setFillStyle("#666");
                        ctx.fillText(descName, self.getPx(50), self.getPx(965));
                        ctx.stroke();

                        // 商品描述，第二行
                        let descName2 =
                            self.shareGood.baseInfo.description || "";
                        if (descName2.length > 14) {
                            descName2 = descName2.substr(14, 14) + "...";

                            ctx.setFontSize(self.getPx(24));
                            ctx.setFillStyle("#666");
                            ctx.fillText(
                                descName2,
                                self.getPx(50),
                                self.getPx(995)
                            );
                            ctx.stroke();
                        }

                        // 商品价格符号
                        ctx.setFontSize(self.getPx(20));
                        ctx.setFillStyle("#f8662a");
                        ctx.fillText("¥", self.getPx(50), self.getPx(1050));
                        ctx.stroke();

                        // 商品价格
                        ctx.setFontSize(self.getPx(40));
                        ctx.setFillStyle("#f8662a");
                        ctx.fillText(
                            self.shareGood.baseInfo.price / 100,
                            self.getPx(65),
                            self.getPx(1050)
                        );
                        ctx.stroke();

                        // 小程序吗
                        ctx.drawImage(
                            res[2][1].path,
                            self.getPx(460),
                            self.getPx(850),
                            self.getPx(170),
                            self.getPx(170)
                        );

                        // 长按扫码购买
                        ctx.setFontSize(self.getPx(24));
                        ctx.setFillStyle("#999");
                        ctx.fillText(
                            "长按扫码购买",
                            self.getPx(470),
                            self.getPx(1050)
                        );
                        ctx.stroke();

                        ctx.draw();

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

        // 关闭海报
        closeCanvas() {
            const self = this;

            self.canvasShow = false;
        },
        // 创建多张分享图
        creationShares(url) {
            const self = this;
            const ctx = uni.createCanvasContext("canvas", self);

            return new Promise((resolve) => {
                self.router.getScene(self.$mp.query).then((res) => {
                    Promise.all([
                        uni.getImageInfo({
                            src:
                                this.user.avatar ||
                                self.config.imageResourceUrl +
                                    "images/common/avatar.png",
                        }),
                        uni.getImageInfo({
                            src: url,
                        }),
                        uni.getImageInfo({
                            src:
                                self.config.imageResourceUrl +
                                "resource/share/recognition.jpg",
                        }),
                        // 获取小程序吗
                        self.api
                            .get("/Share/GetQRCode", {
                                path: "pages/goods/detail",
                                paremeters: JSON.stringify({
                                    goodsId: self.shareGood.baseInfo.id,
                                    storeId: self.shareGood.baseInfo.storeId,
                                }),
                            })
                            .then((res) => {
                                return uni.getImageInfo({
                                    src: res.data,
                                });
                            }),
                    ]).then((res) => {
                        // 背景
                        ctx.setFillStyle("#fff");
                        ctx.fillRect(0, 0, self.getPx(670), self.getPx(1080));

                        // 头像
                        if (res[0][1].path) {
                            let avatarurl_width = self.getPx(70);
                            let avatarurl_heigth = self.getPx(70);
                            let avatarurl_x = self.getPx(30);
                            let avatarurl_y = self.getPx(40);
                            ctx.save();
                            ctx.beginPath();
                            ctx.arc(
                                avatarurl_width / 2 + avatarurl_x,
                                avatarurl_heigth / 2 + avatarurl_y,
                                avatarurl_width / 2,
                                0,
                                Math.PI * 2,
                                true
                            );
                            ctx.clip();
                            ctx.drawImage(
                                res[0][1].path,
                                avatarurl_x,
                                avatarurl_y,
                                avatarurl_width,
                                avatarurl_heigth
                            );
                            ctx.restore();
                        }

                        // 昵称
                        ctx.setFontSize(self.getPx(28));
                        ctx.setFillStyle("#333");
                        ctx.fillText(
                            self.user.nickName + "分享一件好物给你~",
                            self.getPx(115),
                            self.getPx(90)
                        );
                        ctx.stroke();

                        // 商品图片
                        ctx.drawImage(
                            res[1][1].path,
                            self.getPx(0),
                            self.getPx(145),
                            self.getPx(670),
                            self.getPx(670)
                        );

                        // 底部图片
                        ctx.drawImage(
                            res[2][1].path,
                            self.getPx(30),
                            self.getPx(880),
                            self.getPx(400),
                            self.getPx(120)
                        );

                        // 小程序吗
                        ctx.drawImage(
                            res[3][1].path,
                            self.getPx(460),
                            self.getPx(850),
                            self.getPx(170),
                            self.getPx(170)
                        );

                        // 长按扫码购买
                        ctx.setFontSize(self.getPx(24));
                        ctx.setFillStyle("#999");
                        ctx.fillText(
                            "长按扫码购买",
                            self.getPx(470),
                            self.getPx(1050)
                        );
                        ctx.stroke();

                        ctx.draw();

                        self.canvasShow = true;
                        uni.hideLoading();
                        setTimeout(() => {
                            // 生成临时路径
                            uni.canvasToTempFilePath({
                                canvasId: "canvas",
                                fileType: "jpg",
                                success: function (res) {
                                    resolve(res.tempFilePath);
                                },
                            });
                        }, 100);
                    });
                });
            });
        },
        // 保存图片到相册
        async saveImage(type) {
            const self = this;
            const good = this.shareGood;
            if (type === "single" && !self.canvasHandleStatus) {
                // 分享图
                self.canvasHandleStatus = true;
                // 获取用户设置
                uni.getSetting({
                    success(res) {
                        if (
                            res.authSetting["scope.writePhotosAlbum"] === false
                        ) {
                            //用户拒绝权限打开设置界面
                            self.fn
                                .showModal({
                                    title: "图片保存失败",
                                    content:
                                        "需要你打开允许使用“相册”权限，才能成功保存图片",
                                    confirmText: "去设置",
                                })
                                .then((res) => {
                                    if (res.confirm) {
                                        self.canvasHandleStatus = false;
                                        self.shareEnd();
                                        self.fn.openSetting();
                                    } else {
                                        self.shareLoading(
                                            good.baseInfo.id,
                                            false
                                        );
                                    }
                                });
                        } else {
                            // 生成分享图
                            self.creationShare().then((res) => {
                                // 保存分享图到相册
                                uni.saveImageToPhotosAlbum({
                                    filePath: res,
                                    success: function () {
                                        self.shareLoading(
                                            good.baseInfo.id,
                                            false
                                        );
                                        self.shareEnd();
                                        self.fn.showToast("海报保存成功");
                                    },
                                    complete: function () {
                                        // self.shareLoading(
                                        //     good.baseInfo.id,
                                        //     false
                                        // );
                                        self.canvasHandleStatus = false;
                                        // self.shareEnd();
                                    },
                                });
                            });
                        }
                    },
                });
            } else {
                // 素材图
                let setting = await uni.getSetting();

                if (
                    setting[1].authSetting["scope.writePhotosAlbum"] === false
                ) {
                    //用户拒绝权限打开设置界面
                    self.fn
                        .showModal({
                            title: "图片保存失败",
                            content:
                                "需要你打开允许使用“相册”权限，才能成功保存图片",
                            confirmText: "去设置",
                        })
                        .then((res) => {
                            if (res.confirm) {
                                self.fn.openSetting();
                            }
                        });
                } else if (!self.canvasHandleStatus) {
                    let imageList = self.shareGood.images;
                    let num = imageList.length;

                    self.canvasHandleStatus = true;
                    uni.showLoading({
                        title: "正在生成海报",
                    });

                    for (let i = 0; i < num; i++) {
                        let url = await self.creationShares(imageList[i]);

                        // 保存分享图到相册
                        uni.saveImageToPhotosAlbum({
                            filePath: url,
                            complete: function () {
                                if (i + 1 === num) {
                                    self.canvasHandleStatus = false;
                                    self.canvasShow = false;
                                    self.fn.showModal({
                                        title:
                                            "已经保存" +
                                            num +
                                            "张商品素材图到手机相册可在相册直接查看",
                                        showCancel: false,
                                        confirmText: "我知道了",
                                    });
                                }
                            },
                        });
                    }
                }
            }
        },

        shareEnd() {
            this.shareRootLoading = false;
            if (this.shareLoadList.length > 0) {
                let val = this.shareLoadList[0];
                this.shareLoadList.splice(0, 1);
                this.shareLoadList = [...this.shareLoadList];
                val.shareLoading = false;
                this.sharePoster(val);
            }
        },

        closeSearchVal() {
            this.searchVal = "";
            this.getGoodsList();
        },

        openMore(item) {
            let arr = [];
            if (item.status === 0) {
                arr.push("上架");
            } else {
                arr.push("下架");
            }
            arr = [...arr, "改价", "改库存", "跨店复制"];
            uni.showActionSheet({
                itemList: arr,
                success: (res) => {
                    switch (res.tapIndex) {
                        case 0:
                            if (item.status === 0) {
                                this.setStatus(item, 1);
                            } else {
                                this.setStatus(item, 0);
                            }
                            break;
                        case 1:
                            this.setPrice(item);
                            // this.sendProduct(item, "text");
                            break;
                        case 2:
                            this.setStock(item);
                            // this.sendProduct(item, "product");
                            break;
                        case 3:
                            this.copyProductsPlay(item);
                            break;
                    }
                },
            });
        },

        sendProduct(item, type) {
            let sendData = {
                pid: item.id,
                storeId: item.storeId,
            };
            if (type === "text") {
                sendData.sendTxt = false;
                sendData.sendVideo = false;
                sendData.sendImg = 0;
            } else {
                // sendData.sendTxt = true;
                // sendData.sendVideo = true;
                // sendData.sendImg = 3;
            }

            this.api
                .get(this.otherUrl + "Home/sendproduct", sendData, {
                    pass: true,
                })
                .then((res) => {
                    this.fn.showToast(res.message);
                });
        },

        copyProductsPlay(item) {
            if(!this.isAdmin){
                return this.fn.showToast('非管理员无权操作！');
            }
            if (!this.shopList) {
                this.getShopList(item);
            } else {
                this.copyProducts(item);
            }
        },

        getShopList(item) {
            uni.showLoading({
                title: "加载中...",
            });
            this.api.get("/Store/GetShopList").then((res) => {
                uni.hideLoading();
                for(let item of res.data){
                    item.label = item.name;
                    item.value = item.id;
                }
                this.shopList = res.data;
                this.copyProducts(item);
            });
        },

        copyProducts(good) {
            this.curGood = good;
            this.$refs.shopSelect.open(good,this.shopList)
        },
    },

    // 数据计算
    computed: {
        // 判断主题  1:红色  2：绿色
        theme() {
            return this.$store.state.common.theme;
        },
        user() {
            return this.$store.state.user.user;
        },
        isAdmin() {
            //店铺管理员  系统管理员
            if (
                this.user.roleId === "50c41c5d-b54c-43ed-b587-10dcb60e72e5" ||
                this.user.roleId === "75b71b24-25de-40ac-a866-c8f5555b8b92"
            ) {
                return true;
            } else {
                return false;
            }
        },
    },

    // 数据监听
    watch: {
        categoryId(val) {
            const self = this;
            self.getSubCategory(val);
        },
    },
};
</script>

<style>
page {
    height: 100%;
    background-color: #fff;
}
</style>

<style lang="scss" scoped>
.page {
    display: flex;
    flex-direction: column;
    height: 100%;

    &__top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: px(145);
        padding: 0 px(50);
        background-color: #fff;
        // box-shadow: 0 px(-5) px(10) #333;
    }

    &__content {
        position: relative;
        flex: 1;
        margin-top: px(5);
    }

    &__box {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1;
        display: flex;
        justify-content: space-between;
    }

    &__right {
        display: flex;
        flex-direction: column;
        flex: 1;
        position: relative;
    }
}

.search {
    display: flex;
    align-items: center;
    width: 100%;
    height: px(86);
    padding: 0 px(35);
    background-color: #f8f8f8;
    border-radius: px(43);

    &__icon {
        margin-top: px(10);
        font-size: px(60);
        color: #999;
    }

    &__text {
        margin-left: px(15);
        font-size: px(36);
        color: #999;
        width: 100%;
    }
}

.service {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    &__icon {
        font-size: px(50);
        color: #666;
    }

    &__text {
        font-size: px(30);
        color: #666;
    }
}

.category {
    width: px(225);
    height: 100%;
    background-color: #f8f6f7;

    &__item {
        position: relative;
        display: flex;
        justify-content: center;
        font-size: px(40);
        color: #888;
        background-color: #f8f6f7;
        padding: px(60) 0;

        &--active {
            // font-weight: 700;
            color: #333;
            background-color: #fff;
            &:before {
                content: "";
                position: absolute;
                top: 50%;
                left: 0;
                z-index: 1;
                display: block;
                width: px(8);
                height: 100%;
                transform: translateY(-50%);
                border-radius: px(4);
                background-color: #27a34f;
            }
        }
    }
}

.category-sub {
    position: relative;
    height: px(130);
    background-color: #fff;
    margin-right: px(140);
    margin-left: px(20);
    &__scroll {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 1;
    }

    &__list {
        display: flex;
        align-items: center;
        height: 100%;
    }

    &__toggle {
        position: absolute;
        top: 0;
        right: px(-140);
        z-index: 2;
        width: px(140);
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: px(30);
        transform: rotate(90deg);
        &.active {
            transform: rotate(-90deg);
        }
    }

    &__item {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        flex: none;
        height: 100%;
        font-size: px(34);
        width: px(220);
        color: #333;
        height: px(70);
        border-radius: px(35);
        background-color: #f6f6f6;
        border: 1px solid #f6f6f6;
        color: #888;
        margin: 0 px(10);
        &--active {
            color: #262626;
            background-color: rgba(39, 163, 79, 0.2);
            border: 1px solid #27a34f;
            color: #27a34f;
        }
    }
}

.category-sub-all {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 100%;
    z-index: 10;
    margin-top: px(130);
    &__bg {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
    }
    &__scroll {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 10;
    }
    &__list {
        display: flex;
        flex-wrap: wrap;
        background-color: #fff;
        padding: px(60) px(40);
    }
    &__item {
        display: flex;
        align-items: center;
        justify-content: center;
        flex: none;
        height: 100%;
        font-size: px(34);
        width: px(220);
        color: #333;
        height: px(70);
        border-radius: px(35);
        background-color: #f6f6f6;
        border: 1px solid #f6f6f6;
        color: #888;
        margin: 0 px(20) px(30);
        flex-shrink: 0;
        &--active {
            color: #262626;
            background-color: rgba(39, 163, 79, 0.2);
            border: 1px solid #27a34f;
            color: #27a34f;
        }
    }
}

.goods {
    position: relative;
    flex: 1;
    border-top: 1px solid #f6f6f6;

    &__scroll {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 1;
        background-color: #fff;
    }

    &__list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        padding: px(35) 0 0 0;
        background-color: #fff;
        border-top: 1px solid #f6f6f6;
    }

    &__item {
        width: 100%;
        margin-bottom: px(60);
        border-bottom: 1px solid #f1f1f1;
    }
    .main {
        width: 100%;
        overflow: hidden;
        // border-radius: px(20) px(20) 0 0;
        display: flex;
        justify-content: space-between;
        padding: 0 px(35);
    }

    &__img {
        flex-shrink: 0;
        margin-right: px(30);
        /deep/ img {
            width: px(230);
            height: px(230);
        }
    }

    &__info {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        align-items: flex-start;
        position: relative;
        width: 100%;
    }

    &__box {
        width: 100%;
    }
    &__title {
        width: 100%;
        @include omits(2);
        max-height: px(88);
        line-height: px(44);
        margin-top: px(30);
        font-size: px(36);
        color: #333;
    }

    &__price {
        // margin-top: px(30);
    }
    &__sale {
        font-size: px(32);
        line-height: px(40);
        color: #999;
        margin-top: px(20);
        span ~ span {
            margin-left: px(20);
        }
    }

    &__present {
        font-size: px(36);
        color: #000;
        font-weight: 600;
    }

    &__original {
        position: relative;
        font-size: px(30);
        color: #999;
        margin-top: px(20);
        text-decoration: line-through;
        &:after {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            z-index: 1;
            width: 100%;
            height: px(1);
            transform: translateY(-100%);
            background-color: #999;
        }
    }
    .btns {
        overflow: visible;
        // position: absolute;
        // bottom: 0;
        // right: 0;
        // z-index: 1;
        width: 100%;
        display: flex;
        align-items: center;
        max-width: 100%;
        border-top: 1px solid #f1f1f1;
        margin-top: px(20);
    }
    .btn {
        width: 25%;
        height: px(100);
        line-height: px(100);
        // background-color: #27a34f;
        color: #333;
        font-size: px(40);
        padding: 0 px(20);
        text-align: center;
        & ~ .btn {
            border-left: 1px solid #f1f1f1;
        }
    }
    .cart-num {
        // padding: px(30) px(10) px(10) px(30);
        padding: 0 px(30);
        box-sizing: border-box;
        min-width: px(60);
    }
    .num-input {
        overflow: visible;
        position: absolute;
        bottom: 0;
        right: 0;
        z-index: 1;
    }

    &__remove {
        background-color: #fff;
        width: px(60);
        height: px(60);
        border-radius: 50%;
        border: 1px solid #999;
        position: relative;
        &::after {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 1;
            width: 60%;
            height: px(6);
            border-radius: px(6);
            background: #999;
            transform: translate(-50%, -50%);
        }
    }
}

.menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: px(110);
    margin-bottom: px(5);
    padding: 0 px(85);
    background-color: #fff;
    // box-shadow: 0 px(-5) px(10) #333;

    &__item {
        display: flex;
        align-items: center;
    }

    &__text {
        font-size: px(36);
        color: #888;
    }

    &__item--active &__text {
        color: #27a34f;
    }

    &__sort {
        margin-left: px(15);

        &:before {
            display: block;
            content: "";
            width: 0;
            height: 0;
            margin-bottom: px(10);
            border-width: px(12);
            border-style: solid;
            border-color: transparent transparent #ccc transparent;
        }

        &:after {
            display: block;
            content: "";
            width: 0;
            height: 0;
            border-width: px(12);
            border-style: solid;
            border-color: #ccc transparent transparent transparent;
        }

        &--up:before {
            border-color: transparent transparent #27a34f transparent;
        }

        &--down:after {
            border-color: #27a34f transparent transparent transparent;
        }
    }
}

.more-text {
    display: flex;
    justify-content: center;
    padding-bottom: px(60);
    font-size: px(34);
    color: #999;
}

.null {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-top: px(115);

    &__img {
        width: px(576);
        height: px(281);
    }

    &__title {
        margin-top: px(60);
        font-size: px(40);
        color: #666;
    }
}

.page_red {
    /deep/ {
        .category {
            &__item {
                &--active {
                    &:before {
                        background-color: #fe6661;
                    }
                }
            }
        }
        .category-sub {
            &__item {
                &--active {
                    background-color: rgba(254, 102, 97, 0.2);
                    border: 1px solid #fe6661;
                    color: #fe6661;
                }
            }
        }
        .category-sub-all {
            &__item {
                &--active {
                    color: #262626;
                    background-color: rgba(254, 102, 97, 0.2);
                    border: 1px solid #fe6661;
                    color: #fe6661;
                }
            }
        }
        .goods {
            &__add-text {
                background-color: #fe6661;
            }
            &__add {
                background-color: #fe6661;
                box-shadow: px(1) px(2) px(6) #fe6661;
            }
        }

        .menu {
            .menu__item--active .menu__text {
                color: #fe6661;
            }

            &__sort {
                &--up:before {
                    border-color: transparent transparent #fe6661 transparent;
                }

                &--down:after {
                    border-color: #fe6661 transparent transparent transparent;
                }
            }
        }
    }
}
.item_one {
    border-bottom: 3px solid #c9c9c9;
    background-color: #efefef;
    padding: px(20) 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.switch {
    transform: scale(0.7);
}
.canvas {
    position: fixed;
    top: -100%;
    left: -100%;
    z-index: -11;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    visibility: hidden;
    &__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: px(920);
        height: px(1483);
        background-color: #fff;
    }
}
.remove-icon {
    padding-left: px(20);
}
.quick-add {
    font-size: px(44);
    color: rgb(0, 188, 38);
    flex-shrink: 0;
    margin-right: px(30);
}

</style>