<template>
    <div style="padding: 10px;background: #E5EBF6;min-height: 830px;">
        <div style="background: #FFF;padding: 10px;border-radius: 10px;margin-bottom: 20px;">
            <el-form :model="baseInfo" ref="baseInfo" :rules="baseRules" size="medium" :inline="true" label-width="110px">
                <!-- <el-form-item label="生产计划单号" prop="productionPlanCode">
                    <el-input v-model="baseInfo.productionPlanCode" placeholder="生产计划单号自动生成" disabled maxlength="20" clearable style="width: 240px"/>
                </el-form-item> -->
                <el-form-item label="生产计划名称" prop="productionPlanName">
                    <el-input v-model="baseInfo.productionPlanName" placeholder="请输入生产计划名称" maxlength="20" clearable style="width: 240px"/>
                </el-form-item>  
                <el-form-item label="所属区域" prop="areaId">
                    <el-cascader v-model="baseInfo.areaId"
                        :options="treeAreaOptions" :filterable="true" style="width: 240px" :show-all-levels="false"
                        :props="{  
                        emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                        checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                        value:'id',label:'label'
                        }" @change="handleAreaChange">
                    </el-cascader>
                </el-form-item> 
                <el-form-item label="所属食堂" prop="canteenId">
                    <el-select v-model="baseInfo.canteenId" placeholder="请选择所属食堂" style="width: 240px;" @change="handleCanteenChange">
                        <el-option v-for="item in canteenOptions"
                            :key="item.canteenId"
                            :label="item.canteenName"
                            :value="item.canteenId"
                        ></el-option>
                    </el-select> 
                </el-form-item> 
                <el-form-item label="所属档口" prop="stallId">
                <el-select v-model="baseInfo.stallId" placeholder="请选择所属档口" style="width: 240px;" @change="handleStallChange">
                        <el-option v-for="item in stallOptions"
                            :key="item.stallId"
                            :label="item.stallName"
                            :value="item.stallId"
                        ></el-option>
                    </el-select> 
                </el-form-item> 
                <el-form-item label="生产计划日期" v-if="dialogType==1">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @change="changeDateRange"
                        format="yyyy-MM-dd"
                        :picker-options="pickerOptions" >
                    </el-date-picker>
                </el-form-item> 
                <el-form-item label="是否重复" v-if="dialogType==1">
                    <el-radio-group v-model="ifRepeat" @change="changeRepeatType">
                        <el-radio label="1" style="font-size: 14px;">多天重复</el-radio>
                        <el-radio label="2" style="font-size: 14px;">多天不重复</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="选择菜谱" prop="recipeId" v-if="dialogType==2">
                    <el-select v-model="baseInfo.recipeId" clearable placeholder="请选择菜谱" style="width: 100%;" @change="handleRecipeChange">
                        <el-option v-for="item in recipeOptions"
                            :key="item.recipeId"
                            :label="item.recipeName"
                            :value="item.recipeId"
                        ></el-option>
                    </el-select> 
                </el-form-item>
                <el-row class="mb8" v-if="ifRepeat==2">
                        <el-col :span="1">
                            <span style="font-weight: bold;color: #606266;font-size: 14px;">日期</span>
                        </el-col>
                        <el-col :span="23">
                            <el-radio-group v-model="dateRangeRadio" @change="choseDateRadio">
                                <el-radio :label="item.applyDate" v-for="(item,index) in dateRangeList" :key="index" style="font-size: 14px;margin-bottom: 10px;">{{ item.applyDateStr }}</el-radio>
                            </el-radio-group>
                        </el-col>
                </el-row> 
                <el-row class="mb8" v-if="dialogType==2">
                        <el-col :span="1">
                            <span style="font-weight: bold;color: #606266;font-size: 14px;">日期</span>
                        </el-col>
                        <el-col :span="23">
                            <el-radio-group v-model="dateRangeRadio" @change="choseDateRadio2">
                                <el-radio :label="item.applyDate" v-for="(item,index) in dateRangeList" :key="index" style="font-size: 14px;margin-bottom: 10px;">{{ item.applyDateStr }}</el-radio>
                            </el-radio-group>
                        </el-col>
                </el-row> 
            </el-form>
        </div> 
        <div style="width: 100%;height: 480px;padding: 10px;border-radius: 10px;margin-bottom: 10px;background: #FFF;"> 
            <div style="width: 100%;height: 450px;padding: 10px;border-radius: 10px;margin-bottom: 10px;display: flex;" >
                <el-card class="dishes-card" v-for="item in detailList" :key="item.mealtimeType">
                    <div slot="header">
                        <span>{{item.mealtimeName}}</span> 
                    </div>
                    <div class="body-card">
                        <div v-for="dish in item.dishesList" :key="dish.dishesId" style="width: 100%;display: flex;justify-content: space-between;align-items: center;">
                            <span>{{dish.dishesName}}</span> 
                            <el-input v-model="dish.dishesNum" placeholder="请输入份数" maxlength="10" clearable 
                                    @input="(v)=>(dish.dishesNum=v.replace(/[^\d]/g,''))" style="width: 100px;"/>
                            <!-- <i class="el-icon-delete" style="color: red;cursor: pointer;" @click="deleteDishes(item,dish)"  v-if="dialogType==1"></i> -->
                        </div>
                    </div>
                    <div class="bottom-card">
                        <el-button type="primary" @click="addDishes(item)" v-if="item.dishesList.length==0&&dialogType==1">新增</el-button>
                        <el-button plain type="primary" v-if="item.dishesList.length>0&&dialogType==1" @click="editDishes(item)" >修改</el-button>
                    </div>
                </el-card>  
            </div>
        </div>
        <div style="width: 100%;height: 80px;padding: 10px;background: #FFF;border-radius: 10px;display: flex;align-items: center;justify-content: center;">
            <el-button type="primary" plain @click="confirmSave" :loading="loadingBtn">保存草稿</el-button>
            <el-button type="success" plain @click="confirmSubmit" :loading="loadingBtn">提交</el-button>
            <el-button @click="jumpList">返回</el-button>
        </div>

        <!-- 选择菜品 -->
        <el-dialog title="选择菜品" :visible.sync="openDishes" width="55%" append-to-body>
            <div style="width: 100%;height:620px;display: flex;align-items: center;color: #000;">   
                <div class="dialog-left">
                    <div>已选菜品数量：{{dishesList.length}}</div>
                    <div>
                        <div style="font-weight: bold;margin: 10px 0;">所属食堂</div>
                        <el-select v-model="queryDish.canteenId" placeholder="请选择所属食堂" style="width: 100%;" clearable @change="getDishesPage">
                            <el-option v-for="item in canteenOptions"
                                :key="item.canteenId"
                                :label="item.canteenName"
                                :value="item.canteenId"
                            ></el-option>
                        </el-select> 
                    </div>
                    <div>
                        <div style="font-weight: bold;margin: 10px 0;">菜品分类</div>
                        <el-cascader v-model="queryDish.typeId"
                            :options="typeOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
                            :props="{ 
                                emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                                checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                                value:'dishesTypeId',label:'dishesTypeName'
                            }" clearable @change="getDishesPage">
                        </el-cascader>
                        <!-- <el-select v-model="queryDish.typeId" style="width: 100%;" clearable @change="getDishesPage">
                            <el-option v-for="item in typeOptions"
                                :key="item.typeId"
                                :label="item.dishesTypeName"
                                :value="item.typeId" 
                            ></el-option>
                        </el-select> -->
                    </div>
                    <div>
                        <div style="font-weight: bold;margin: 10px 0;">菜品名称</div>
                        <el-input  v-model="queryDish.dishesName" placeholder="请输入菜品名称" maxlength="30" clearable @input="getDishesPage"/>
                    </div>
                    <div style="margin-top: 20px;">
                        <el-card style="width: 100%;height: 380px;">
                            <div slot="header">
                                <span>菜品</span> 
                            </div>
                            <div style="width: 100%;height: 320px;overflow-y: auto;">
                                <div v-for="item in dishesPageList" :key="item.dishesId" class="dish-name" @click="chosenDishes(item)">
                                    <span v-if="item.sizeType==1">【标准】</span>
                                    <span v-if="item.sizeType==2">【大小份】</span>
                                    <span>{{ item.dishesName }}</span>
                                    <i class="el-icon-check" v-if="item.isChecked"></i>
                                </div>
                                 
                            </div>
                        </el-card> 
                    </div>
                </div> 
                <div class="dialog-right">
                    <el-table :data="dishesTableList" height="620">
                        <!-- <el-table-column label="菜品编号" align="center" prop="dishesNum" /> -->
                        <el-table-column label="菜品名称" align="center" prop="dishesName" />
                        <el-table-column label="所属食堂" align="center" prop="canteenName" />
                        <el-table-column label="规格" align="center" prop="sizeType">
                            <template slot-scope="scope">
                                <span v-if="scope.row.sizeType==1">标准</span>
                                <span v-if="scope.row.sizeType==2">大小份</span>
                            </template>
                        </el-table-column> 
                        <el-table-column label="份数" align="center" prop="dishesNum">
                            <template slot-scope="scope">
                                <el-input  v-model="scope.row.dishesNum" placeholder="请输入份数" maxlength="10" clearable @input="(v)=>(scope.row.dishesNum=v.replace(/[^\d]/g,''))"/>
                            </template>
                        </el-table-column> 
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" style="color: red;"
                                @click="handleDelDishes(scope.row)" 
                                >删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="confirmChosen">确 定</el-button>
                <el-button @click="openDishes=false">取 消</el-button>
            </div>
        </el-dialog>


    </div>
