<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="xxfbName">
        <el-input v-model="queryParams.xxfbName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="xxfbZt">
        <el-select v-model="queryParams.xxfbZt" placeholder="请选择状态" @keyup.enter.native="handleQuery">
          <el-option v-for="dict in dict.type.info_push_state" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="ml20">
        <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="xxfbList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="名称" min-width="250" align="center" prop="xxfbName" />
      <el-table-column label="状态" align="center" prop="xxfbZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.info_push_state" :value="scope.row.xxfbZt" />
        </template>
      </el-table-column>
      <el-table-column label="查询次数" align="center" prop="num" />
      <el-table-column label="创建时间" align="center" min-width="150" prop="createTime" />
      <el-table-column label="操作" align="center" min-width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <template v-if="scope.row.xxfbZt == '1'">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-search" @click="handleViewDetail(scope.row)">数据
            </el-button>

            <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handlePublish(scope.row)">发布
            </el-button>


            <!--            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"-->
            <!--                         v-hasPermi="['system:role:edit']">-->
            <!--            <span class="el-dropdown-link">-->
            <!--              <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多-->
            <!--            </span>-->
            <!--              <el-dropdown-menu slot="dropdown">-->
            <!--                <el-dropdown-item command="handleViewDetail" icon="el-icon-search"-->
            <!--                                  v-hasPermi="['system:xxfb:edit']">数据-->
            <!--                </el-dropdown-item>-->
            <!--                <el-dropdown-item command="handleExport" icon="el-icon-download"-->
            <!--                                  v-hasPermi="['system:xxfb:edit']">导出-->
            <!--                </el-dropdown-item>-->
            <!--                <el-dropdown-item command="handlePublish" icon="el-icon-s-promotion"-->
            <!--                                  v-hasPermi="['system:xxfb:edit']">发布-->
            <!--                </el-dropdown-item>-->
            <!--              </el-dropdown-menu>-->
            <!--            </el-dropdown>-->
          </template>
          <template v-if="scope.row.xxfbZt == '2'">
            <el-button size="mini" type="text" icon="el-icon-back" @click="handleRecall(scope.row)"
              v-hasPermi="['system:xxfb:export']">撤回
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewData(scope.row)"
              v-hasPermi="['system:xxfb:view']">数据查看
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)"
              v-hasPermi="['system:xxfb:export']">导出
            </el-button>
          </template>


          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-data"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['system:xxfb:remove']"
          >数据</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExport(scope.row)"
            v-hasPermi="['system:xxfb:export']"
          >导出</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handlePublish(scope.row)"
            v-hasPermi="['system:xxfb:export']"
          >发布</el-button> -->
        </template>

      </el-table-column>
    </el-table>

    <!-- 添加或修改信息发布主表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="980px" @close="dialogClose" append-to-body>
      <b>第一步: 设置查询基本资料本次查询名称</b>
      <el-divider></el-divider>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="查询名称" prop="xxfbName">
          <el-input v-model="form.xxfbName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="级部" prop="gradeId">
          <treeselect v-model="form.gradeId" :options="gradeTree" :show-count="true" @select="deptIdAndName"
            :disable-branch-nodes="true" :defaultExpandLevel="2" placeholder="请选择级部" />
        </el-form-item>
      </el-form>
      <!--      <span style="color: red">*</span>-->
      <b>第二步: 上传查询内容</b> <b @click="changeShow" style="color: #ee6877">（
        点击查看示例 ）</b>
      <el-divider></el-divider>
      <div v-show="isShow">
        <div
          style="font-size: 10px; color: #ed5565; font-weight: 400; background: #d8ecf6; border: 1px solid #03b3f5; padding: 10px">
          注：上传excel文件,第一行为数据表头，不允许合并单元格，列名不要重复，第一列为学号，第二列为姓名。后续不限制
        </div>
        <br />
        <el-table :data="tableData" :border="true" style="width: 100%">
          <!--          <el-table-column type="index" label="序号" width="50">-->
          <!--          </el-table-column>-->
          <el-table-column prop="schoolNo" min-width="120px" label="学号">
          </el-table-column>
          <el-table-column prop="name" label="姓名">
          </el-table-column>
          <el-table-column label="C">
          </el-table-column>
          <el-table-column label="D">
          </el-table-column>
          <el-table-column label="E">
          </el-table-column>
          <el-table-column label="F">
          </el-table-column>
          <el-table-column label="G">
          </el-table-column>
          <el-table-column label="H">
          </el-table-column>
          <el-table-column label="I">
          </el-table-column>
        </el-table>
        <br /> <br />
      </div>
      <el-upload style="width: 950px;display: block; margin: 0 auto;" ref="upload" :limit='1' class="upload-demo"
        action="uploadUrl" accept=".xlsx, .xls" :headers="upload.headers" show-file-list
        :before-upload="handleBeforeUpload" :http-request="uploadImage">
        <el-button style="width: 950px; display: block; margin: 0 auto; background: #54bbbc; color: white">
          点击上传文件
        </el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xlsx, .xls文件</div>
      </el-upload>

      <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 :title="title" :visible.sync="edtion" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="名称" prop="xxfbName">
          <el-input v-model="form.xxfbName" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel_edit">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  infoList,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  getGrade,
  gradeTree,
  publish,
  withdraw,
} from "@/api/smartSchool/gradeWork/infoPublish/index.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Xxfb",
  components: { Treeselect },
  dicts: ['info_push_state'],
  data() {
    return {
      uploadFileData: undefined,
      isShow: false,
      // formDatee: {},
      fileList: [],
      upload: {
        // 设置上传的请求头部
        // headers: {
        //   Authorization: "Bearer " + getToken(),
        //   content-type: 'multipart/form-data'
        // },
        headers: {
          'content-type': 'multipart/form-data'
        }

      },
      tableData: [{
        schoolNo: 'xxxxxxxxxxxxx',
        name: 'xxx',
      }, {
        schoolNo: 'xxxxxxxxxxxxx',
        name: 'xxx',
      }],
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传excel
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 信息发布主表表格数据
      xxfbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        xxfbName: null,
        xxfbZt: null,
        gradeId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        xxfbName: [
          { required: true, message: "查询名称不能为空", trigger: "blur" }
        ],
        gradeId: [
          { required: true, message: "级部不能为空", trigger: "blur" }
        ],
      },
      // 级部树
      gradeTree: [],
      // 级部默认值
      deGrade: '',
      // 是否进入下一步
      unNext: true,
      // 导入文件页面
      importFile: false,
      // 修改页面
      edtion: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询信息发布主表列表 */
    getList() {
      this.loading = true;
      infoList(this.queryParams).then(response => {
        this.xxfbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    cancel_edit() {
      this.edtion = false;
      this.reset();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      // if (this.fileSize) {
      //   const isLt = file.size / 1024 / 1024 < this.fileSize;
      //   if (!isLt) {
      //     this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
      //     return false;
      //   }
      // }
      return true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xxfbName: null,
        xxfbZt: null,
        gradeId: 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.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //树形控件点击事件
    deptIdAndName(node) {
      // this.form.claimBelongName = node.label;
      this.form.gradeId = node.id;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "信息发布新增";
      getGrade().then(response => {
        this.form.gradeId = response.data
      })
      gradeTree().then(response => {
        this.gradeTree = response.data
      })
    },
    // 图片上传功能
    uploadImage(file) {
      this.uploadFileData = file.file;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getInfo(row.id).then(response => {
        this.form = response.data;
        this.edtion = true;
        this.title = "信息修改";
      });
    },

    /** 提交按钮 */
    submitForm() {
      const formData = new FormData();

      formData.append("xxfbName", this.form.xxfbName);


      this.$refs["form"].validate(valid => {
        if (valid) {
          // 打开遮罩层
          this.$modal.loading("正在提交数据，请稍后...");
          if (this.form.id != null) {
            formData.append("id", this.form.id);
            updateInfo(formData).then(response => {
              // 关闭遮罩层
              this.$modal.closeLoading();
              this.$modal.msgSuccess("修改成功");
              this.edtion = false;
              // this.$refs.upload.clearFiles()
              this.getList();
            }).catch(() => {
              // 关闭遮罩层
              this.$modal.closeLoading();
            }
            );
          } else {
            if (this.uploadFileData) {
              formData.append("file", this.uploadFileData);
            }
            formData.append("gradeId", this.form.gradeId);
            addInfo(formData).then(() => {
              this.$modal.closeLoading();
              this.open = false;
              this.$modal.msgSuccess("新增成功");
              // this.$refs.upload.clearFiles()
              this.getList();
            }).catch(() => {
              // 关闭遮罩层
              this.$modal.closeLoading();
            }
            );
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除此信息？').then(() => {
        return delInfo(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport(row) {
      this.download('/school/xxfb/export/' + row.id, {
        ...this.queryParams
      }, `xxfb_${Date.now()}.xlsx`)
    },
    /** 数据按钮 */
    handleViewDetail(row) {
      // 这里进行一次路由跳转
      this.$router.push({
        path: '/gradeWork/infoPublish/dataList',
        query: {
          id: row.id,
          xxfbName: row.xxfbName
        }
      })
    },
    /** 数据查看按钮 */
    handleViewData(row) {
      // 这里进行一次路由跳转
      this.$router.push({
        path: '/gradeWork/infoPublish/dataView',
        query: {
          id: row.id,
          xxfbName: row.xxfbName
        }
      })
    },
    // 发布
    handlePublish(row) {
      this.$modal.confirm('是否确认发布此信息？').then(() => {
        return publish(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch((exception) => {
        throw new Error(exception)
      });
    },
    // 撤回
    handleRecall(row) {
      this.$modal.confirm('是否确认撤回此信息？').then(() => {
        return withdraw(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).catch((exception) => {
        throw new Error(exception);
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleViewDetail":
          this.handleViewDetail(row);
          break;
        case "handleExport":
          this.handleExport(row);
          break;
        case "handlePublish":
          this.handlePublish(row);
          break;
        default:
          break;
      }
    },

    changeShow() {
      this.isShow = !this.isShow
    },
    dialogClose() {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
