<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属区域" prop="areaId">
        <el-cascader v-model="queryParams.areaId"
            :options="treeOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
            :props="{ 
              emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
              checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
              value:'id',label:'label'
            }" clearable @change="handleTreeChange">
          </el-cascader>
      </el-form-item>
      <el-form-item label="所属食堂" prop="canteenId">
        <el-select v-model="queryParams.canteenId" placeholder="请选择所属食堂" clearable style="width: 100%;">
            <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="stallName">
        <el-input 
          v-model="queryParams.stallName"
          placeholder="请输入档口名称"
          clearable maxlength="30"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> 
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>  
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableListData" height="800" border>
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="档口名称" align="center" prop="stallName" :show-overflow-tooltip="true" width="180" fixed="left"/>
      <el-table-column label="所属区域" align="center" prop="areaName" :show-overflow-tooltip="true" width="160"/>
      <el-table-column label="所属食堂" align="center" prop="canteenName" :show-overflow-tooltip="true" width="160"/>
      <el-table-column label="负责人" align="center" prop="manager" :show-overflow-tooltip="true" width="80"/>
      <el-table-column label="联系电话" align="center" prop="contactTel" :show-overflow-tooltip="true" width="100"/>
      <el-table-column label="档口状态" align="center" prop="bizState" :show-overflow-tooltip="true" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.bizState==1">休息</span>
          <span v-if="scope.row.bizState==2">营业</span>
        </template> 
      </el-table-column>
      <el-table-column label="营业时间" align="center" prop="bizStartTime" :show-overflow-tooltip="true" width="180">
        <template slot-scope="scope">
          {{ scope.row.bizStartTime }}-{{ scope.row.bizEndTime }}
        </template> 
      </el-table-column>
      <!-- <el-table-column label="线上流水号前缀" align="center" prop="onLineMealCodePrefix" :show-overflow-tooltip="true" width="120"/>
      <el-table-column label="线下流水号前缀" align="center" prop="offLineMealCodePrefix" :show-overflow-tooltip="true" width="120"/> -->
      <el-table-column label="档口图片" align="center" prop="imgUrl" width="100">
        <template slot-scope="scope"> 
          <img :src="scope.row.imgUrl" v-if="scope.row.imgUrl" alt="" style="width: 80px;height: 40px;" @click="openImg(scope.row)">
          <span v-else>无</span>
        </template>
      </el-table-column> 
      <el-table-column label="创建时间" align="center" prop="createTime" :show-overflow-tooltip="true" width="160"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" :show-overflow-tooltip="true" width="160"/>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope"> 
          <el-button
            size="mini"
            type="text" 
            @click="handleUpdate(scope.row)" 
          >编辑</el-button>
          <el-button
            size="mini"
            type="text" style="color: red;"
            @click="handleDelete(scope.row)" 
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title+'-档口'" :visible.sync="open" width="1200px" append-to-body>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 基础设置 -->
        <el-tab-pane label="基础设置" name="baseSetting" style="height: 500px;overflow-y: auto;">
          <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="档口名称" prop="stallName">
                  <el-input  v-model="baseForm.stallName" placeholder="请输入档口名称" maxlength="30" clearable/>
                </el-form-item> 
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属区域" prop="areaId">
                  <el-cascader v-model="baseForm.areaId"
                    :options="treeOptions" :filterable="true" style="width: 100%;" :show-all-levels="false"
                    :props="{ 
                      emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
                      checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
                      value:'id',label:'label'
                    }"
                    clearable @change="handleTreeChange2" >
                  </el-cascader>
                </el-form-item>
              </el-col> 
              <el-col :span="12">
                <el-form-item label="所属食堂" prop="canteenId">
                  <el-select v-model="baseForm.canteenId" placeholder="请选择所属食堂" style="width: 100%;">
                      <el-option v-for="item in canteenOptions2"
                          :key="item.canteenId"
                          :label="item.canteenName"
                          :value="item.canteenId"
                      ></el-option>
                  </el-select> 
                </el-form-item>
              </el-col>  
              <el-col :span="12">
                <el-form-item label="负责人" prop="manager">
                  <el-input
                      v-model="baseForm.manager"
                      type="text" clearable
                      placeholder="请输入负责人"
                      maxlength="30"
                    />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactTel">
                    <el-input v-model="baseForm.contactTel" placeholder="请输入联系电话" maxlength="11" clearable 
                              @input="(v)=>(baseForm.contactTel=v.replace(/[^\d]/g,''))"/>
                </el-form-item>
              </el-col>  
              <el-col :span="12">
                <el-form-item label="营业时间">
                  <el-time-picker
                    is-range 
                    v-model="rangeTime"
                    value-format="HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" style="width: 100%;"
                    placeholder="选择时间范围">
                  </el-time-picker>
                </el-form-item> 
              </el-col> 
              <el-col :span="12">
                  <el-form-item label="营业状态">
                    <el-select v-model="baseForm.bizState" placeholder="请选择营业状态" style="width: 100%;" clearable>
                      <el-option label="休息" :value="1" />
                      <el-option label="营业" :value="2" />
                    </el-select> 
                  </el-form-item> 
              </el-col> 
              <!-- <el-col :span="12">
                <el-form-item label="线上流水号前缀" prop="onLineMealCodePrefix"> 
                  <el-input v-model="baseForm.onLineMealCodePrefix" placeholder="请输入线上流水号前缀" maxlength="30" clearable/>
                </el-form-item>
              </el-col> 
              <el-col :span="12">
                <el-form-item label="线下流水号前缀" prop="offLineMealCodePrefix"> 
                  <el-input v-model="baseForm.offLineMealCodePrefix" placeholder="请输入线下流水号前缀" maxlength="30" clearable/>
                </el-form-item>
              </el-col> -->
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="档口图片">
                  <el-upload
                        :http-request="(obj) => imgUpLoad(obj, 'fileUrl')"
                        action="#"
                        :limit="1"
                        :file-list="fileList"
                        :show-file-list="true"
                        list-type="picture-card"
                        accept=".png, .jpg, .jpeg"
                        :on-success="handleAvatarSuccess"
                        :class="{ disabled: uploadDisabled }"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                    >
                        <i
                            class="el-icon-plus avatar-uploader-icon"
                        ></i>
                    </el-upload>
                </el-form-item>
              </el-col>
            </el-row>  
          </el-form>
        </el-tab-pane> 
        <!-- 预订/点餐/报餐设置 -->
        <el-tab-pane label="餐次设置" name="orderSetting" style="height: 500px;overflow-y: auto;">  
          <el-table :data="mealtimeList" height="400" >
            <el-table-column label="餐次类型" align="center" prop="mealtimeName"/> 
            <el-table-column label="餐次时段" align="center" >
              <template slot-scope="scope">
                <el-time-picker
                  is-range
                  v-model="scope.row.orderTimeList" style="width: 200px;"
                  range-separator="至" format="HH:mm:ss" value-format="HH:mm:ss" 
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围" @change="changeOrderTimeList(scope.row)">
                </el-time-picker>
                <!-- <span>{{scope.row.startTime}}</span>-<span>{{scope.row.endTime}}</span> -->
              </template> 
            </el-table-column>
            <el-table-column label="是否启用" align="center" >
              <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.ifEnable"
                    active-value="1"
                    inactive-value="2" 
                ></el-switch>
              </template> 
            </el-table-column>
            <!-- <el-table-column label="预定餐" align="center"> 
                <el-table-column label="预定时段" align="center" width="220">
                    <template slot-scope="scope">
                      <el-time-picker
                        is-range :clearable="true"
                        v-model="scope.row.reserveTimeList"  style="width: 190px;"
                        range-separator="至" format="HH:mm:ss" value-format="HH:mm:ss" 
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        placeholder="选择时间范围" @change="changeReserveTimeList(scope.row)">
                      </el-time-picker>
                    </template>
                </el-table-column>
                <el-table-column label="退单截止时间" align="center" width="150">
                    <template slot-scope="scope">
                      <el-time-picker
                        v-model="scope.row.reserveRefundDeadline" style="width: 120px;"
                        placeholder="选择时间">
                      </el-time-picker>
                    </template>
                </el-table-column>
                <el-table-column label="自动打印时间" align="center" width="150">
                    <template slot-scope="scope">
                      <el-time-picker
                        v-model="scope.row.reservePrintTime" style="width: 120px;"
                        placeholder="选择时间">
                      </el-time-picker>
                    </template>
                </el-table-column>
            </el-table-column>
            <el-table-column label="当餐点餐" align="center"> 
                <el-table-column label="点餐时段" align="center" width="220">
                    <template slot-scope="scope">
                      <el-time-picker
                        is-range :clearable="true"
                        v-model="scope.row.currTimeList" style="width: 190px;"
                        range-separator="至" format="HH:mm:ss" value-format="HH:mm:ss" 
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        placeholder="选择时间范围" @change="changeCurrTimeList(scope.row)">
                      </el-time-picker>
                    </template>
                </el-table-column>
                <el-table-column label="退单截止时间" align="center" width="150">
                    <template slot-scope="scope">
                      <el-time-picker
                        v-model="scope.row.currRefundDeadline" style="width: 120px;" 
                        placeholder="选择时间">
                      </el-time-picker>
                    </template>
                </el-table-column>
            </el-table-column>  
            <el-table-column label="状态" align="center" prop="ifUse" width="150">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.ifUse"
                    active-text="开启"
                    inactive-text="关闭"
                    :active-value="1"
                    :inactive-value="2">
                  </el-switch>
                </template>
            </el-table-column> -->
          </el-table> 
        </el-tab-pane>
      </el-tabs> 
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      
    </el-dialog>
 

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>





  </div>
