<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食谱日期">
        <!--        <el-input v-model="queryForm.mealDate" placeholder="请输入食谱日期"></el-input>-->
        <el-date-picker
          type="date"
          v-model="queryForm.date"
          value-format="yyyy-MM-dd"
          placeholder="请输入食谱日期">
        </el-date-picker>
      </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="['system:recipes: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="['system:recipes: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="['system:recipes:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:recipes:export']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:recipes:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recipesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="食谱日期" align="center" prop="date"/>
      <el-table-column label="早餐" align="center" prop="breakfast"/>
      <el-table-column label="早点" align="center" prop="dessertAfterBreakfast"/>
      <el-table-column label="午餐" align="center" prop="lunch"/>
      <el-table-column label="午点" align="center" prop="dessertAfterLunch"/>
      <el-table-column label="晚餐" align="center" prop="dinner"/>
      <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="['system:recipes:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:recipes:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      :pageSizes="[5,10,20,50]"
      @pagination="getList"
    />
    <!-- 添加或修改学校每日食谱对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
                          style="width: 100%"
                          v-model="form.date"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择食谱日期">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="早餐" prop="breakfast">
              <el-input v-model="form.breakfast" placeholder="请输入早餐"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="早点" prop="dessertAfterBreakfast">
              <el-input v-model="form.dessertAfterBreakfast" placeholder="请输入早点"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="午餐" prop="lunch">
              <el-input v-model="form.lunch" placeholder="请输入午餐"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="午点" prop="dessertAfterLunch">
              <el-input v-model="form.dessertAfterLunch" placeholder="请输入午点"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="晚餐" prop="dinner">
          <el-input v-model="form.dinner" placeholder="请输入晚餐"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>

      </div>
    </el-dialog>
    <!-- 导入对话框相关 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        :limit="1"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :headers="upload.headers"
        :http-request="excelFileUploadMain"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--<div class="el-upload__tip" slot="tip">-->
          <!--  <el-checkbox v-model="upload.updateSupport"/>-->
          <!--  是否更新已经存在的用户数据-->
          <!--</div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecipes,
  getRecipes,
  delRecipes,
  addRecipes,
  updateRecipes,
  handleImport
} from "@/api/smartSchool/mealAdministrate/recipes.js";
import {getToken} from "@/utils/auth";

export default {
  name: "Recipes",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校每日食谱表格数据
      recipesList: [
        //   {
        //   mealDate:'11',
        //   breakfast:'n22ll',
        //   breakfastDessert:'n333ull',
        //   noon:'nul444l',
        //   noonDessert:'555',
        //   supper:55555555,
        // }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数

      queryForm: {
        pageNum: 1,
        pageSize: 10,
        date: '',
      },
      // 表单参数
      form: {
        id: null,
        date: null,
        breakfast: null,
        dessertAfterBreakfast: null,
        lunch: null,
        dessertAfterLunch: null,
        dinner: null,
      },
      // 表单校验
      rules: {
        date: [{required: true, message: '日期不能为空', trigger: 'change'}],
        breakfast: [{required: true, message: '早餐不能为空', trigger: 'blur'}],
        breakfastDessert: [{required: true, message: '早点不能为空', trigger: 'blur'}],
        noon: [{required: true, message: '午餐不能为空', trigger: 'blur'}],
        noonDessert: [{required: true, message: '午点不能为空', trigger: 'blur'}],
        dinner: [{required: true, message: '晚餐不能为空', trigger: 'blur'}],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + `/schoolRecipes/import/`,
      },

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询学校每日食谱列表 */
    getList() {
      this.loading = true;
      listRecipes(this.queryForm).then(response => {
        // this.recipesList = response.rows.filter(el => {
        //   if (this.queryForm.date !== null) {
        //     const date = this.queryForm.date
        //     const dateStr = `${ date.getFullYear() }-${ date.getMonth() + 1 }-${ date.getDate() }`
        //     return el.date === dateStr
        //   } else {
        //     return true
        //   }
        // });
        this.recipesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        breakfast: null,
        dessertAfterBreakfast: null,
        lunch: null,
        dessertAfterLunch: null,
        dinner: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        date: null,
      }
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校每日食谱";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecipes(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学校每日食谱";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id !== null) {
            updateRecipes(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.loading = false
              this.open = false;
              this.getList();
            });
          } else {
            addRecipes(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.loading = false
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该食谱').then(function () {
        return delRecipes(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const ids = this.ids
      if (ids) {
        this.download(`schoolRecipes/export/${ids}`, {
          ...this.queryForm
        }, `recipes_${new Date().getTime()}.xlsx`)
      } else {
        this.download(`schoolRecipes/export/`, {}, `recipes_${new Date().getTime()}.xlsx`)
      }
    },
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      // console.log(event, file, fileList);
    },
    // // 文件上传自定义函数
    async excelFileUploadMain(fileObj) {
      //将文件放进表单对象进行上传
      let res;
      let fd = new FormData();
      fd.append("file", fileObj.file);
      try {
        // res = (await handleImport(fd)).data;
        res = await handleImport(fd);
        // console.log(res);
        //沿袭文件上传成功时的响应函数
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        await this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          res.msg +
          "</div>",
          "导入结果",
          {dangerouslyUseHTMLString: true}
        );
        this.getList();
      } catch (error) {
        console.error(error);
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$message.error(res.msg);
      }
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    importTemplate() {
      this.download(
        "/schoolRecipes/importTemplate",
        {},
        `内容模板_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
