<template>
    <div>
        <el-dialog :title="form.id ? '编辑酒品' : '添加酒品'" :visible.sync="dialogVisible" @close="reset">
            <div class="head-container" v-if="!form.id">
                <div class="tab_wrap">
                    <div class="tab" :style="{ '--index': form.source }">
                        <div class="item" v-for="(item, index) in tabs" :key="item.value"
                            :class="{ active: index == form.source }" @click="tabChange(item)">
                            {{ item.label }}
                        </div>
                    </div>
                </div>
            </div>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
                <template v-if="form.source == 0">
                    <el-form-item label="酒品名" prop="name">
                        <el-input v-model="form.name" placeholder="请输入酒品名" />
                    </el-form-item>
                    <el-form-item label="酒品图片">
                        <uploadImg ref="uploadImg" :limit="1" @success="e => form.imgUrl = e[0]"
                            @remove="form.imgUrl = ''" />
                    </el-form-item>
                </template>
                <template v-else>
                    <template v-if="!form.id">
                        <el-form-item label="选择商品" prop="name">
                            <div>
                                <el-button type="primary" icon="el-icon-plus"
                                    @click="$refs.shopListRef.show([...productIds])">
                                    添加商品
                                </el-button>
                            </div>
                            <div class="shop_list">
                                <div class="item_wrap" v-for="(item, index) in productIds" :key="item.id"
                                    @click="productIds.splice(index, 1)">
                                    <div class="item" :data-index="index + 1">
                                        <el-image :src="item.coverImg" style="width: 100%;height: 100%;"></el-image>
                                    </div>
                                    <div class="name">{{ item.name }}</div>
                                </div>
                            </div>
                        </el-form-item>
                    </template>
                    <template v-else>
                        <el-form-item label="商品">
                            <div class="goods_info">
                                <el-image :src="form.imgUrl" style="width: 50px;height: 50px;"></el-image>
                                <div class="info">{{ form.name }}</div>
                            </div>
                        </el-form-item>
                    </template>
                </template>
                <el-form-item label="单位">
                    <el-input v-model="form.unit" placeholder="请输入单位" style="width: 200px;" />
                    <!-- <el-select v-model="form.unitId" placeholder="请选择单位" style="width: 200px;" @change="selectUnitt">
                        <el-option :label="item.name" :value="item.id" v-for="item in units" :key="item.id"></el-option>
                    </el-select>
                    <el-button type="primary" plain icon="el-icon-plus"
                        @click="$refs.addUnitRef.show()">添加单位</el-button> -->
                </el-form-item>
                <el-form-item label="有效期(天)">
                    <el-input-number v-model="form.period" controls-position="right" step-strictly :min="1"
                        placeholder="请输入有效期(天)"></el-input-number>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onSubmitHandle">确 定</el-button>
            </span>
        </el-dialog>
        <addUnit ref="addUnitRef" @success="tbShopUnit" />
        <shopList ref="shopListRef" @success="slectShop" />
    </div>
</template>

