<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" :show-all-levels="false" :filterable="true"
            :options="treeOptions" :props="treeProps" collapse-tags clearable
            @change="handleTreeChange"></el-cascader>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
            <el-select v-model="queryParams.warehouseId" clearable placeholder="请选择所属仓库" style="width: 100%;">
                <el-option v-for="item in wareHouseOptions"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item.warehouseId"
                ></el-option>
            </el-select> 
        </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">
        <el-table-column label="序号" align="center" width="100" type="index" fixed="left">
                <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="areaName" :show-overflow-tooltip="true"/> 
        <el-table-column label="仓库" align="center" prop="warehouseName" :show-overflow-tooltip="true"/>
        <el-table-column label="超市名称" align="center" prop="supermarketName" :show-overflow-tooltip="true"/>
        <el-table-column label="线上超市模式" align="center" prop="appSaleMode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <span v-if="scope.row.appSaleMode==1">现货</span>
                <span v-if="scope.row.appSaleMode==2">预定</span>
              </template>
        </el-table-column>
        <el-table-column label="超市地址" align="center" prop="address" :show-overflow-tooltip="true"/>
        <el-table-column label="图片" align="center" prop="imgUrl" width="120">
          <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="manager" :show-overflow-tooltip="true" width="100"/>
        <el-table-column label="更新时间" align="center" prop="updateTime" :show-overflow-tooltip="true" width="160"/>
        <el-table-column label="收款码" align="center" prop="payCodeUrl" :show-overflow-tooltip="true" width="120">
          <template slot-scope="scope">
            <span>未开启</span>
          </template>
        </el-table-column>  
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <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: 550px;overflow-y: auto;">
            <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-width="140px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="超市名称" prop="supermarketName">
                    <el-input  v-model="baseForm.supermarketName" 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: 400px;" :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="warehouseId"> 
                    <el-select v-model="baseForm.warehouseId" placeholder="请选择超市仓库" clearable style="width: 100%;">
                        <el-option v-for="item in wareHouseOptions2"
                            :key="item.warehouseId" 
                            :label="item.warehouseName"
                            :value="item.warehouseId" 
                        ></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" placeholder="请输入管理员" maxlength="30" clearable/>
                  </el-form-item>
                </el-col>  
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="mobile">
                      <el-input v-model="baseForm.mobile" placeholder="请输入联系电话" maxlength="11" clearable 
                                @input="(v)=>(baseForm.mobile=v.replace(/[^\d]/g,''))"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="超市地址" prop="address">
                    <el-input  v-model="baseForm.address" placeholder="请输入超市地址" maxlength="30" clearable/>
                  </el-form-item> 
                </el-col>  
                <!-- <el-col :span="12">
                  <el-form-item label="用户类别" prop="userType">
                    <el-select v-model="baseForm.userType" style="width: 100%" clearable>
                      <el-option
                        v-for="dict in dict.type.sys_user_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="Number(dict.value)"
                      />
                    </el-select>  
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="配送费" prop="deliveryCost">
                    <el-input  v-model="baseForm.deliveryCost" placeholder="请输入配送费" maxlength="30" clearable
                        @input="(v)=>(baseForm.deliveryCost=v.replace(/[^\d]/g,''))"/>
                  </el-form-item> 
                </el-col>   -->
                <el-col :span="12">
                  <el-form-item label="线上超市模式" prop="appSaleMode">
                    <el-select v-model="baseForm.appSaleMode" style="width: 100%" clearable> 
                        <el-option label="现货" value="1"></el-option>
                        <el-option label="预定" value="2"></el-option>
                        </el-select>  
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最少配送时间(分钟)" prop="minDeliveryTime">
                    <el-input  v-model="baseForm.minDeliveryTime" placeholder="请输入配最少配送时间" maxlength="30" clearable
                        @input="(v)=>(baseForm.minDeliveryTime=v.replace(/[^\d]/g,''))"/>
                  </el-form-item> 
                </el-col>  
                <el-col :span="12">
                  <el-form-item label="选择时间间隔(分钟)" prop="selectTimeInterval">
                    <el-select v-model="baseForm.selectTimeInterval" style="width: 100%" clearable> 
                        <el-option label="15" value="15"></el-option>
                        <el-option label="20" value="20"></el-option>
                        <el-option label="30" value="30"></el-option>
                        <el-option label="60" value="60"></el-option>
                        </el-select>  
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="可退单时间(分钟)" prop="refundLimitTime">
                    <el-input  v-model="baseForm.refundLimitTime" placeholder="请输入可退单时间(分钟)" maxlength="30" clearable
                        @input="(v)=>(baseForm.refundLimitTime=v.replace(/[^\d]/g,''))"/>
                  </el-form-item> 
                </el-col>  
                <el-col :span="12">
                    <el-form-item label="流水号前缀" prop="mealCode">
                        <el-input  v-model="baseForm.mealCode" placeholder="请输入流水号前缀" maxlength="30" clearable
                            @input="(v)=>(baseForm.mealCode=v.replace(/[^\d]/g,''))"/>
                    </el-form-item> 
                </el-col>
                <el-col :span="12"> 
                    <el-form-item label="配送方式" prop="deliveryWay">
                        <el-select v-model="baseForm.deliveryWay" style="width: 100%" clearable> 
                            <el-option label="自取" value="1"></el-option>
                            <el-option label="配送" value="2"></el-option> 
                        </el-select>   
                  </el-form-item> 
                </el-col>  
                <el-col :span="12">
                  <el-form-item label="是否关联出入库" prop="ifRelateDrp">
                    <el-switch
                      v-model="baseForm.ifRelateDrp"
                      active-text="开启"
                      inactive-text="关闭"
                      :active-value="1"
                      :inactive-value="2">
                    </el-switch>
                  </el-form-item>
                </el-col> 
                <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="paySetting" style="height: 550px;overflow-y: auto;">
            <div style="width: 100%;height: 400px;display: flex;align-items: center;justify-content: center;">暂无数据</div>
          </el-tab-pane>  -->
        </el-tabs> 
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="loadingBtn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="dialogVisible" width="700px">
        <img style="width: 100%;height: 100%;" :src="dialogImageUrl" alt="">
      </el-dialog>





    </div>
  </template>
  
  <script>
  import { systemAreaTreeApi } from "@/api/base/area";
  import { drpWareHousePageApi,supermarketPageListApi,insertSupermarketApi,editSupermarketApi,deleteSupermarketApi,userListByRoleApi } from "@/api/superStore/super";
  import { imgUpLoadTwo } from '@/api/system/upload'
  export default {
    name: "",
    dicts: ['sys_user_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        loadingBtn: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        tableListData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        treeOptions:[],//区域树
        treeProps:{ 
          value:"id",
          emitPath: false,// 若设置 false，则只返回该节点的值，只返回最后选择的id
          checkStrictly: false,//来设置父子节点取消选中关联，从而达到选择任意一级选项的目的
          label:"label",
          children:"children",
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          warehouseId: undefined,
          areaId: undefined, 
        },
        wareHouseOptions:[],
        wareHouseOptions2:[],
        psnTypeOptions:[],
        userOptions:[],
        activeName:"baseSetting",
        canteenId:"",//食堂数据-编辑
        canteenData:{},//食堂数据-编辑
        baseForm: {
          "areaId": "",     
          "ifRelateDrp": 2,
          "imgUrl": "", 
        },//基础设置
        configList:[
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期一",
                    "weekType": 1
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期二",
                    "weekType": 2
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期一",
                    "weekType": 1
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期三",
                    "weekType": 3
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期四",
                    "weekType": 4
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期五",
                    "weekType": 5
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期六",
                    "weekType": 6
                },
                {   
                    "ifBusiness": 1,
                    "ifReserveFetch": 2,
                    "closingTime": "23:59:59",
                    "openingTime": "00:00:00",
                    "weekName": "星期日",
                    "weekType": 7
                }

        ],
        // 表单校验
        baseFormRules: {
          supermarketName: [
            { required: true, message: "超市名称不能为空", trigger: "blur" }
          ],
          areaId: [
            { required: true, message: "所属区域不能为空", trigger: "blur" }
          ],
          deliveryWay: [
            { required: true, message: "配送方式不能为空", trigger: "change" }
          ],
          mobile: [
            {
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                message: '请输入正确的手机号码',
                trigger: 'blur',
            }
          ]
        },  
        // 总条数
        dialogTotal: 0,
        currentCustRow:{},//选中的负责人数据
        fileList: [],//食堂图片
        checkUrlList: [],//食堂图片
        checkUrlNameList: [],//食堂图片
        dialogVisible:false,//图片弹窗
        dialogImageUrl:"",//图片弹窗  
         
        deliveriesList:[],//配送类型

        orderDTO:{},//订单设置
        mealtimeList:[],//餐次列表

      };
    },
    created() {
      this.getTreeData();
      this.getWareHouse();
      this.getList();  
      // this.mgruserListByRole();
      
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.checkUrlList.length > 0
        },
    },
    methods: {
        //区域树
        getTreeData() {
          systemAreaTreeApi({}).then((response) => {
            this.treeOptions = response.data;
            console.log(this.treeOptions) 
          });
        },
        handleTreeChange(e){
            console.log(e) 
            let param = {
                areaId:e
            } 
            drpWareHousePageApi(param).then(response => {
                this.wareHouseOptions = response.rows
                this.queryParams.warehouseId = null
            });
        },
        getWareHouse() {
            drpWareHousePageApi({}).then(response => {
                this.wareHouseOptions = response.rows 
                this.wareHouseOptions2 = response.rows 
            });
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() { 
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 查询列表 */
        getList() {
            this.loading = true; 
            let param = {
              "pageNum": this.queryParams.pageNum, 
              "pageSize": this.queryParams.pageSize,
              "warehouseId": this.queryParams.warehouseId,
              "areaId":this.queryParams.areaId
            }
            supermarketPageListApi(param).then(response => {
                this.tableListData = response.rows;
                this.total = Number(response.total);
                this.loading = false;
            });
        },
        handleTabClick(tab, event) {
          console.log(tab, event);
        },
        /** 新增按钮操作 */
        handleAdd() { 
            this.reset(); 
            this.open = true;
            this.title = "新增";
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.fileList=[]
            this.checkUrlList=[]
            this.baseForm = {
                "areaId": "",     
                "ifRelateDrp": 2,
                "imgUrl": "", 
            }
            this.baseForm = {}; 
            this.resetForm("baseForm");
        }, 
        /** 修改按钮操作 */
        handleUpdate(row) {
            console.log(row)
            this.reset(); 
            this.baseForm = Object.assign({}, row)
            // let param = {
            //     areaIdList:[this.baseForm.areaId]
            // } 
            // drpWareHousePageApi(param).then(response => {
            //     this.wareHouseOptions2 = response.rows 
            // });
            if(row.imgUrl){
                this.fileList=[{url:row.imgUrl}]
                this.checkUrlList=[row.imgUrl]
            }else{
                this.fileList=[]
                this.checkUrlList=[]
            }
            this.open = true;
            this.title = "修改"; 
        },
        /** 删除按钮操作 */
        handleDelete(row) { 
            this.$modal.confirm('是否确认删除数据项？').then(function() {
                return deleteSupermarketApi({supermarketId:row.supermarketId});
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        /** 提交按钮 */
        submitForm: function() {
            console.log(this.baseForm) 
            this.$refs["baseForm"].validate(valid => {//基本设置表单校验
            if (valid) { 
              this.loadingBtn=true
              this.baseForm.imgUrl = this.checkUrlList[0]
              let param = this.baseForm
              // param.configList = this.configList; 
              if (param.supermarketId) { 
                  editSupermarketApi(param).then(response => {
                      this.$modal.msgSuccess("修改成功");
                      this.open = false;
                      this.loadingBtn = false;
                      this.getList();
                  });
              } else {
                  insertSupermarketApi(param).then(response => {
                      this.$modal.msgSuccess("新增成功");
                      this.open = false;
                      this.loadingBtn = false;
                      this.getList();
                  });
              }
            }
            });
        },
        //基础设置-选择区域
        handleTreeChange2(val){
            // let param = {
            //     areaIdList:[val]
            // } 
            // drpWareHousePageApi(param).then(response => {
            //     this.wareHouseOptions2 = response.rows 
            //     this.baseForm.warehouseId = null
            // });
        },
        //商户类用户
        mgruserListByRole(){
          let param = {
            "roleKey": "ROLE_MERCHANT"
          }
          userListByRoleApi(param).then(response => {
            this.userOptions = response.rows
          });
        },
        //选中
        chosenUser(e){
          let obj = {}
          this.userOptions.forEach(item=>{
            if(item.userId == e){
              obj=item
            }
          }) 
          this.$set(this.baseForm,"mobile",obj.phonenumber)
        },
        // 仓库图片上传
        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 = 'canteen'
            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>
  