<template>
    <div class="content safe-area-inset-bottom">
        <div class="header">
            <u-navbar
                :background="{ backgroundColor: '#ffcb57' }"
                :border-bottom="false"
                title="发布订单"
                title-color="#472d21"
            ></u-navbar>
        </div>
        <div class="card">
            <u-card :show-head="false">
                <view slot="body" class="ahHead">
                    <view class="left">
                        <span class="title">{{ displayServiceType }}</span>
                    </view>
                    <view class="right">
                        <u-button size="mini" hover-class="defaultBtnhover" @click="chooseServiceType"
                            >选择类目</u-button
                        >
                    </view>
                </view>
                <!-- <view slot="body" class="ahBody">
                <u-radio-group v-model="mode" active-color="#ffcb57" wrap size="45">-->
                <!-- <u-radio name="一口价下单" shape="circle">
                            <view class="mainT">一口价下单</view>
                            <view class="desc">下单后支付相应的订单金额，师傅接单马上与客户预约上门服务</view>
                </u-radio>-->
                <!-- <u-radio name="报价后下单" shape="circle">
                            <view class="mainT">报价后下单</view>
                            <view class="desc">下单后让师傅给您报价，您选择合适的师傅为您服务</view>
                </u-radio>-->
                <!-- <u-radio name="悬赏下单" shape="circle">
                            <view class="mainT">悬赏下单</view>
                            <view class="desc last">下单后价格由您决定，师傅接单后直接预约客户上门服务</view>
                </u-radio>-->
                <!-- </u-radio-group>
                </view>-->
            </u-card>
            <view class="empty">
                <u-button size="mini" @click="addGood">添加商品</u-button>
                <u-button size="mini" @click="chooseTemplate">选择商品模板</u-button>
            </view>
            <Good
                v-for="item in goods"
                :key="item.guid"
                :guid="item.guid"
                :source="item"
                :canbeDelete="showDeleteBtn"
                @delete="deleteGood"
                :goodTypesSource="goodTypes"
                @change="handleGoodChange"
            />
        </div>
        <u-picker
            mode="selector"
            title="请选择服务类目"
            v-model="showServiceTypes"
            :range="serviceTypes"
            range-key="label"
            @confirm="changeServiceType"
            confirm-color="#ffcb57"
        ></u-picker>
        <u-toast ref="uToast" />
        <view class="mc-btn">
            <u-button
                :custom-style="{ margin: '16rpx 30rpx', backgroundColor: '#ffcb57', color: '#472d21' }"
                hover-class="defaultBtnhover"
                :loading="loading"
                @click="next"
                >下一步</u-button
            >
        </view>
    </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex';