</template>
  
<script> 
import { systemAreaTreeApi,getCanteenByAreaApi,getStallByCanteenApi } from "@/api/base/stall";  
import { getProductionPlanInfoApi, addProductionPlanApi, editProductionPlanApi } from "@/api/foodManage/purchaseManage";
import { getDishesByTypePageApi,getPageRecipeListAllApi,getMenuRecipeDetailApi } from "@/api/dish/menu"; 
import { menuDishesTypeAllListApi } from "@/api/dish/dish";
export default {
    name: "ProductionPlanEdit",
    dicts: [],
    data() {
      return {
        dialogType:1,//页面传参
        ifRepeat:1,//页面传参
        productionPlanRowData:{},//页面传参
        loading:false,
        loadingBtn:false,
        baseInfo: {},
        resDetailList:[],
        // 表单校验
        baseRules: {
            productionPlanName: [
                { required: true, message: "生产计划名称不能为空", trigger: "change" }
            ], 
            // deliverGoodsDate: [
            //     { required: true, message: "交货日期不能为空", trigger: "change" }
            // ],  
            areaId: [
                { required: true, message: "所属区域不能为空", trigger: "change" }
            ],
            canteenId: [
                { required: true, message: "所属食堂不能为空", trigger: "change" }
            ],
            stallId: [
                { required: true, message: "所属档口不能为空", trigger: "change" }
            ],
            recipeId: [
                { required: true, message: "菜谱不能为空", trigger: "change" }
            ]
        },
        treeAreaOptions:[],
        canteenOptions:[], 
        stallOptions:[],
        recipeOptions:[],
        dateRange:[new Date(),new Date().setDate(new Date().getDate() + 6)],
        pickerOptions: { 
            disabledDate(v) {
                return v.getTime() < (new Date().getTime() - 86400000);//  - 86400000是否包括当天
            }
        }, 
        dateRangeList:[],
        dateRangeIndex:0,
        dateRangeRadio:"",
        detailList:[],
        noMaterial:false,
        openDishes:false,
        // 查询菜品
        queryDish:{
            salesMode:null,
            typeId:null,
            dishesName:''
        },
        typeOptions:[],
        //弹窗左侧待选菜品
        dishesPageList:[],  
        //弹窗右侧已选菜品
        dishesTableList:[],
        dishesList:[],
        noDishes:true,
        
      };
    },
    created() {
        this.getAreaTreeData()   
        //获取菜品类型
        this.getTypeData()   
        if(this.$route.query.dialogType){ 
            this.dialogType = this.$route.query.dialogType
            this.initEditDetail()
        } 
        if(this.$route.query.productionPlanRowData){ 
            this.productionPlanRowData = JSON.parse(this.$route.query.productionPlanRowData)
            this.getContractInfo()
        } 
    },
    watch:{
        '$route.query.productionPlanRowData':function(newId, oldId) {
            if(newId){
                this.productionPlanRowData = JSON.parse(newId)
                this.getContractInfo()
            }
        },
        '$route.query.dialogType':function(newValue, oldId) {
            if(newValue){
                this.dialogType = this.$route.query.dialogType
                this.initEditDetail()
            }
        },
    },
    methods: { 
        // 返回列表页
        jumpList() {
            const obj = { path: "foodManage/purchaseManage/productionPlanEdit" };
            this.$tab.closeOpenPage(obj);
            this.$router.replace({ path: "/foodManage/purchaseManage/productionPlan" }); // 要打开的页面 
        },
        initEditDetail(){
            if(this.dialogType==1){
                this.dateRange=[new Date(),new Date().setDate(new Date().getDate() + 6)] 
                this.dateRangeList = this.getDateRange(this.dateRange[0],this.dateRange[1]) 
                this.dateRangeIndex = 0
                this.dateRangeRadio = this.formatDate(this.dateRange[0]); 
                this.detailList = this.dateRangeList[0].detailList; 
            }
            if(this.dialogType==2){
                this.recipeOptions = []
                this.dateRange=[new Date(),new Date()] 
                this.dateRangeList = this.getDateRange(this.dateRange[0],this.dateRange[1]) 
                this.dateRangeIndex = 0
                this.dateRangeRadio = this.formatDate(this.dateRange[0]); 
                this.detailList = this.dateRangeList[0].detailList; 
            } 
        },
        getContractInfo(){
            console.log(this.productionPlanRowData) 
            let param = {
                planId:this.productionPlanRowData.planId
            }
            //查询查询食堂下拉结构
            getProductionPlanInfoApi(param).then((response) => {
                this.baseInfo = response.data;  
                this.dialogType = response.data.productionPlanType;
                this.ifRepeat = response.data.ifRepeat;
                getCanteenByAreaApi({areaId:this.baseInfo.areaId}).then((response) => {
                    this.canteenOptions=response.rows||[];
                    this.$set(this.baseInfo,"canteenId",this.baseInfo.canteenId)
                });
                getStallByCanteenApi({ canteenId:this.baseInfo.canteenId }).then((response) => {
                    this.stallOptions=response.rows||[]
                    this.$set(this.baseInfo,"stallId",this.baseInfo.stallId)  
                });    
                getPageRecipeListAllApi({areaId:this.baseInfo.areaId,canteenId:this.baseInfo.canteenId,stallId:this.baseInfo.stallId,}).then((response) => {
                    this.recipeOptions = response.rows||[]
                    this.$set(this.baseInfo,"recipeId",this.baseInfo.recipeId)    
                }); 
                this.resDetailList = response.data.productionPlanDetailVOList;
                this.dateRange=[this.resDetailList[0].detailDate,this.resDetailList[this.resDetailList.length-1].detailDate] 
                this.dateRangeList = this.getDateRange(this.dateRange[0],this.dateRange[1]) 
                this.dateRangeIndex = 0
                this.dateRangeRadio = this.formatDate(this.dateRange[0]); 
                if(this.dialogType==1){
                    for (let i = 0; i < this.resDetailList.length; i++) {
                        this.dateRangeList.forEach(item=>{
                            if(this.resDetailList[i].detailDate==item.applyDate){
                                item.detailList.forEach(subItem=>{
                                    if(this.resDetailList[i].mealtimeType==subItem.mealtimeType){ 
                                        this.$set(this.resDetailList[i],'dishesNum',this.resDetailList[i].dishesNum) 
                                        subItem.dishesList.push(this.resDetailList[i])
                                    }
                                })
                            } 
                        }) 
                    }
                    this.detailList = this.dateRangeList[0].detailList; 
                }
                if(this.dialogType==2){ 
                    let param = {
                            "applyDate": this.dateRangeRadio,
                            "recipeId": this.baseInfo.recipeId
                        }
                        getMenuRecipeDetailApi(param).then((response) => { 
                            if(response.data.length>0){
                                for (let i = 0; i < response.data.length; i++) { 
                                    this.dateRangeList[0].detailList.forEach(item=>{
                                        if(item.mealtimeType==response.data[i].mealtimeType){ 
                                            item.dishesList = response.data[i].dishesList
                                        }
                                    })  
                                } 
                                for (let i = 0; i < this.resDetailList.length; i++) {
                                    this.dateRangeList.forEach(item=>{
                                        if(this.resDetailList[i].detailDate==item.applyDate){
                                            item.detailList.forEach(subItem=>{
                                                if(this.resDetailList[i].mealtimeType==subItem.mealtimeType){ 
                                                    subItem.dishesList.forEach(lastItem=>{
                                                        if(this.resDetailList[i].dishesId==lastItem.dishesId){
                                                            this.$set(lastItem,'dishesNum',this.resDetailList[i].dishesNum) 
                                                        } 
                                                    }) 
                                                }
                                            })
                                        } 
                                    }) 
                                } 
                                this.detailList = this.dateRangeList[0].detailList;
                            }
                        });   
                }
                 
            }); 
        },
        //区域树
        getAreaTreeData() {
            systemAreaTreeApi({}).then((response) => {
                this.treeAreaOptions = response.data; 
            });
        },
        getFirstChild(node) {
            if (!node.children || node.children.length === 0) {
                return node; // 没有子节点或子节点为空，返回当前节点
            } else {
                return this.getFirstChild(node.children[0]); // 递归调用最后一个子节点
            }
        },
        //选中区域-查询食堂
        handleAreaChange(e){  
            this.getCanteenData() 
        }, 
        /** 查询查询食堂下拉结构 */
        getCanteenData() { 
            let param= {
                areaId:this.baseInfo.areaId
            } 
            getCanteenByAreaApi(param).then((response) => {
                this.canteenOptions=response.rows||[];
                this.$set(this.baseInfo,"canteenId",null)
            });
        },
         //选中食堂-查询档口
        handleCanteenChange(e){ 
            this.getStallData()
        },
        /** 查询查询档口下拉结构 */
        getStallData() { 
            let param= {
                canteenId:this.baseInfo.canteenId
            } 
            getStallByCanteenApi(param).then((response) => {
                this.stallOptions=response.rows||[]
                this.$set(this.baseInfo,"stallId",null)
            });
        }, 
        //档口下拉联动
        handleStallChange(e){
            let param= {
                areaId:this.baseInfo.areaId,
                canteenId:this.baseInfo.canteenId,
                stallId:this.baseInfo.stallId,
            }
            getPageRecipeListAllApi(param).then((response) => {
                this.recipeOptions = response.rows||[]
                this.$set(this.baseInfo,"recipeId",null)  
            });
        },
        //选择日期范围
        changeDateRange(e){ 
            this.dateRangeList = this.getDateRange(this.formatDate(e[0]),this.formatDate(e[1]))
            this.dateRangeIndex = 0
            this.dateRangeRadio = this.formatDate(e[0])
            this.detailList = this.dateRangeList[0].detailList; 
        },
        //获取两日期间所有日期-构建每日菜谱数据
        getDateRange(startDate, endDate) {
            let start = new Date(startDate);
            let end = new Date(endDate) 
            let dateArray = []; 
            while (start <= end) { 
                //周几
				var days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				var dayOfWeek = start.getDay();
                let obj = {
                    applyDate:this.formatDate(start),
                    applyWeek:dayOfWeek,
                    applyDateStr:this.formatDate(start)+" "+days[dayOfWeek],
                    detailList:[
                        {
                            mealtimeType:"1",
                            mealtimeName:"早餐",
                            dishesList:[]
                        },
                        {
                            mealtimeType:"2",
                            mealtimeName:"午餐",
                            dishesList:[]
                        },
                        {
                            mealtimeType:"3",
                            mealtimeName:"下午茶",
                            dishesList:[]
                        },
                        {
                            mealtimeType:"4",
                            mealtimeName:"晚餐",
                            dishesList:[]
                        },
                        {
                            mealtimeType:"5",
                            mealtimeName:"夜宵",
                            dishesList:[]
                        }
                    ]
                }
                dateArray.push(obj); // 转换为 YYYY-MM-DD 格式
                start.setDate(start.getDate() + 1); // 日期加 1 
            } 
            return dateArray; 
        }, 
        //切换重复类型
        changeRepeatType(e){ 
            if(e==1){//
                this.dateRangeIndex = 0
                this.detailList = this.dateRangeList[0].detailList;
            }else{
                let index = this.dateRangeList.findIndex(v=>v.applyDate==this.dateRangeRadio)
                this.dateRangeIndex = index
                this.detailList = this.dateRangeList[index].detailList;
            }
        },
        //切换日期菜谱-直接生成
        choseDateRadio(e){ 
                let index = this.dateRangeList.findIndex(v=>v.applyDate==this.dateRangeRadio)
                this.dateRangeIndex = index
                this.detailList = this.dateRangeList[index].detailList; 
        }, 
        /** 查询新增页面-菜品类型下拉 */
        getTypeData() {
            menuDishesTypeAllListApi({}).then((response) => {
                this.typeOptions = response.data; 
            });
        },
        //新增菜品
        addDishes(item){ 
            if(this.baseInfo.areaId!=undefined){
                this.dishesList=item.dishesList;  
                this.dishesTableList=item.dishesList
                this.getDishesPage()
                this.openDishes=true 
            }else{
                this.$modal.msgError("请先选择区域");
            }
        },
        //修改菜品
        editDishes(item){
             if(this.baseInfo.areaId!=undefined){
                this.dishesList=item.dishesList;  
                this.dishesTableList=item.dishesList
                this.getDishesPage()
                this.openDishes=true
            }else{
                this.$modal.msgError("请先选择区域");
            } 
        },
        //获取左侧待选菜品
        getDishesPage(){
            let param = {
                "areaId":this.baseInfo.areaId,
                "canteenId":this.baseInfo.canteenId, 
                "salesMode":this.queryDish.canteenId,
                "typeIds":[this.queryDish.typeId],
                "dishesName":this.queryDish.dishesName, 
                "pageNum":1,
                "pageSize":100
            }
            getDishesByTypePageApi(param).then((response) => { 
                this.dishesPageList = response.rows;
                for(let i =0 ;i < this.dishesList.length ;i++){
                    this.dishesPageList.forEach(item=>{
                        if(item.dishesId==this.dishesList[i].dishesId){
                            item.isChecked=true
                        }
                    })
                }
            });
        },
        //点击左侧待选菜品
        chosenDishes(obj){
            //判断是否为新菜品类型
            let index = this.dishesList.findIndex(v=>v.dishesId==obj.dishesId)
            if(index==-1){//新-加入
                let dish = Object.assign({}, obj)   
                this.$set(dish,'dishesNum',null) 
                this.dishesList.push(dish)
                // this.dishesTableList.push(dish)
                //反显选中样式
                this.dishesPageList.forEach(item=>{
                    if(obj.dishesId==item.dishesId){
                        item.isChecked = true;
                    }
                }) 
            }else{
                this.dishesList.splice(index,1)
                // this.dishesTableList.splice(index,1)
                //反显选中样式
                this.dishesPageList.forEach(item=>{
                    if(obj.dishesId==item.dishesId){
                        item.isChecked = null;
                    }
                })
            } 
        }, 
        //弹窗右侧表格删除菜谱
        handleDelDishes(item){
            this.$modal.confirm('是否确认删除？').then(()=>{
                let index = this.dishesList.findIndex(v=>v.dishesId==item.dishesId) 
                if(index>-1){
                    this.dishesList.splice(index,1)
                    // let index2 = this.dishesTableList.findIndex(v=>v.dishesId==item.dishesId) 
                    // this.dishesTableList.splice(index2,1)
                    this.dishesPageList.forEach(dish=>{
                        if(dish.dishesId==item.dishesId){
                            dish.isChecked = null;
                        }
                    })
                }
            }).catch(() => {}); 
        },
        //选择菜品弹窗-确认按钮
        confirmChosen(){
            console.log(this.dishesList)
            let index = this.dishesList.findIndex(v=>v.dishesNum==null||v.dishesNum==0) 
            console.log(index)
            if(index>-1){
                this.$modal.msgError("请填写菜品份数");
            }else{
                this.openDishes=false
            } 
        },
        //外部餐次列表删除菜谱
        deleteDishes(type,dish){
            this.$modal.confirm('是否确认删除？').then(()=>{
                let index = type.dishesList.findIndex(v=>v.dishesId==dish.dishesId)
                this.detailList.forEach(item=>{
                    if(item.mealtimeType==type.mealtimeType){
                        item.dishesList.splice(index,1)
                    }
                })
            }).catch(() => {}); 
        },
        //菜谱选择联动
        handleRecipeChange(e){ 
            let index = this.recipeOptions.findIndex(v=>v.recipeId==this.baseInfo.recipeId)
            let currentItem = this.recipeOptions[index]   
            if(currentItem.applyDateList.length>0){
                this.dateRange=[currentItem.applyDateList[0],currentItem.applyDateList[currentItem.applyDateList.length-1]] 
                this.dateRangeList = this.getDateRange(this.dateRange[0],this.dateRange[1]) 
                this.dateRangeIndex = 0
                this.dateRangeRadio = this.formatDate(this.dateRange[0]);   
                let param = {
                    "applyDate": this.dateRangeRadio,
                    "recipeId": this.baseInfo.recipeId
                }
                getMenuRecipeDetailApi(param).then((response) => {
                    if(response.data.length>0){
                        for (let i = 0; i < response.data.length; i++) {
                            this.dateRangeList[0].detailList.forEach(item=>{
                                if(item.mealtimeType==response.data[i].mealtimeType){
                                    response.data[i].dishesList.forEach(dish=>{
                                        this.$set(dish,'dishesNum',null) 
                                    }); 
                                    item.dishesList = response.data[i].dishesList
                                }
                            }) 
                        }  
                        this.detailList = this.dateRangeList[0].detailList; 
                    }else{
                        this.detailList = [
                            {
                                mealtimeType:"1",
                                mealtimeName:"早餐",
                                dishesList:[]
                            },
                            {
                                mealtimeType:"2",
                                mealtimeName:"午餐",
                                dishesList:[]
                            },
                            {
                                mealtimeType:"3",
                                mealtimeName:"下午茶",
                                dishesList:[]
                            },
                            {
                                mealtimeType:"4",
                                mealtimeName:"晚餐",
                                dishesList:[]
                            },
                            {
                                mealtimeType:"5",
                                mealtimeName:"夜宵",
                                dishesList:[]
                            }
                        ]
                    }
                });  
            }else{
                this.$modal.msgError("所选菜谱近期无菜品");
            } 
        },
        //切换日期菜谱-选择菜谱
        choseDateRadio2(e){
            let index = this.dateRangeList.findIndex(v=>v.applyDate==this.dateRangeRadio)
            this.dateRangeIndex = index
            this.detailList = this.dateRangeList[index].detailList;
            let hasDishes = false
            this.detailList.forEach(item=>{
                if(item.dishesList.length>0){
                    hasDishes=true
                }
            }) 
            if(!hasDishes){
                this.getRecipeDetailByDate()
            }
        },
        // 获取指定日期菜谱计划菜品详情
        getRecipeDetailByDate(){
            let param = {
                "applyDate": this.dateRangeRadio,
                "recipeId": this.baseInfo.recipeId
            }
            getMenuRecipeDetailApi(param).then((response) => { 
                if(response.data.length>0){
                    for (let i = 0; i < response.data.length; i++) {
                        this.detailList.forEach(item=>{
                            if(item.mealtimeType==response.data[i].mealtimeType){
                                item.dishesList = response.data[i].dishesList;
                                item.dishesList.forEach(dish=>{
                                    this.$set(dish,'dishesNum',null) 
                                })
                            }
                        }) 
                    } 
                    // setTimeout(()=>{
                        for (let i = 0; i < this.resDetailList.length; i++) {
                            this.dateRangeList.forEach(item=>{
                                if(this.resDetailList[i].detailDate==item.applyDate){
                                    item.detailList.forEach(subItem=>{
                                        if(this.resDetailList[i].mealtimeType==subItem.mealtimeType){ 
                                            subItem.dishesList.forEach(lastItem=>{
                                                if(this.resDetailList[i].dishesId==lastItem.dishesId){
                                                    this.$set(lastItem,'dishesNum',this.resDetailList[i].dishesNum) 
                                                } 
                                            }) 
                                        }
                                    })
                                } 
                            }) 
                        }
                    // },500) 
                }
            });
        },
        //保存草稿
        confirmSave(){
            this.$refs["baseInfo"].validate(valid => {
                if (valid) {
                    let param = Object.assign({},this.baseInfo); 
                    param.ifRepeat=this.ifRepeat;
                    param.productionPlanType=this.dialogType;
                    param.status=1;
                    param.goodsType=1;
                    param.productionPlanDetailAddList=[]; 
                    if(this.dialogType==1){ 
                        console.log(this.dateRangeList)
                        if(this.ifRepeat==1){
                            for(let i =0 ;i < this.dateRangeList.length ;i++){
                                for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                    if(this.dateRangeList[0].detailList[j].dishesList.length>0){
                                        this.dateRangeList[0].detailList[j].dishesList.forEach(dishItem=>{ 
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[0].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[0].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            param.productionPlanDetailAddList.push(obj)
                                        }) 
                                    } 
                                }
                            } 
                        }
                        if(this.ifRepeat==2){
                            for(let i =0 ;i < this.dateRangeList.length ;i++){
                                for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                    if(this.dateRangeList[i].detailList[j].dishesList.length>0){
                                        this.dateRangeList[i].detailList[j].dishesList.forEach(dishItem=>{
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[i].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[i].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            param.productionPlanDetailAddList.push(obj)
                                        }) 
                                    } 
                                }
                            } 
                        }
                        console.log(param.productionPlanDetailAddList)  
                    }
                    if(this.dialogType==2){ 
                        var addList = []
                        for(let i =0 ;i < this.dateRangeList.length ;i++){
                            for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                if(this.dateRangeList[i].detailList[j].dishesList.length>0){
                                    this.dateRangeList[i].detailList[j].dishesList.forEach(dishItem=>{ 
                                        if(dishItem.dishesNum>0){
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[i].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[i].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            addList.push(obj)
                                        } 
                                    }) 
                                } 
                            }
                        }
                        console.log(addList)
                        if(param.productionPlanDetailVOList&&param.productionPlanDetailVOList.length>0){
                            addList.forEach(item=>{ 
                                let index = param.productionPlanDetailVOList.findIndex(v=>(v.detailDate==item.detailDate&&v.mealtimeType==item.mealtimeType&&v.dishesId==item.dishesId))
                                param.productionPlanDetailVOList[index].dishesNum = item.dishesNum
                            })
                            param.productionPlanDetailAddList = param.productionPlanDetailVOList 
                        }else{
                            param.productionPlanDetailAddList = addList
                        } 
                        console.log(param.productionPlanDetailAddList)  
                    }
                    console.log(param)
                    if(param.productionPlanDetailAddList.length==0){
                        this.$modal.msgError("请填写菜品份数！");
                    }else{
                        this.loadingBtn=true;
                            if (this.baseInfo.planId != undefined) {
                                editProductionPlanApi(param).then((response) => {
                                    this.$modal.msgSuccess("修改成功");
                                    this.loadingBtn=false
                                    this.jumpList() 
                                }).catch(() => {
                                    this.loadingBtn=false
                                }); 
                            } else {
                                addProductionPlanApi(param).then((response) => {
                                    this.$modal.msgSuccess("保存成功");
                                    this.loadingBtn=false
                                    this.jumpList() 
                                }).catch(() => {
                                    this.loadingBtn=false
                                });  
                            } 
                    } 
                }
            });
        },
        // 提交按钮
        confirmSubmit(){
            this.$refs["baseInfo"].validate(valid => {
                if (valid) { 
                    let param = Object.assign({},this.baseInfo); 
                    param.ifRepeat=this.ifRepeat;
                    param.productionPlanType=this.dialogType;
                    param.status=2;
                    param.goodsType=1;
                    param.productionPlanDetailAddList=[]; 
                    if(this.dialogType==1){ 
                        console.log(this.dateRangeList)
                        if(this.ifRepeat==1){
                            for(let i =0 ;i < this.dateRangeList.length ;i++){
                                for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                    if(this.dateRangeList[0].detailList[j].dishesList.length>0){
                                        this.dateRangeList[0].detailList[j].dishesList.forEach(dishItem=>{ 
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[0].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[0].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            param.productionPlanDetailAddList.push(obj)
                                        }) 
                                    } 
                                }
                            } 
                        }
                        if(this.ifRepeat==2){
                            for(let i =0 ;i < this.dateRangeList.length ;i++){
                                for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                    if(this.dateRangeList[i].detailList[j].dishesList.length>0){
                                        this.dateRangeList[i].detailList[j].dishesList.forEach(dishItem=>{
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[i].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[i].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            param.productionPlanDetailAddList.push(obj)
                                        }) 
                                    } 
                                }
                            } 
                        }
                        console.log(param.productionPlanDetailAddList)  
                    }
                    if(this.dialogType==2){ 
                        var addList = []
                        for(let i =0 ;i < this.dateRangeList.length ;i++){
                            for(let j =0 ;j < this.dateRangeList[0].detailList.length;j++){ 
                                if(this.dateRangeList[i].detailList[j].dishesList.length>0){
                                    this.dateRangeList[i].detailList[j].dishesList.forEach(dishItem=>{ 
                                        if(dishItem.dishesNum>0){
                                            let obj = Object.assign({}, dishItem)   
                                            obj.detailDate = this.dateRangeList[i].applyDate
                                            obj.dishesId=dishItem.dishesId;
                                            obj.dishesName=dishItem.dishesName;
                                            obj.dishesNum=Number(dishItem.dishesNum); 
                                            obj.mealtimeName=this.dateRangeList[i].detailList[j].mealtimeName;
                                            obj.mealtimeType=this.dateRangeList[i].detailList[j].mealtimeType;
                                            obj.dishesNum=dishItem.dishesNum;
                                            obj.sizeType=dishItem.sizeType; 
                                            addList.push(obj)
                                        } 
                                    }) 
                                } 
                            }
                        }
                        console.log(addList)
                        if(param.productionPlanDetailVOList&&param.productionPlanDetailVOList.length>0){
                            addList.forEach(item=>{ 
                                let index = param.productionPlanDetailVOList.findIndex(v=>(v.detailDate==item.detailDate&&v.mealtimeType==item.mealtimeType&&v.dishesId==item.dishesId))
                                param.productionPlanDetailVOList[index].dishesNum = item.dishesNum
                            })
                            param.productionPlanDetailAddList = param.productionPlanDetailVOList 
                        }else{
                            param.productionPlanDetailAddList = addList
                        } 
                        console.log(param.productionPlanDetailAddList)  
                    }
                    console.log(param)
                    if(param.productionPlanDetailAddList.length==0){
                        this.$modal.msgError("请填写菜品份数！");
                    }else{
                        this.loadingBtn=true;
                            if (this.baseInfo.planId != undefined) {
                                editProductionPlanApi(param).then((response) => {
                                    this.$modal.msgSuccess("修改成功");
                                    this.loadingBtn=false
                                    this.jumpList() 
                                }).catch(() => {
                                    this.loadingBtn=false
                                }); 
                            } else {
                                addProductionPlanApi(param).then((response) => {
                                    this.$modal.msgSuccess("保存成功");
                                    this.loadingBtn=false
                                    this.jumpList() 
                                }).catch(() => {
                                    this.loadingBtn=false
                                });  
                            } 
                    } 
                }
            });
        },
 
        //日期
        formatDate(date) {
            // 格式化为 YYYY-MM-DD
            date = new Date(date)
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        //日期时间
        formatDateTime(date) {
            // 格式化为 YYYY-MM-DD
            date = new Date(date)
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
            const day = String(date.getDate()).padStart(2, '0');
            const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
            const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        } 
    }
};
</script>
<style scoped>
    .dishes-card{
        width: 20%;
        height: 100%;
        margin-right: 15px;
        position: relative;
    }
    .body-card{
        width: 96%;
        margin: 10px auto;
        display: flex;
        flex-direction: column;
        height: 300px;
        overflow-y: auto;
    }

    .bottom-card{
        width: 100%;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        bottom: 0;
    }


    .dialog-left{
        width: 25%;
        height: 100%;
    }
    .dish-name{
        width: 100%;
        height: 32px;
        display: flex;
        align-items: center;
        cursor: pointer;
    }
    .dish-name:hover{ 
        background-color:rgba(0, 0, 0, 0.1);
        color: #4b80fd;
    } 

    .dialog-center{
        width: 15%;
        height: 100%;
        /* background: #4b80fd; */
        border: 1px solid #ccc;
        border-radius: 5px;
        margin: 0 1%;
    }
    .dialog-center-header{
        width: 100%;display: flex;align-items: center;justify-content: center;height: 60px;font-weight: bold;border-bottom: 1px solid #ccc;
    }
    .dialog-right{
        width: 73%;
        height: 100%;
        margin: 0 1%;
    }
    .primary{
        background: #1890ff!important;
        color: #fff!important;
    }
    .dateTable{
        width: 14%;
        height: 40px;
        color: #9a9da3;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #e6ebf5;
    }
    .dateTable2{
        width: 14%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fff;
        color:#000;
        border: 1px solid #e6ebf5;
        cursor: pointer;
    }
    .bgBlue{
        width: 14%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #0c6ccc;
        color:#fff !important;
        border: 1px solid #fff;
        cursor: pointer;
    }
</style>