<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="菜单编号" prop="menuNumber">
        <el-input
          v-model="queryParams.menuNumber"
          placeholder="请输入菜单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时段" prop="periodId">
        <el-select v-model="queryParams.periodId" placeholder="请选择时段" clearable size="small">
          <el-option
            v-for="dict in dict.type.consumption_period"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="消费模式" prop="patternId">
        <el-select v-model="queryParams.patternId" placeholder="请选择消费模式" clearable size="small">
          <el-option
            v-for="dict in dict.type.consumption_pattern"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="消费人员类型" prop="consumerType">
        <el-select v-model="queryParams.consumerType" placeholder="请选择消费人员类型" multiple clearable
                   size="small">
          <el-option
            v-for="dict in dict.type.user_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </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"
          v-hasPermi="['canteen:menu:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['canteen:menu:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['canteen:menu:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['canteen:menu:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="menuList" @selection-change="handleSelectionChange" @row-click="refreshSubView">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="菜单id" align="center" prop="menuId" v-if="false"/>
      <el-table-column label="菜单编号" align="center" prop="menuNumber"/>
      <el-table-column label="菜单名称" align="center" prop="menuName"/>
      <el-table-column label="菜单使用日期" align="center" prop="useDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.useDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每人可选菜品数量限制" align="center" prop="maxCount"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['canteen:menu:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['canteen:menu:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="时段" align="center" prop="periodId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.consumption_period" :value="scope.row.periodId"/>
        </template>
      </el-table-column>
      <el-table-column label="消费模式" align="center" prop="patternId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.consumption_pattern" :value="scope.row.patternId"/>
        </template>
      </el-table-column>
      <el-table-column label="消费人员类型" align="center" prop="consumerType" width="220">
        <template slot-scope="scope">
          <el-select v-model="scope.row.consumerType" :disabled="true" placeholder="请选择消费人员类型" multiple>
            <el-option
              v-for="dict in dict.type.user_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
<!--      <el-table-column label="就餐地" align="center" prop="diningPlace"/>-->
      <el-table-column label="机构" align="center" prop="jgid" v-if="false">
        <template slot-scope="scope">
          {{getChangeType(scope.row.jgid)}}
        </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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <!--        <el-form-item label="菜单编号" prop="menuNumber">-->
        <!--          <el-input v-model="form.menuNumber" placeholder="请输入菜单编号" />-->
        <!--        </el-form-item>-->
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" disabled/>
        </el-form-item>
        <el-form-item label="时段" prop="periodId" v-if="sel">
          <el-select v-model="form.periodId" placeholder="请选择时段" @change="defaultName">
            <el-option
              v-for="dict in dict.type.consumption_period"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消费模式" prop="patternId">
          <el-select v-model="form.patternId" placeholder="请选择消费模式" @change="changePattern($event)">
            <el-option
              v-for="dict in dict.type.consumption_pattern"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消费人员类型" prop="consumerType">
          <el-select v-model="form.consumerType" placeholder="请选择消费人员类型" multiple style="width: 80%">
            <el-option
              v-for="dict in dict.type.user_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用时间" prop="useDate" v-if="sel">
          <el-date-picker clearable size="small"
                          v-model="form.useDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择使用时间"
                          @change="defaultName">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="每人可选菜品数量限制" prop="maxCount">
          <el-input v-model="form.maxCount" placeholder=""/>
        </el-form-item>
<!--        <el-form-item label="就餐地" prop="diningPlace">-->
<!--          <treeselect v-model="form.diningPlace" :options="placeOptions" :normalizer="normalizer"  placeholder="请选择就餐地" />-->
<!--        </el-form-item>-->
        <el-form-item label="机构代码" prop="jgid">
          <el-select v-model="form.jgid" disabled>
            <el-option
              v-for="item in organizations"
              :key="item.deptCode"
              :label="item.deptName"
              :value="item.deptCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listMenu, getMenu, delMenu, addMenu, updateMenu, exportMenu} from "@/api/canteen/menu";
  import {queryOrganizationInfo} from "@/api/system/dept";
  import user from "@/store/modules/user";
  import { listPlace } from "@/api/canteen/place";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Menu",
    components: {
      Treeselect
    },
    dicts: ['consumption_period', 'consumption_pattern', 'user_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 菜单表格数据
        menuList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          menuNumber: null,
          menuName: null,
          periodId: null,
          patternId: null,
          consumerType: [],
          jgid: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          menuName: [
            { required: true, message : "菜单名称不能为空", trigger: "blur" }
          ],
          consumerType: [
            { required: true, message : "消费人员类型不能为空", trigger: "blur" }
          ],
          periodId: [
            { required: true, message : "消费时段不能为空", trigger: "blur" }
          ],
          useDate: [
            { required: true, message : "使用日期不能为空", trigger: "blur" }
          ],
          patternId: [
            { required: true, message : "消费模式不能为空", trigger: "blur" }
          ]
        },
        sel: true,
        organizations: [],
        jurisdiction :false,
        // 就餐地树选项
        placeOptions: undefined
      };
    },
    created() {
      this.getList();
      //this.getTreeSelect();
      queryOrganizationInfo().then((response) => {
        this.organizations = response.data;
      });
    },
    methods: {
      refreshSubView(row) {
        // console.log('refreshSubView')
        this.$emit('refreshSubView', row)
      },
      /** 查询菜单列表 */
      getList() {
        this.queryParams.jgid =  user.state.organ;
        this.loading = true;
        listMenu(this.queryParams).then(response => {
          response.rows.forEach(item => {
            let temp = [];
            item.consumerType.split(',').forEach(item1 => {
              temp.push(parseInt(item1))
            })
            item.consumerType = temp;
          })
          this.menuList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          menuId: null,
          menuNumber: null,
          menuName: null,
          periodId: null,
          patternId: null,
          consumerType: [],
          isDelete: null,
          jgid: null,
          useDate: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.menuId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加菜单";
        this.form.jgid = user.state.organ;
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const menuId = row.menuId || this.ids
        getMenu(menuId).then(response => {
          this.form = response.data;
          let temp = [];
          this.form.consumerType.split(",").forEach(
            item => {
              temp.push(parseInt(item))
            }
          );
          this.form.consumerType = temp;
          this.open = true;
          this.title = "修改菜单";
        });
      },
      // changText() {
      //   console.log(this.queryParams.consumerType);
      // },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          this.form.consumerType = this.form.consumerType.join(",");
          if (valid) {
            if (this.form.menuId != null) {
              updateMenu(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addMenu(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
          let temp = [];
          this.form.consumerType.split(",").forEach(
            item => {
              temp.push(parseInt(item))
            }
          );
          this.form.consumerType = temp;
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const menuIds = row.menuId || this.ids;
        this.$modal.confirm('是否确认删除菜单编号为"' + menuIds + '"的数据项？').then(function () {
          return delMenu(menuIds);
        }).then(response => {
          this.getList();
          this.refreshSubView(row)
          this.$modal.msgSuccess(response.data);
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$modal.confirm('是否确认导出所有菜单数据项？').then(() => {
          this.exportLoading = true;
          return exportMenu(queryParams);
        }).then(response => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        }).catch(() => {
        });
      },
      changePattern(val) {
        this.dict.type.consumption_pattern.map(item => {
          if (item.value == val) {
            if (item.value == 3) {
              this.form.useDate = null;
              this.form.periodId = null;
              this.sel = false;
            } else if (item.value == 4) {
              this.form.useDate = null;
              this.form.periodId = null;
              this.sel = false;
            } else {
              this.sel = true;
            }
          }
        })
        this.defaultName();
      },
      getChangeType(e) {
        for (var i = 0; i < this.organizations.length; i++) {
          if (this.organizations[i].deptCode == e) {
            return this.organizations[i].deptName;
          }
        }
      },
      defaultName() {
        var name = '';
        if (this.form.useDate != null){
          name = name + this.form.useDate.substr(5,2) + this.form.useDate.substr(8,2)  + "-";
        }
        this.dict.type.consumption_period.map(item =>{
          if (item.value == this.form.periodId){
            name = name +item.label + "-"
          }
        })
        this.dict.type.consumption_pattern.map(item => {
          if (item.value == this.form.patternId) {
            name = name + item.label;
          }
        })
        this.form.menuName = name;
      },
      getTreeSelect() {
        listPlace({jgid:user.state.organ}).then(response => {
          this.placeOptions = [];
          const data = { placeId: 0, placeName: '顶级节点', children: [] };
          data.children = this.handleTree(response.data, "placeId", "parentId");
          // console.log(data);
          this.placeOptions.push(data);
        });
      },
      /** 转换就餐地数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.placeName,
          label: node.placeName,
          children: node.children
        };
      },
    }
  };
</script>