import request from '../../common/service';
import Good from '@/components/good/index';
export default {
    components: {
        Good,
    },
    data() {
        return {
            mode: '报价后下单',
            goods: [],
            showServiceTypes: false,
            serviceTypes: [],
            serviceType: null,
            loading: false,
            templates: [],
            isAdding: false,
            goodTypes: [],
        };
    },
    computed: {
        ...mapGetters({
            userDetail: 'user/userDetail',
            attachOrders: 'publish/templates',
            currentOrder: 'order/currentOrder',
        }),
        displayServiceType() {
            if (!this.serviceType) {
                return '请选择服务类目';
            }
            return `${this.serviceType.label}`;
        },
        showDeleteBtn() {
            return this.goods.length > 1;
        },
    },
    watch: {
        serviceType() {
            this.goods = [
                {
                    guid: this.$u.guid(),
                },
            ];
        },
    },
    async onLoad(options) {
        console.log(this.currentOrder);
        this.getServiceTypes();
        if (options.type && options.type === 'payAgain') {
            this.serviceType = {
                value: this.currentOrder.FServiceItemID.Id,
                label: this.currentOrder.FServiceItemID.Name[0].Value,
                number: this.currentOrder.FServiceItemID.Number,
            };
            this.getGoodTypes(this.serviceType.label);
            for (let i = 0; i < this.currentOrder.CustOrderGoodsMould.length; i++) {
                const good = this.currentOrder.CustOrderGoodsMould[i];
                const { FGoodsMouldImagesEntity } = good;
                if (!FGoodsMouldImagesEntity || FGoodsMouldImagesEntity.length === 0) {
                    good.thumbs = [
                        '//img13.360buyimg.com/n7/jfs/t1/103005/7/17719/314825/5e8c19faEb7eed50d/5b81ae4b2f7f3bb7.jpg',
                    ];
                } else {
                    good.thumbs = [];
                    for (let j = 0; j < FGoodsMouldImagesEntity.length; j++) {
                        const imgItem = FGoodsMouldImagesEntity[j];
                        const result = await this.getImageUrl(imgItem.FGoodsImage);
                        good.thumbs.push(result[0].fileurl);
                    }
                }
                this.goods.push({
                    guid: this.$u.guid(),
                    goodType: {
                        value: good.FGoodsType.Id,
                        label: good.FGoodsType.Name[0].Value,
                        number: good.FGoodsType.Number,
                    },
                    category: {
                        value: good.FServiceTypeID.Id,
                        label: good.FServiceTypeID.Name[0].Value,
                        number: good.FServiceTypeID.Number,
                    },
                    // sku: good.FGoodsSpecs,
                    mark: good.FTools,
                    thumbs: good.thumbs.map((x) => {
                        return {
                            url: x,
                        };
                    }),
                });
            }
        } else {
            this.goods.push({
                guid: this.$u.guid(),
            });
        }
    },
    onShow() {
        if (!this.isAdding) {
            return;
        }
        const _t = this;
        // 移除空白商品模板
        this.goods = this.goods.filter((x) => x.goodType && x.thumbs.length !== 0);
        // 插入选择的商品模板数据
        this.attachOrders.forEach((od) => {
            const guid = _t.$u.guid();
            _t.goods.push({
                guid,
                goodType: {
                    value: od.FGoodsTypeID.Id,
                    label: od.FGoodsTypeID.Name[0].Value,
                    number: od.FGoodsTypeID.Number,
                },
                // sku: od.FModel,
                mark: od.Description,
                thumbs: od.CustGoodsMouldImagesURL.map((x) => {
                    return {
                        url: x.fileurl,
                        fileid: x.fileid,
                    };
                }),
            });
        });
        this.isAdding = false;
    },
    updated() {},
    methods: {
        ...mapActions({
            updatePublishDetail: 'publish/updatePublishDetail',
        }),
        addGood() {
            if (!this.serviceType) {
                this.$refs.uToast.show({
                    title: '请先选择类目',
                });
                this.showServiceTypes = true;
                return;
            }
            this.goods.push({
                guid: this.$u.guid(),
            });
        },
        getServiceTypes() {
            request.get('/api/BaseData/ServiceItem').then((res) => {
                const { code, result } = res;
                if (code === 0) {
                    this.serviceTypes = result.map((x) => {
                        return {
                            value: x.id,
                            label: x.name,
                            number: x.number,
                            price: x.price,
                        };
                    });
                }
            });
        },
        changeServiceType(e) {
            const { currentCardIndex } = this;
            this.serviceType = this.serviceTypes[e[0]];
            this.getGoodTypes(this.serviceType.label);
        },
        chooseServiceType() {
            this.showServiceTypes = true;
        },
        getGoodTypes(servicename) {
            request.get('/api/BaseData/GoodsType', { serviceitem: servicename }).then((res) => {
                const { code, result } = res;
                if (code === 0) {
                    this.goodTypes = result.map((x) => {
                        return {
                            value: x.id,
                            label: x.name,
                            number: x.number,
                        };
                    });
                }
            });
        },
        async getImageUrl(value) {
            const res = await request.get('/api/UploadAttachments/GetUrl', { fileid: value });
            return res.result;
        },
        checkIfCompleteness(good, index) {
            const { goodType, category, count, thumbs } = good;
            if (!goodType || !category || !count || thumbs.length === 0) {
                return false;
            }
            return true;
        },
        next() {
            const { serviceType, goods } = this;
            if (!serviceType) {
                this.$refs.uToast.show({
                    title: '请先选择类目',
                });
                this.showServiceTypes = true;
            }
            if (!goods.some((item, index) => this.checkIfCompleteness(item, index))) {
                this.$refs.uToast.show({
                    title: '请先完善必填项',
                });
                return;
            }
            this.updatePublishDetail({
                FServiceItemID: {
                    FNUMBER: serviceType.number, //服务类目编码
                },
                FBusinessID: {
                    FNumber: this.userDetail.Number,
                },
                //商品模板
                FGoodsMouldEntity: goods.map((good, idx) => {
                    return {
                        FGoodsType: {
                            FNUMBER: good.goodType.number,
                        },
                        FServiceTypeID: {
                            FNUMBER: good.category.number,
                        },
                        FGoodsQty: good.count,
                        // FGoodsSpecs: good.sku,
                        FAmount: good.totalAmount,
                        FTools: good.mark,
                        FGoodsMouldImagesEntity: good.thumbs.map((file) => {
                            return {
                                FGoodsImage: file.fileid
                                    ? file.fileid
                                    : this.GetQueryString(file.url, 'filename').split('.')[0],
                            };
                        }),
                    };
                }),
            }).then(() => {
                this.$u.route('/pages/customer/index');
            });
        },
        chooseTemplate() {
            if (!this.serviceType) {
                this.$refs.uToast.show({
                    title: '请先选择类目',
                });
                this.showServiceTypes = true;
                return;
            }
            this.$u.route('/pages/good-template/choose/index', {
                id: this.serviceType.value,
            });
        },
        deleteGood(guid) {
            const idx = this.goods.findIndex((x) => x.guid === guid);
            this.goods.splice(idx, 1);
        },
        handleGoodChange(value) {
            const idx = this.goods.findIndex((x) => x.guid === value.guid);
            this.goods[idx] = value.data;
        },
        GetQueryString(url, name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = url.split('?')[1].substr(1).match(reg);
            if (r != null) return r[2];
            return null;
        },
    },
    onShareAppMessage(res) {
        if (res.from === 'button') {
            // 来自页面内分享按钮
            console.log(res.target);
        }
        return {
            title: '京台分享更多精彩',
            path: '/pages/index/index',
            imageUrl: '/static/images/share/WechatIMG96.png'
        };
    },
};
</script>

