<template>
  <div class="app-container">
    <TextSearch/>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主题" prop="topic">
        <el-input
          v-model="queryParams.topic"
          placeholder="请输入主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="培训人" prop="trainer">
        <el-input
          v-model="queryParams.trainer"
          placeholder="请输入培训人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参加培训人员" prop="participants">
        <el-input
          v-model="queryParams.participants"
          placeholder="请输入参加培训人员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期" prop="trainDate">
        <el-date-picker clearable
                        v-model="queryParams.trainDate"
                        type="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="['training:roster: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="['training:roster: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="['training:roster:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rosterList" @selection-change="handleSelectionChange" :height="clientHeight"
              border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主题" align="center" prop="topic"/>
      <el-table-column label="培训材料" align="center" prop="material"/>
      <el-table-column label="培训人" align="center" prop="trainer"/>
      <el-table-column label="参加培训人员" align="center" prop="participants"/>
      <el-table-column label="日期" align="center" width="180">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.trainStartDate, '{y}-{m}-{d}')
            }} ~ {{ parseTime(scope.row.trainEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" align="center" prop="trainDuration" width="180"/>
      <el-table-column label="培训内容" align="center" prop="content"/>
      <el-table-column label="备注" align="center" prop="remarks"/>
      <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-download"
            @click="getReport(scope.row)"
            v-hasPermi="['training:roster:edit']"
          >导出
          </el-button>
          <el-button
            icon="el-icon-folder"
            size="mini"
            type="text"
            @click="openFileDialog(scope.row)"
          >附件
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['training:roster:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['training:roster:remove']"
          >删除
          </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 :close-on-click-modal="false" :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="主题" prop="topic">
          <el-input v-model="form.topic" placeholder="请输入主题"/>
        </el-form-item>
        <el-form-item label="培训材料" prop="material">
          <el-input v-model="form.material" placeholder="请输入培训材料（若有）"/>
        </el-form-item>
        <el-form-item label="培训人" prop="trainer">
          <el-input v-model="form.trainer" placeholder="请输入培训人"/>
        </el-form-item>
        <el-form-item label="参加培训人员" prop="participants">
          <el-input v-model="form.participants" placeholder="请输入参加培训人员"/>
        </el-form-item>
        <el-form-item label="培训日期" prop="trainDateTmpl">
          <el-date-picker
            v-model="form.trainDateTmpl"
            type="daterange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="培训时间" prop="trainDuration">
          <el-input v-model="form.trainDuration" placeholder="请输入培训时间"/>
        </el-form-item>
        <el-form-item label="导出方式" prop="exportType">
          <el-radio-group v-model="form.exportType">
            <el-radio :label="1">预输入</el-radio>
            <el-radio :label="2">手动填写</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班组名单" prop="teams" v-if="form.exportType==1">
          <el-select v-model="form.teams" placeholder="请选择参与培训的班组" multiple clearable size="small"
                     style="width: 100%;">
            <el-option
              v-for="dict in teamOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参与培训的人员名单" prop="nameList" v-if="form.exportType==1">
          <el-input v-model="form.nameList" type="textarea"
                    placeholder="请输入参与培训的人员名单（每个人名之间请务必使用中文输入法下的逗号隔开。例如：张三，李四，王五）"/>
        </el-form-item>
        <el-form-item label="培训内容">
          <el-input type="textarea" v-model="form.content" placeholder="请输入培训内容概述" :min-height="192"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注"/>
        </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>
    <el-dialog :close-on-click-modal="false" :visible.sync="file.open" append-to-body title="附件管理" width="60%">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            icon="el-icon-plus"
            plain
            size="mini"
            type="primary"
            @click="handleFileAdd"
          >新增
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="file.fileList" :height="clientHeight-100"
                border>
        <el-table-column align="center" label="附件名称" prop="fileName">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="previewFile(scope.row.fileUrl)"
            >{{ scope.row.fileName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上传时间" prop="uploadDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.uploadDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上传人" prop="uploader">
        </el-table-column>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="text"
              @click="handleFileRemove(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="file.total>0"
        :limit.sync="file.queryParams.pageSize"
        :page.sync="file.queryParams.pageNum"
        :total="file.total"
        @pagination="getFileList"
      />
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="doc.open" append-to-body title="附件上传" width="400px">
      <el-upload
        ref="doc"
        :action="doc.url"
        :auto-upload="false"
        :file-list="doc.fileList"
        :headers="doc.headers"
        :on-progress="handleFileDocProgress"
        :on-success="handleFileDocSuccess"
        drag
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {addRoster, delRoster, getRoster, listRoster, updateRoster, wordView} from "@/api/training/roster";
import {getToken} from "../../../utils/auth";
import {delFile, listFile} from "../../../api/file/file";

export default {
  name: "Roster",
  data() {
    return {
      file: {
        open: false,
        fileList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          linkId: null,
          linkName: 'roster',
        },
        total: 0,
      },
      doc: {
        id: null,
        file: "",
        fileList: [],
        // 是否显示弹出层
        open: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/file/uploadFile",
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      //字典
      teamOptions: [],
      // 页面高度
      clientHeight: 300,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 培训签字表格数据
      rosterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        topic: null,
        material: null,
        trainer: null,
        participants: null,
        trainDate: null,
        teams: null,
        content: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        topic: [
          {required: true, message: "主题不能为空", trigger: "blur"}
        ],
        trainer: [
          {required: true, message: "培训人不能为空", trigger: "blur"}
        ],
        exportType: [
          {required: true, message: "请选择导出方式", trigger: "blur"}
        ],
        participants: [
          {required: true, message: "参加培训人员不能为空", trigger: "blur"}
        ],
        trainDateTmpl: [
          {required: true, message: "培训日期不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = (document.body.clientHeight - 80) * 0.8
    });
    this.getDicts("team_divide").then(res => {
      this.teamOptions = res.data;
    });
  },
  methods: {
    previewFile(url) {
      window.open(process.env.VUE_APP_BASE_API + url);
    },
    submitUpload() {
      this.$refs.doc.submit();
      this.doc.open = false;
      this.doc.fileList = [];
      this.getFileList();
    },
    //附件上传中处理
    handleFileDocProgress(event, file, fileList) {
      this.doc.file = file;
    },
    //附件上传成功处理
    handleFileDocSuccess(response, file, fileList) {
      this.$modal.msgSuccess("上传成功");
      this.doc.open = false;
      this.doc.fileList = [];
      this.getFileList();
    },
    cancelUpload() {
      this.doc.open = false;
      this.doc.fileList = [];
    },
    openFileDialog(row) {
      this.$router.push({path: '/system/file', query: {linkId: row.id, linkName: 'roster'}})
    },
    getFileList() {
      listFile(this.file.queryParams).then(response => {
        this.file.fileList = response.rows;
        this.file.total = response.total;
      })
    },
    handleFileAdd() {
      this.doc.open = true;
      this.doc.url = process.env.VUE_APP_BASE_API + "/file/file/uploadFile?linkId=" + this.file.queryParams.linkId + "&linkName=" + this.file.queryParams.linkName;
    },
    handleFileRemove(row) {
      delFile(row.id).then(res => {
        this.$modal.msgSuccess("删除成功");
        this.getFileList();
      });
    },
    /** 查询培训签字列表 */
    getList() {
      this.loading = true;
      listRoster(this.queryParams).then(response => {
        this.rosterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        topic: null,
        material: null,
        trainer: null,
        participants: null,
        trainDate: null,
        trainDateTmpl: null,
        teams: null,
        content: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: 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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加培训签字";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRoster(id).then(response => {
        if (response.data.teams) {
          response.data.teams = response.data.teams.split(',');
        }
        response.data.trainDateTmpl = [];
        response.data.trainDateTmpl[0] = new Date(response.data.trainStartDate);
        response.data.trainDateTmpl[1] = new Date(response.data.trainEndDate);
        this.form = response.data;
        this.open = true;
        this.title = "修改培训签字";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.trainStartDate = this.form.trainDateTmpl[0];
          this.form.trainEndDate = this.form.trainDateTmpl[1];
          if (this.form.teams)
            this.form.teams = this.form.teams.join(',')
          if (this.form.id != null) {
            updateRoster(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoster(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除培训签字编号为"' + ids + '"的数据项？').then(function () {
        return delRoster(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('training/roster/export', {
        ...this.queryParams
      }, `roster_${new Date().getTime()}.xlsx`)
    },
    /** 生成报告按钮操作 */
    getReport(row) {
      // this.meetingId = row.id
      // console.log(row.id)
      // this.$nextTick(() => {
      //   this.$refs['downloadFileForm'].submit()
      // })
      wordView(row.id).then(res => {
        window.open(process.env.VUE_APP_BASE_API + res.msg)
      })
    },
  }
};
</script>
