<template>
    <div class="order">
        <z-title title="点餐项目设置" ref="title"></z-title>
        <el-card class="content1" ref="search">
            <div class="flex-n fac fjb">
            <div class=" flex-n fac">
                <el-input
                        size="medium"
                        class="ele-input mr-10"
                        maxlength="16"
                        placeholder="输入所属分类"
                        title="输入所属分类"
                        clearable
                        prefix-icon="el-icon-search"
                        v-model="foodTypeName">
                </el-input>
                <el-input
                        size="medium"
                        class="ele-input mr-10"
                        maxlength="16"
                        clearable
                        placeholder="输入菜品名称"
                        title="输入菜品名称"
                        prefix-icon="el-icon-search"
                        v-model="foodName">
                </el-input>
            </div>
            <div class="flex-n fac">
                <el-button type="primary" class="ele-btn1" @click="addFood">新增菜品</el-button>
                <el-upload
                        class="upload-demo"
                        ref="fileUpload"
                        action="#"
                        :http-request="httpRequest"
                        accept=".xlsx,.xls"
                        :show-file-list="false"
                >
                    <el-button type="primary" class="ele-btn1 ml-10 mr-10" >导入菜品</el-button>
                </el-upload>

                <el-button type="primary" class="ele-btn1" @click="editFenlei">编辑分类</el-button>
                <el-button type="primary" class="ele-btn2" @click="searchFood">查询</el-button>
            </div>
            </div>
        </el-card>
        <el-card class="mt-10">
            <el-table
                    v-loading="loading"
                    :height="height+'px'"
                    highlight-current-row
                    element-loading-text="列表刷新中"
                    header-cell-class-name="headerrow"
                    cell-class-name="cellclass"
                    :data="dataList"
                    style="width: 100%">
                <el-table-column
                        fixed
                        prop="foodName"
                        label="菜品名称"
                        width="150"
                        align="center">
                </el-table-column>
                <el-table-column
                        align="center"
                        prop="foodTypeName"
                        label="所属分类"
                        min-width="150">
                </el-table-column>
                <el-table-column
                        prop="foodPrice"
                        label="菜品价格"
                        min-width="150"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="remark"
                        label="备 注"
                        min-width="150"
                        align="center">
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="130"
                        align="center">
                    <template slot-scope="scope">
                        <div style="margin: 5px 0">
                            <el-button type="primary" class="ele-btn-small mr-10" @click="editFood(scope.row.id)">编辑</el-button>
                            <el-popconfirm
                                    title="确定删除该点餐项目吗？"
                                    @confirm="delFood(scope.row.id)"
                            >
                            <el-button slot="reference" type="primary" class="ele-btn-small">删除</el-button>
                            </el-popconfirm>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页-->
            <pagination :current-page="currentPage" :page-size="pageSize" :total="total"   @sizeChange="handleSizeChange"
                        @currentChange="handleCurrentChange"></pagination>
        </el-card>
        <!--新增-->
        <el-dialog :visible.sync="showedit"
                  class="ele-toast" :close-on-click-modal="false">
            <div slot="title" >
                <z-title :title="editstate+'点餐项目'"></z-title>
            </div>
            <el-form :model="dataForm" :rules="rules" ref="ruleForm" class="rulefrom">
                <el-form-item label="菜品名称" prop="foodName" label-width="80px">
                    <el-input maxlength="32" v-model="dataForm.foodName" placeholder="请输入菜品名称"></el-input>
                </el-form-item>
                <el-form-item label="所属分类" prop="foodTypeCode" label-width="80px">
                    <div class="flex-n fjb fac">
                        <el-select v-model="dataForm.foodTypeCode" placeholder="请选择所属分类" style="width: 100%"
                                   @visible-change="visiblechange"     class="mr-10">
                            <el-option
                                    v-for="item,index in classifyList"
                                    :key="item.foodTypeCode"
                                    :label="item.foodTypeName"
                                    :value="item.foodTypeCode">
                            </el-option>
                        </el-select>
                        <el-button type="primary" @click="editFenlei">编辑分类</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="是否推荐" prop="isStar" label-width="80px">
                    <el-radio-group v-model="dataForm.isStar">
                       <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜品价格" prop="foodPrice" label-width="80px">
                    <el-input-number placeholder="请输入菜品价格" v-model="dataForm.foodPrice" :precision="2" :step="0.1"
                                     controls-position="right" :max="9999999999"></el-input-number>
                </el-form-item>
                <el-form-item label="备 注" prop="remark" label-width="80px">
                    <el-input type="textarea" rows="6" show-word-limit v-model="dataForm.remark" resize="none"
                              maxlength="512"></el-input>
                </el-form-item>
                <el-form-item class="mt-10 flex-n fje">
                    <el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
                    <el-button @click="showedit = false">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!--编辑分类-->
        <el-dialog :visible.sync="showfenlei" width="30%" top="20vh" :close-on-click-modal="false" class="editfenlei">
            <div slot="title" class="flex-n fac">
                <z-title title="编辑分类"></z-title>
                <el-button type="text" size="mini" @click="classify.typeList.push({foodTypeName:'',foodTypeCode:''})">添加</el-button>

            </div>
            <el-form :model="classify"  ref="ruleForm2">
                <div class="tips">注意：如果分类下已经添加菜品，则删除此分类，其分类下的所有菜品也将一同删除</div>
                <el-form-item
                        v-for="(item, index) in classify.typeList"
                        label="分类名称"
                        :key="index"
                        :prop="'typeList.' + index + '.foodTypeName'"
                        :rules="{required: true, message: '分类名称不能为空', trigger: 'blur'}" >
                    <div class="flex-n fac fjb">
                        <el-input v-model="item.foodTypeName" size="mini" class="mr-20"></el-input>
                        <!--<el-button type="primary" v-if="index==0" @click="classify.typeList.push({foodTypeName:'',foodTypeCode:''})" class="btn  flex-n fac fjc">-->
                            <!--<i class="el-icon-plus"></i>-->
                        <!--</el-button>-->
                        <el-button type="primary" @click="classify.typeList.splice(index,1)" class="btn flex-n fac fjc">
                            <i class="el-icon-minus"></i>
                        </el-button>
                    </div>
                </el-form-item>
                <el-form-item class="mt-10 flex-n fje">
                    <el-button type="primary" @click="submitForm2('ruleForm2')">保 存</el-button>
                    <el-button @click="showfenlei = false">取 消</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import ZTitle from "../../components/ZTitle";
    import ElFormItem from "element-ui/packages/form/src/form-item";
    import Pagination from "../../components/pagination/pagination";

    export default {
        components: {
            Pagination,
            ElFormItem,
            ZTitle},
        name: "order",
        data() {
            return {
                loading: false,
                pageSize: 20,
                currentPage: 1,
                total: 0,
                height: 250,

                dataForm: {
                    foodTypeCode:'',
                    isStar:'0'
                },
                editstate: '新增',
                showedit: false,

                dataList: [],

                foodName: '',
                foodTypeName : '',
                id: '',

                showfenlei: false,
                classify:{
                    typeList:[]
                },
                classifyList:[],

                rules: {
                    foodName: [{required: true, message: '菜品名称不能为空', trigger: 'blur'}],
                    foodTypeCode: [{required: true, message: '所属分类不能为空', trigger: 'blur'}]
                },

            }
        },
        watch: {
            showedit(newval, oldval) {
                if (!newval) {
                    this.$refs.ruleForm.resetFields();
                    this.dataForm={
                        foodTypeCode:''
                    };
                }else{
                    if(this.editstate=='新增'){
                        this.$set(this.dataForm,'isStar','0');
                    }
                }
            },
            showfenlei(newval,oldval){
                if(!newval){
                    this.$refs.ruleForm2.resetFields();
                    this.classify={
                        typeList:[]
                    }
                }
            },
        },
        mounted() {
            setTimeout(()=>{
                this.height=document.body.offsetHeight -this.$refs.title.$el.offsetHeight-this.$refs.search.$el.offsetHeight - 200;
                console.log(this.height)
            },0)
            this.getFood();
            this.getClassifyList();
        },
        methods: {
            //查询点餐项目列表
            getFood() {
                this.loading = true;
                this.$axios.post('/itemsFood/itemsFoodList', {
                    "storeId": this.$root.getStorage('storeId'),
                    "foodName": this.foodName,
                    "foodTypeName": this.foodTypeName,
                    "currentPage":this.currentPage,
                    "pageSize":this.pageSize,
                }).then(res => {
                    console.log('点餐项目列表', res);
                    this.dataList = res.data.list;
                    this.total = res.data.total;
                    this.loading = false;
                }).catch(err => {
                    this.$message.error(err.msg);
                    this.loading = false;
                })
            },
            //搜索
            searchFood(){
                this.currentPage=1;
                this.getFood();
            },
            getClassifyList(){
                this.$axios.post('/itemsFood/itemsFoodTypeListByStoreId',{
                    "storeId": this.$root.getStorage('storeId')
                }).then(res=>{
                    console.log('点餐项目下拉列表',res)
                    this.classifyList=res.data.list;
                    if(this.showfenlei){
                        if(res.data.total==0){
                            this.classify.typeList=[{foodTypeName:'',foodTypeCode:''}];
                        }else{
                            this.classify.typeList=[].concat(res.data.list)
                        }
                    }
                }).catch(err=>{
                    this.$message.error(err.msg);
                })
            },
            //查看分类列表
            visiblechange(isshow) {
                if (isshow) {
                    this.getClassifyList();
                }
            },
            editFenlei(){
                this.showfenlei=true;
                this.getClassifyList();
            },
            //添加
            addFood() {
                this.showedit = true;
                this.editstate = '新增'
            },
            //编辑
            editFood(id) {
                console.log('编辑',id)
                this.id=id;
                this.showedit = true;
                this.editstate = '编辑';
                this.$axios.get('/itemsFood/itemsFoodById/'+id).then(res=>{
                    console.log(res)
                    this.dataForm=res.data;
                }).catch(err=>{
                    this.$message.error(err.msg);
                })
            },
            //删除
            delFood(id){
                console.log('删除',id)
                this.$axios.post('/itemsFood/itemsFoodDeleteByIds',id).then(res=>{
                    this.$message.success('删除点餐项目成功！');
                    this.getFood();
                }).catch(err=>{
                    this.$message.error(err.msg);
                })

            },
            //添加提交
            addSubmit() {
                let {isStar, foodName, foodTypeCode, foodPrice, remark} = this.dataForm;
                console.log(isStar)
                this.$axios.post('/itemsFood/itemsFoodAdd', {
                    "storeId": this.$root.getStorage('storeId'),
                    "isStar": isStar,
                    "foodName": foodName,
                    "foodTypeCode": foodTypeCode,
                    "foodPrice": foodPrice,
                    "remark": remark
                }).then(res => {
                    this.currentPage = 1;
                    this.getFood();
                    this.$message.success('新增点餐项目成功！');
                    this.showedit = false;
                }).catch(err => {
                    this.$message.error(err.msg);
                })
            },
            //编辑提交
            editSubmit() {
                let {isStar, foodName, foodTypeCode,foodPrice, remark} = this.dataForm;

                this.$axios.post('/itemsFood/itemsFoodUpdate', {
                    "storeId": this.$root.getStorage('storeId'),
                    "id": this.id,
                    "isStar": isStar,
                    "foodName": foodName,
                    "foodTypeCode": foodTypeCode,
                    "foodPrice": foodPrice,
                    "remark": remark
                }).then(res => {
                    this.$message.success('编辑点餐项目成功！');
                    this.getFood();
                    this.showedit = false;
                }).catch(err => {
                    this.$message.error(err.msg);
                })
            },
            //验证表单
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.editstate == '新增') {
                            this.addSubmit();
                        } else {
                            this.editSubmit();
                        }
                    } else {
                        this.$message.error('表单填写有误');
                        return false;
                    }
                });
            },
            //验证表单2
            submitForm2(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var typeList=[];
                        for(var i=0;i<this.classify.typeList.length;i++ ){
                            typeList.push({'typeName':this.classify.typeList[i].foodTypeName,'id':this.classify.typeList[i].foodTypeCode})
                        }
                        console.log(typeList)
                        this.$axios.post('/itemsFoodType/itemsFoodTypeUpdate',{
                            "storeId": this.$root.getStorage('storeId'),
                            "typeList":typeList
                        }).then(res=>{
                            this.$message.success('编辑分类成功！');
                            this.dataForm.foodTypeCode='';
                            this.showfenlei = false;
                            this.searchFood();
                        }).catch(err=>{
                            this.$message.error(err.msg);
                        })
                    } else {
                        this.$message.error('表单填写有误');
                        return false;
                    }
                });
            },
            httpRequest(file) {
                console.log(file)
                var fileData=file.file;
                var msg = fileData.name.substring(fileData.name.lastIndexOf('.') + 1)
                //判断文件格式
                if (!(msg === 'xlsx' || msg === 'xls')) {
                    this.$refs.fileUpload.clearFiles()
                    this.$notify.error({
                        title: '错误',
                        message: '上传文件只能是 xlsx,xls格式!',
                        duration: 2000
                    })
                    return
                }
                let formData = new FormData();
                formData.append('file', fileData);
                formData.append('type', 1)
                this.$axios.post('/importExcel/uploadFoodItemsExcel', formData).then(res => {
                    console.log(res)
                    this.$message.success('附件上传成功');
                    this.searchFood();
                }).catch(err => {
                    this.$message.success('附件上传失败')
                })
            },

            handleSizeChange(val) {
                this.pageSize = val;
                this.getFood();
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getFood();
                console.log(`当前页: ${val}`);
            },
        },
    }
</script>

<style scoped lang="scss">
    .order {
        .content1 {
            .textnowrap {
                font-size: 13px;
                color: #333;
            }
            .date {
                min-width: 100px;
            }
        }
        .editfenlei {
            padding: 0 20px !important;
            .tips {
                font-size: 12px;
                color: #F56C6C;
            }
            .btn {
                padding: 0 !important;
                width: 28px;
                min-width: 28px;
                height: 28px;
                font-size: 20px;
                font-weight: bold;
            }
        }
    }
</style>