<script>
import { tbShopStorageGood } from '@/api/application'
import { queryAllShopUser, tbShopUnit } from '@/api/shop'
import uploadImg from '@/components/uploadImg'
import addUnit from '@/views/product/components/addUnit'
import shopList from '@/components/shopList'
export default {
    components: {
        uploadImg,
        addUnit,
        shopList
    },
    data() {
        const nameValidator = (rule, value, callback) => {
            if (this.form.source == 0) {
                if (!this.form.name) {
                    callback(new Error('请输入酒名名'))
                } else {
                    callback()
                }
            } else {
                if (!this.productIds.length) {
                    callback(new Error('请选择商品'))
                } else {
                    callback()
                }
            }
        }
        return {
            dialogVisible: false,
            tabs: [
                {
                    value: 0,
                    label: '手动添加'
                },
                {
                    value: 1,
                    label: '从商品添加'
                }
            ],
            units: [],
            loading: false,
            options: [],
            productIds: [],
            form: {
                name: '',
                imgUrl: '',
                source: 0,
                id: '',
                goods: [
                    {
                        imgUrl: '',
                        name: '',
                    }
                ],
                period: '',
                unit: ''
            },
            resetForm: '',
            rules: {
                name: [
                    {
                        required: true,
                        validator: nameValidator,
                        trigger: 'change'
                    }
                ]
            }
        }
    },
    mounted() {
        this.resetForm = { ...this.form }
        // this.getTableData()
        this.tbShopUnit()
    },
    methods: {
        slectShop(res) {
            if (this.productIds.length) {
                res.map(async item => {
                    if (!await this.checkShop(item.id)) {
                        this.productIds.push({ ...item })
                    }
                })
            } else {
                this.productIds = res
            }
        },
        selectUnitt(e) {
            this.form.unit = this.units.find(item => item.id == e).name
        },
        // 获取单位
        async tbShopUnit() {
            try {
                const res = await tbShopUnit({
                    shopId: localStorage.getItem('shopId'),
                    sort: 'id',
                    page: 0,
                    size: 100
                })
                this.units = res.content
            } catch (error) { }
        },
        // 切换类型
        tabChange(item) {
            this.form.source = this.tabs.findIndex(i => i.value == item.value)
        },
        // 获取用户列表
        async getTableData(query = '') {
            this.loading = true
            try {
                const res = await queryAllShopUser({
                    telephone: query,
                })
                this.loading = false
                this.options = res.content
            } catch (error) {
                this.loading = false
                console.log(error)
            }
        },
        // 提交
        onSubmitHandle() {
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        if (this.form.source == 0) {
                            //  手动大导入
                            this.form.goods = [{
                                name: this.form.name,
                                imgUrl: this.form.imgUrl
                            }]
                        } else {
                            this.form.goods = this.productIds.map(item => {
                                return {
                                    name: item.name,
                                    imgUrl: item.coverImg
                                }
                            })
                        }
                        let res = await tbShopStorageGood(this.form, this.form.id ? 'put' : 'post')
                        this.$emit('success', res)
                        this.close()
                        this.$notify({
                            title: '成功',
                            message: `${this.form.id ? '编辑' : '添加'}成功`,
                            type: 'success'
                        });
                    } catch (error) {
                        console.log(error)
                    }
                }
            })
        },
        show(obj) {
            this.dialogVisible = true
            if (obj && obj.id) {
                this.form = obj
                if (obj.imgUrl && obj.source == 0) {
                    setTimeout(() => {
                        this.$refs.uploadImg.fileList = [
                            {
                                url: obj.imgUrl
                            }
                        ]
                    }, 100)
                }
            }
        },
        close() {
            this.dialogVisible = false
        },
        reset() {
            if (this.form.source == 0) {
                this.$refs.uploadImg.clearFiles()
            }
            this.form = { ...this.resetForm }
            this.$refs.form.resetFields()

        }
    }
}
</script>

<style scoped lang="scss">
.goods_info {
    background-color: #f9f9f9;
    padding: 10px;
    display: flex;
    align-items: center;

    .info {
        flex: 1;
        padding-left: 10px;
    }
}

.head-container {
    display: flex;
    justify-content: center;
}

.tab_wrap {
    background-color: #DCF0E8;
    padding: 4px;

    .tab {
        --w: 120px;
        height: 35px;
        display: flex;
        position: relative;


        &::after {
            content: "";
            width: var(--w);
            height: inherit;
            background-color: #39D47A;
            position: absolute;
            top: 0;
            left: calc(var(--index) * var(--w));
            z-index: 1;
            transition: left .3s ease-in-out;
        }

        .item {
            width: var(--w);
            height: inherit;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            z-index: 2;
            color: #39D47A;
            transition: all .1s ease-in-out .15s;

            &:hover {
                cursor: pointer;
            }

            &.active {
                color: #fff;
            }
        }
    }
}

.shop_list {
    display: flex;
    flex-wrap: wrap;

    .item_wrap {
        $size: 80px;

        .item {
            $radius: 4px;
            width: $size;
            height: $size;
            border-radius: $radius;
            overflow: hidden;
            position: relative;
            margin-right: 10px;
            margin-top: 10px;

            &:hover {
                cursor: pointer;
            }

            &::after {
                content: attr(data-index);
                font-size: 12px;
                height: 20px;
                display: flex;
                padding: 0 10px;
                border-radius: 0 0 $radius 0;
                align-items: center;
                background-color: rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(10px);
                color: #fff;
                position: absolute;
                top: 0;
                left: 0;
                z-index: 10;
            }

            &::before {
                content: '删除';
                font-size: 12px;
                width: 100%;
                height: 20px;
                display: flex;
                padding: 0 10px;
                align-items: center;
                justify-content: center;
                background-color: rgba(0, 0, 0, 0.3);
                backdrop-filter: blur(10px);
                color: #fff;
                position: absolute;
                bottom: 0;
                left: 0;
                z-index: 10;
                transition: all .1s ease-in-out;
            }
        }

        .name {
            width: $size;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
</style>