<template>
    <div class="container">
        <el-form :model="formData" :rules="rules" ref="form" label-width="80px" label-position="right" size="small" style="max-width: 800px;">

            <!-- <el-form-item prop="storeId" label="店铺">
                <el-input v-model="formData.storeId" :disabled="'storeId'==subColumn"></el-input>
            </el-form-item> -->
            <el-form-item prop="typeFlag" label="类型" style="max-width:400px">
                <template>
                    <el-select v-model="formData.typeFlag" clearable placeholder="请选择">
                        <el-option v-for="item in typeFlagOptions" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </template>
            </el-form-item>

            <!-- <el-form-item prop="serviceType" label="服务大类">
                <el-select v-model="formData.serviceType" filterable placeholder="请选择" size="small">
                    <el-option v-for="item in serviceTypes" :key="item.id" :label="item.shortName" :value="item.id">
                    </el-option>
                </el-select>

            </el-form-item>

            <el-form-item prop="subclass" label="服务小类">
                <el-select v-model="formData.subclass" filterable placeholder="请选择" size="small">
                    <el-option v-for="item in serviceTypeDetails[formData.serviceType]" :key="item.id" :label="item.typeName" :value="item.id">
                    </el-option>
                </el-select>

            </el-form-item> -->

            <el-form-item prop="title" label="标题" style="max-width:400px">
                <el-input v-model="formData.title" :disabled="'title'==subColumn"></el-input>
            </el-form-item>
            <el-form-item prop="image" label="商品主图">
                <single-upload v-model="formData.image" :disabled="'image'==subColumn"></single-upload>
                <span style="color:#999;font-size:12px;">最佳尺寸 352*200</span>
            </el-form-item>
            <el-form-item prop="serviceDetail" label="服务详情" style="max-width:400px">
                <el-input type="textarea" v-model="formData.serviceDetail" :disabled="'serviceDetail'==subColumn"></el-input>
            </el-form-item>
            <el-form-item prop="inventory" label="库存" style="max-width:400px">
                <!-- <el-input v-model="formData.inventory" :disabled="'inventory'==subColumn"></el-input> -->
                <el-input-number v-model="formData.inventory" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item prop="price" label="默认价格">
                <el-input-number v-model="formData.price" :min="0"></el-input-number>
                <template v-if="levelNum.length<3">
                    <el-button type="danger" icon="el-icon-plus" @click="addLevel" circle plain size="mini" style="margin-left:20px"></el-button>
                    <span style="font-size:12px;color:#999;margin-left:5px;">添加梯级价格</span>

                </template>
                <span style="font-size:12px;color:rgb(255, 73, 73);margin-left:5px;">(阶梯价格提交时，最后一项的最大值会自动清空)</span>

                <el-table v-if="levelNum.length>0" :data="levelNum" style="width: 100%">
                    <el-table-column prop="name" label="名称" align="center">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.name" size="mini" style="width:100%"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="价格" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.price" :min="0" size="mini" style="width:100%"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="minCounts" label="最小值" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.minCounts" :disabled="true" size="mini" :min="getMini(scope.$index)" style="width:100%"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="maxCounts" label="最大值" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.maxCounts" @change='changeLevel(scope.$index)' size="mini" :min="scope.row.minCounts+1" style="width:100%"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="maxCounts" label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="danger" @click="delLevel(scope.$index)" icon="el-icon-delete" circle plain size="mini"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="商品详情">
                <rich-text :height='500' v-model="formData.productDetail"></rich-text>
                <!-- <el-upload :action="url" :file-list="fileList" list-type="picture-card" :on-success="handleSuccess" :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                </el-upload> -->
                <span style="color:#999;font-size:12px;">最佳尺寸 宽度大于1150px 高度不限</span>
            </el-form-item>
            <el-form-item prop="onShelf" label="上下架">
                <el-switch v-model="formData.onShelf" active-color="#13ce66" inactive-color="#ff4949" :disabled="'onShelf'==subColumn">
                </el-switch>
            </el-form-item>
            <!-- <el-form-item prop="useFlag" label="可用">
                <el-switch v-model="formData.useFlag" active-color="#13ce66" inactive-color="#ff4949" :disabled="'useFlag'==subColumn">
                </el-switch>
            </el-form-item> -->
            <!-- <el-form-item prop="hotFlag" label="热门">
                <el-switch v-model="formData.hotFlag" active-color="#13ce66" inactive-color="#ff4949" :disabled="'hotFlag'==subColumn">
                </el-switch>
            </el-form-item>
            <el-form-item prop="homeFlag" label="首页">
                <el-switch v-model="formData.homeFlag" active-color="#13ce66" inactive-color="#ff4949" :disabled="'homeFlag'==subColumn">
                </el-switch>
            </el-form-item> -->
            <!-- <el-form-item prop="rank" label="排序">
                <el-input v-model="formData.rank" :disabled="'rank'==subColumn"></el-input>
            </el-form-item> -->

            <!-- <el-form-item prop="salesVolume" label="销量">
                <el-input v-model="formData.salesVolume" :disabled="'salesVolume'==subColumn"></el-input>
            </el-form-item>-->

            <el-form-item>
                <el-button @click="onSave" :loading="$store.state.fetchingData" type="primary">保存</el-button>
                <el-button @click="onDelete" v-if="formData.id" type="danger">删除</el-button>
                <el-button @click="$router.go(-1)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { mapState } from 'vuex'