<style lang="scss" scoped>
.content {
    .header {
        background-color: #ffcb57;
    }
    .card {
        .ahHead {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .left {
                display: flex;
                align-items: center;
                .title {
                    margin-left: 6rpx;
                    font-size: 28rpx;
                    color: #262626;
                }
            }
        }
        .ahBody {
            .mainT {
                font-size: 32rpx;
                color: #262626;
            }
            .desc {
                position: relative;
                margin: 6rpx 0 12rpx 0;
                font-size: 24rpx;
                color: #8c8c8c;
                // &::after {
                //     content: '';
                //     display: block;
                //     margin: 16rpx 0 12rpx 0;
                //     width: 100%;
                //     border-bottom: 2rpx dashed #bfbfbf;
                // }
                &.last {
                    &::after {
                        display: none;
                    }
                }
            }
        }
        .goodBd {
            .chooseBtn {
                padding-bottom: 24rpx;
            }
        }
        .goodFt {
            .price {
                display: flex;
                justify-content: flex-end;
                align-content: center;
                .unit,
                .amount {
                    font-size: 36rpx;
                    color: red;
                }
                .amount {
                    margin-right: 32rpx;
                }
            }
            .delete {
                margin-top: 12rpx;
                padding-top: 24rpx;
                border-top: 2rpx dashed #bfbfbf;
            }
        }
        .u-body-item {
            font-size: 32rpx;
            color: #333;
            padding: 0rpx 10rpx;
            .right {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                width: 400rpx;
                flex: 0 0 400rpx;
                height: 120rpx;
                border-radius: 8rpx;
                margin-left: 12rpx;
                .extra-content {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }
        }
        .empty {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16rpx 32rpx;
        }
    }
    .defaultBtnhover {
        color: '#472d21';
    }
}
</style>