</template>

<script>
import { systemAreaTreeApi,getCanteenByAreaApi, getPageStallApi, addStallApi, getStallInfoModifyApi, updateStallApi, removeStallApi } from "@/api/base/stall";
import { imgUpLoadTwo } from '@/api/system/upload'
// import C from "highlight.js/lib/languages/1c";
export default {
  name: "",
  dicts: ['stall_type','stall_tag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      tableListData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      treeOptions:[],//区域树
      treeProps:{
        multiple: true,
        value:"id",
        label:"label",
        children:"children",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaId: undefined,
        stallName: undefined,
        canteenId: undefined
      },
      canteenOptions:[],//查询-食堂下拉选 
      activeName:"baseSetting",
      areaId:"",
      stallId:"",//档口数据-编辑
      stallData:{},//档口数据-编辑
      baseForm: {
        "offLineMealCodePrefix": null,
        "onLineMealCodePrefix": null,
        "payCodeUrl": null,
        "areaId": "",
        "canteenId": "",  
        "stallName": "", 
        "contactTel": "",
        "manager": "",
        "bizEndTime": "",
        "bizStartTime": "", 
        "imgUrl": "", 
      },//基础设置
      rangeTime:["08:00:00", "18:00:00"],//营业时间
      canteenOptions2:[],//弹窗食堂下拉选
      // 表单校验
      baseFormRules: {
        stallName: [
          { required: true, message: "档口名称不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "所属区域不能为空", trigger: "blur" }
        ],
        canteenId: [
          { required: true, message: "所属食堂不能为空", trigger: "blur" }
        ],
        contactTel: [
            {
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                message: '请输入正确的手机号码',
                trigger: 'blur',
            }
        ] 
      },
      mealtimeList:[
        {
          "mealtimeType": "1",
          "mealtimeName": "早餐",
          "orderTimeList":["05:00:00","10:00:00"],
          "startTime": "05:00:00",
          "endTime": "10:00:00",
          "ifEnable":"1"
        },
        {
          "mealtimeType": "2",
          "mealtimeName": "午餐",
          "orderTimeList":["10:00:01","14:00:00"],
          "startTime": "10:00:01",
          "endTime": "14:00:00",
          "ifEnable":"1"
        },
        {
          "mealtimeType": "3",
          "mealtimeName": "下午茶",
          "orderTimeList":["14:00:01","18:00:00"],
          "startTime": "14:00:01",
          "endTime": "18:00:00",
          "ifEnable":"1"
        },
        {
          "mealtimeType": "4",
          "mealtimeName": "晚餐",
          "orderTimeList":["18:00:01","21:00:00"],
          "startTime": "18:00:01",
          "endTime": "21:00:00",
          "ifEnable":"1"
        },
        {
          "mealtimeType": "5",
          "mealtimeName": "夜宵",
          "orderTimeList":["21:00:01","23:59:59"],
          "startTime": "21:00:01",
          "endTime": "23:59:59",
          "ifEnable":"1"
        } 
      ],//餐次列表
      fileList: [],//档口图片
      checkUrlList: [],//档口图片
      checkUrlNameList: [],//档口图片
      dialogVisible:false,//图片弹窗
      dialogImageUrl:"",//图片弹窗  
    };
  },
  created() {
    this.getTreeData();
    this.getList();
    
  },
  computed: {
      //图片上传1张后，隐藏上传框
      uploadDisabled() {
          return this.checkUrlList.length > 0
      },
  },
  methods: {
      //区域树
      getTreeData() {
        systemAreaTreeApi({}).then((response) => {
          this.treeOptions = response.data;
        });
      },
      handleTreeChange(e){ 
        let param= {
          "areaId":e,
          "canteenType":1,
          "pagenation":true
        }
        getCanteenByAreaApi(param).then((response) => {
          this.canteenOptions=response.rows||[]
          this.queryParams.canteenId=null
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
          this.queryParams.pageNum = 1;
          this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
          this.queryParams = {
            pageNum: 1,
            pageSize: 10,
            areaId: undefined,
            stallName: undefined,
            canteenId: undefined
          }
          this.resetForm("queryForm");
          this.handleQuery();
      },
      /** 查询列表 */
      getList() {
          this.loading = true;
          let param = {
            "pageNum": this.queryParams.pageNum, 
            "pageSize": this.queryParams.pageSize,
            "pagenation":true,
            "stallName": this.queryParams.stallName,
            "canteenId": this.queryParams.canteenId,
            "areaId": this.queryParams.areaId
          }
          getPageStallApi(param).then(response => {
              this.tableListData = response.rows;
              this.total = Number(response.total);
              this.loading = false;
          });
      },
 
      handleTabClick(tab, event) {
        console.log(tab, event);
      },
      /** 新增按钮操作 */
      handleAdd() {
          this.stallId=""
          this.reset(); 
          this.activeName="baseSetting"
          this.open = true;
          this.title = "新增";
      },
      // 取消按钮
      cancel() {
          this.open = false;
          this.reset();
      },
      // 表单重置
      reset() {
          this.fileList=[]
          this.checkUrlList=[]
          this.baseForm = {}; 
          this.rangeTime=["08:00:00", "18:00:00"]
          this.resetForm("baseForm");
      }, 
      /** 修改按钮操作 */
      handleUpdate(row) {
        console.log(row)
          this.reset();
          this.activeName="baseSetting"
          getStallInfoModifyApi(row.stallId).then(response => {
              this.stallId = response.data.stallId;
              this.baseForm = response.data;
              if(response.data.imgUrl){
                this.fileList=[{url:response.data.imgUrl}]
                this.checkUrlList=[response.data.imgUrl]
              }else{
                this.fileList=[]
                this.checkUrlList=[]
              }
              this.areaId = this.baseForm.areaId
              setTimeout(()=>{
                // 选择区域后获取相应食堂
                getCanteenByAreaApi({"areaId":row.areaId,"canteenType": 1}).then((response) => {
                  this.canteenOptions2=response.rows||[] 
                  this.$forceUpdate()
                }); 
              },200)
              this.rangeTime=[response.data.bizStartTime, response.data.bizEndTime]
              if(response.data.basicStallMealtimeList&&response.data.basicStallMealtimeList.length>0){
                this.mealtimeList = response.data.basicStallMealtimeList
                this.mealtimeList.forEach(item=>{
                  this.$set(item,"orderTimeList",[item.startTime,item.endTime]) 
                })
              }
              
              this.open = true;
              this.title = "修改";
          });
      },
      /** 删除按钮操作 */
      handleDelete(row) { 
          this.$modal.confirm('是否确认删除数据项？').then(function() {
              return removeStallApi(row.stallId);
          }).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
      }, 
      /** 提交按钮 */
      submitForm: function() {
          console.log(this.baseForm)
          console.log(this.rangeTime)
          this.$refs["baseForm"].validate(valid => {//基本设置表单校验
          if (valid) {
            this.baseForm.bizStartTime=this.rangeTime[0]
            this.baseForm.bizEndTime=this.rangeTime[1]
            this.baseForm.imgUrl = this.checkUrlList[0] 
            this.baseForm.basicStallMealtimeList = this.mealtimeList
            let param = this.baseForm
            if (this.stallId != "") {
              param.stallId = this.stallId
              updateStallApi(param).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                });
            } else {
                addStallApi(param).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                });
            }
          }
          });
      },
      changeOrderTimeList(row){
          console.log(row)
          row.startTime = row.orderTimeList[0]
          row.endTime = row.orderTimeList[1]
      },
      // 状态修改
      handleStatusChange(row) {
          // let text = row.status === '0' ? '启用' : '停用'
          // this.$modal
          //     .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
          //     .then(function () {
          //         return changeUserStatus(row.userId, row.status)
          //     })
          //     .then(() => {
          //         this.$modal.msgSuccess(text + '成功')
          //     })
          //     .catch(function () {
          //         row.status = row.status === '0' ? '1' : '0'
          //     })
      },
      //基础设置-选择区域
      handleTreeChange2(val){  
          if(val){ 
            let param= {"areaId":val,"canteenType": 1}
            // 选择区域后获取相应食堂
            getCanteenByAreaApi(param).then((response) => {
                this.canteenOptions2=response.rows||[] 
                this.$set(this.baseForm,"canteenId",null)
            });
          }   
      },
      


      // 档口图片上传
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      openImg(row) {
        this.dialogImageUrl = row.imgUrl;
        this.dialogVisible = true;
      },
      // 图片上传
      imgUpLoad(param, name, index) {
          // console.log(param,'image')
          param.type = 'stall'
          imgUpLoadTwo(param).then((res) => {
              if (res.code == 200) {
                  this.checkUrlList.push(res.data.url)
                  this.checkUrlNameList.push(res.data.name)
              } else { 
                  this.$modal.msgError(res.msg)
              }
          })
          .catch((error) => { 
              this.$modal.msgError(error)
          })
      },
      handleAvatarSuccess(res, file) {
          console.log('success')
      },
      handleExceed(files, fileList) {
          this.$message.warning('最多只可以上传一张图片')
      },
      handleRemove(file, fileList) {
          let sum = 0
          this.checkUrlNameList.forEach((item, index) => {
              if (item == file.name) {
                  sum = index
              }
          })
          this.checkUrlNameList.splice(sum, 1)
          this.checkUrlList.splice(sum, 1)
      },
      //图片点击查看
      handlePictureCardPreview(file) {
          console.log(file)
          this.dialogImageUrl = file.url
          this.dialogVisible = true
      }




      
  }
};
</script>
<style lang="scss" scoped>
  //隐藏图片上传框的css
  ::v-deep.disabled {
      .el-upload--picture-card {
          display: none;
      }
  }
</style>