import formValidator from '../formValidator'
const baseUrl = process.env.NODE_ENV === 'production' ? '../' : 'http://localhost:8080';
import RichText from '../components/RichText'
export default {
    created() {

        if (this.$route.query.id) {
            this.$http.get({
                url: '/productInfo/getOne',
                data: {
                    id: this.$route.query.id
                }
            }).then(res => {
                if (res.success) {


                    this.formData = res.data;
                    this.levelNum = res.data.productPriceList
                    // res.data.productImageList.forEach(item => {
                    //     item.url = item.image
                    // })
                    // this.fileList = res.data.productImageList


                    this.formData.hotFlag = this.formData.hotFlag == 1 ? true : false;
                    this.formData.homeFlag = this.formData.homeFlag == 1 ? true : false;
                    this.formData.useFlag = this.formData.useFlag == 'Y' ? true : false;
                    this.formData.onShelf = this.formData.onShelf == 'Y' ? true : false;


                }
            })
        }


        this.$http.get({
            url: '/serviceType/all'
        }).then(res => {
            if (res.success) {
                this.serviceTypes = res.data;

                this.serviceTypes.forEach(element => {

                    this.serviceTypeDetails[element.id] = element.serviceTypeDetailList

                });
            }
        });

        this.formData.storeId = this.myStoreInfo.id
        this.formData.serviceType = this.myStoreInfo.serviceType
        this.formData.subclass = this.myStoreInfo.subclass

    },
    data() {
        return {
            saving: false,
            formData: {
                typeFlag: 0,
                rank: 0,
                responseTime: 0,
                reworkRate: 0,
                useFlag: true,
                serviceType: 1,
                onShelf: false,
                price: 0,
                inventory: 0
            },
            rules: {
                typeFlag: [
                    { required: true, message: '请选择类型', trigger: 'blur' },
                ],
                title: [
                    { required: true, message: '请输入商品标题', trigger: 'blur' },
                ],
                image: [
                    { required: true, message: '请上传商品主图', trigger: 'blur' },
                ],
                inventory: [
                    { required: true, message: '请上传商品主图', trigger: 'blur' },
                ],
                price: [
                    { required: true, message: '请输入默认价格', trigger: 'blur' },
                ],
            },
            subColumn: '',
            subValue: '',
            serviceTypes: [],
            serviceTypeDetails: {},
            typeFlagOptions: [{ label: '修图', value: 0 }],//[{ label: '修图', value: 0 }, { label: '实体商品', value: 1 }],
            levelNum: [],
            fileList: []
        }
    },
    computed: {
        ...mapState(['userInfo', 'myStoreInfo']),
        url() {
            return baseUrl + '/assets/uploadFile'
        }
    },
    methods: {
        onSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.submit();
                } else {
                    this.$message.warning('数据录入不全')
                    return false;
                }
            });
        },
        submit() {
            var data = JSON.parse(JSON.stringify(this.formData));

            delete data.productImageList
            delete data.productPriceList
            delete data.storeInfo

            data.hotFlag = this.formData.hotFlag ? 1 : 0;
            data.homeFlag = this.formData.homeFlag ? 1 : 0;
            data.useFlag = this.formData.useFlag ? 'Y' : 'N';
            data.onShelf = this.formData.onShelf ? 'Y' : 'N';

            console.log(data)
            this.$http.post({
                url: this.formData.id ? '/productInfo/update' : '/productInfo/save',
                data: data
            }).then(res => {
                if (res.success) {
                    this.savePrice(0, this.formData.id ? this.formData.id : res.data)
                    // this.saveImage(0, this.formData.id ? this.formData.id : res.data)
                    this.$message.success('成功');
                    this.$router.go(-1);
                } else {
                    this.$message.warning('失败')
                }
            });
        },
        savePrice(index, id) {
            if (index >= this.levelNum.length) {
                return
            }
            else {
                var data = JSON.parse(JSON.stringify(this.levelNum[index]));
                data.productId = id
                data.typeFlag = index
                if (index == this.levelNum.length - 1) {
                    data.maxCounts = -1
                }
                this.$http.post({
                    url: data.id ? '/productPrice/update' : '/productPrice/save',
                    data: data
                }).then(res => {
                    if (res.success) {
                        this.savePrice(index + 1, id)
                    } else {
                        this.$message.warning('失败')
                    }
                })
            }
        },
        saveImage(index, id) {
            if (index >= this.fileList.length) {
                return
            }
            else if (!this.fileList[index].id) {
                var data = JSON.parse(JSON.stringify(this.fileList[index]));
                data.productId = id
                delete data.url
                this.$http.post({
                    url: '/productImage/save',
                    data: data
                }).then(res => {
                    if (res.success) {
                        this.saveImage(index + 1, id)
                    } else {
                        this.$message.warning('失败')
                    }
                })
            }
            else {
                this.saveImage(index + 1, id)
            }
        },
        onDelete() {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
                return this.$http.post({
                    url: '/productInfo/del',
                    data: { id: this.formData.id }
                })
            }).then(() => {
                this.$message.success('删除成功');
                this.$router.go(-1);
            }).catch(action => {
                if (action === 'cancel') {
                    this.$message.info('删除取消');
                } else {
                    this.$message.error('删除失败');
                }
            })
        },
        addLevel() {
            if (this.levelNum.length > 0) {
                if (!this.levelNum[this.levelNum.length - 1].maxCounts) {
                    this.$message({
                        message: '最后一项最大值未输入不能添加新的阶梯价格',
                        type: 'warning'
                    });
                    return
                }
            }
            this.levelNum.push({
                name: '',
                price: '',
                minCounts: '',
                maxCounts: ''
            })
        },
        changeLevel(index) {
            if (index < this.levelNum.length - 1) {
                if (!this.levelNum[index].maxCounts) {
                    // this.levelNum[index].maxCounts = Number(this.levelNum[index + 1].minCounts) - 1
                    var jsonp = { ...this.levelNum[index] }
                    jsonp.maxCounts = Number(this.levelNum[index + 1].minCounts) - 1
                    this.$set(this.levelNum, index, jsonp)
                    this.$message({
                        message: '当前并不是最后一项不能清空最大值',
                        type: 'warning'
                    });

                    return
                }
                else {
                    this.levelNum[index + 1].minCounts = this.levelNum[index].maxCounts + 1
                }
            }
        },
        delLevel(index) {


            if (this.levelNum[index].id) {
                this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
                    return this.$http.post({
                        url: '/productPrice/del',
                        data: { id: this.levelNum[index].id }
                    })
                }).then(() => {
                    this.$message.success('删除成功');
                    this.levelNum.splice(index, 1)
                }).catch(action => {
                    if (action === 'cancel') {
                    } else {
                        this.$message.error('删除失败');
                    }
                })
            }
            else {
                this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' }).then(() => {
                    this.levelNum.splice(index, 1)
                    this.$message.success('删除成功');
                }).catch(action => {
                    if (action === 'cancel') {
                    } else {
                        this.$message.error('删除失败');
                    }
                })

            }

        },
        handleSuccess(response) {
            console.log(response)
            var jsonp = {
                image: response.data[0],
                url: response.data[0]
            }
            this.fileList.push(jsonp)
        },
        handleRemove(file, fileList) {
            console.log(file)
            if (file.id) {
                this.$http.post({
                    url: '/productImage/del',
                    data: { id: file.id }
                }).then(() => {
                    this.$message.success('删除成功');
                }).catch(action => {

                })
            }


            this.fileList = fileList
        },
        getMini(index) {
            if (index == 0) {
                return 0
            }
            else {
                return Number(this.levelNum[index - 1].maxCounts) + 1
            }
        }
    },
    components: {
        RichText
    }
}
</script>
<style lang="less" scoped>
.container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    border: 1px solid rgba(234, 234, 234, 1);
}
</style>
