<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="警示资料管理" name="datamanage">
      <div class="datamanage-wrapper">
        <div class="tool-wrapper">
          <el-button type="primary" @click="addDialogData">新增</el-button>
          <el-button
            type="warning"
            :disabled="isEditable"
            @click="editDialogData"
            >编辑</el-button
          >
          <el-button
            type="danger"
            :disabled="isDeleteable"
            @click="deleteDialogData"
            >删除</el-button
          >
        </div>
        <div class="search-wrapper">
          <!--时间、题目、类别、上传人-->
          <el-date-picker
            v-model="searchTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <el-input
            v-model="searchTitle"
            style="width: 180px;margin-left: 20px;"
            placeholder="请输入题目"
          />
          <el-select
            v-model="searchType"
            placeholder="请选择类别"
            style="margin-left: 20px;"
          >
            <el-option
              v-for="item in category"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-input
            v-model="searchPerson"
            style="width: 180px;margin-left: 20px;"
            placeholder="请输入上传人"
          />
          <el-button
            type="success"
            style="margin-left: 20px;"
            @click="initWarning"
            >查询</el-button
          >
        </div>
        <div class="table-wrapper">
          <el-table
            v-loading="isLoadingWarning"
            :data="warnList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="type" label="类别" width="180" />
            <el-table-column prop="title" label="标题" width="180" />
            <el-table-column prop="introduce" label="简介" width="180" />
            <el-table-column prop="uploader" label="上传人" width="180" />
            <el-table-column prop="uploadtime" label="上传时间" width="180" />
          </el-table>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="curPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalColumn"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <el-dialog title="新增警示教育" :visible.sync="addDialogFormVisible">
          <el-form
            v-if="addDialogFormVisible"
            ref="addDataForm"
            :model="addFormInfo"
            :rules="rules"
          >
            <el-form-item prop="type" label="类别" :label-width="'120px'">
              <el-select
                v-model="addFormInfo.type"
                placeholder="请选择类别"
                filterable
                allow-create
              >
                <el-option
                  v-for="item in category"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="title" label="题目" :label-width="'120px'">
              <el-input v-model="addFormInfo.title" :maxlength="50" />
            </el-form-item>
            <el-form-item prop="introduce" label="简介" :label-width="'120px'">
              <el-input v-model="addFormInfo.introduce" :maxlength="200" />
            </el-form-item>
            <el-form-item
              prop="fileName"
              label="文件名称"
              :label-width="'120px'"
            >
              <div class="upload-file-wrapper">
                <div class="file-wrapper">
                  <label
                    style="width: 100%; height: 100%;display: flex;align-items: center;justify-content: center;"
                  >
                    选择要上传的文件
                    <input
                      ref="addDataFileRef"
                      type="file"
                      hidden
                      @change="chosenAddFile"
                    />
                  </label>
                  <div>{{ addFormInfo.fileName }}</div>
                </div>
                <el-progress :percentage="addFormUploadPercentage" />
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="cancelAddForm">取消</el-button>
            <el-button type="primary" @click="uploadAddForm">上传</el-button>
          </div>
        </el-dialog>
        <el-dialog title="编辑警示教育" :visible.sync="editDialogFormVisible">
          <el-form
            v-if="editDialogFormVisible"
            ref="editDataForm"
            :model="editFormInfo"
            :rules="rules"
          >
            <el-form-item prop="type" label="类别" :label-width="'120px'">
              <el-select
                v-model="editFormInfo.type"
                placeholder="请选择类别"
                filterable
                allow-create
              >
                <el-option
                  v-for="item in category"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="title" label="题目" :label-width="'120px'">
              <el-input v-model="editFormInfo.title" :maxlength="50" />
            </el-form-item>
            <el-form-item prop="introduce" label="简介" :label-width="'120px'">
              <el-input v-model="editFormInfo.introduce" :maxlength="200" />
            </el-form-item>
            <el-form-item
              prop="fileName"
              label="上传文件"
              :label-width="'120px'"
            >
              <div class="upload-file-wrapper">
                <div class="file-wrapper">
                  <label
                    style="width: 100%; height: 100%;display: flex;align-items:center;justify-content: center;"
                  >
                    选择要上传的文件
                    <input
                      ref="editDataFileRef"
                      type="file"
                      hidden
                      @change="chosenEditFile"
                    />
                  </label>
                  <div>{{ editFormInfo.fileName }}</div>
                </div>
                <el-progress :percentage="editFormUploadPercentage" />
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer">
            <el-button @click="cancelEditForm">取消</el-button>
            <el-button type="primary" @click="uploadEditForm">上传</el-button>
          </div>
        </el-dialog>
      </div>
    </el-tab-pane>
    <el-tab-pane label="观看记录管理" name="recordmanage">
      <div class="tools-wrapper">
        <el-date-picker
          v-model="recordSearchTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-input
          v-model="recordSearchUser"
          placeholder="请输入用户名"
          style="width: 240px;margin-left: 20px;"
        />
        <el-input
          v-model="recordSearchEnter"
          placeholder="请输入企业名"
          style="width: 240px;margin-left: 20px;"
        />
        <el-button type="success" style="margin-left: 20px;">查询</el-button>
        <el-button type="primary" @click="exportFile">导出</el-button>
      </div>
      <el-table :data="recordList">
        <el-table-column prop="userName" label="用户名" width="100" />
        <el-table-column prop="company" label="所属企业" width="100" />
        <el-table-column prop="companyCommunity" label="所属区域" width="100" />
        <el-table-column prop="companyIndus" label="企业所属行业" width="100" />
        <el-table-column prop="recordTitle" label="标题" width="150" />
        <el-table-column prop="recordType" label="类别" width="100" />
        <el-table-column prop="recordTime" label="观看时间" width="100" />
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 30, 40]"
        :page-size="curRecordPageSize"
        :current-page="curRecordPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="curRecordTotal"
        @size-change="handleRecordSizeChange"
        @current-change="handleRecordCurrentChange"
      />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import {
  deleteWarnTeach,
  getWranTeach,
  getWarnTeachCategory
} from "@/api/warnteach.js";
import axiosFile from "@/utils/requestfile";
import { parseTime } from "../../utils";
/**
 * axiosFile({
        url: '/api/thRisk/create',
        method: 'POST',
        data: mForm,
        onUploadProgress: progressEvent => {
          // progressEvent.loaded
          // progressEvent.total
          this.curUploadProgress = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
        }
      })
 */
export default {
  data() {
    return {
      category: [],
      warnList: [],
      multipleSelection: [],
      typeList: [],
      // 时间 、题目 、 类别、 上传人
      searchTime: "",
      searchTitle: "",
      searchType: "",
      searchPerson: "",
      formInfo: {
        type: "",
        title: "",
        introduce: "",
        uploader: "",
        uploadTime: ""
      },
      isLoadingWarning: false,
      currentPage: 1,
      curPageSize: 10,
      totalColumn: 40,
      activeName: "datamanage",
      isEditable: true,
      isDeleteable: true,
      recordSearchTime: "",
      recordSearchUser: "",
      recordSearchEnter: "",
      recordList: [
        {
          userName: "1",
          company: "2",
          companyCommunity: "1",
          companyIndus: "2",
          recordTitle: "1",
          recordType: "2",
          recordTime: "1"
        },
        {
          userName: "3",
          company: "4",
          companyCommunity: "3",
          companyIndus: "4",
          recordTitle: "3",
          recordType: "4",
          recordTime: "3"
        }
      ],
      curRecordPageSize: 10,
      curRecordPage: 1,
      curRecordTotal: 40,
      addDialogFormVisible: false,
      addFormInfo: {
        type: "", // 类型
        title: "", // 标题
        introduce: "", // 简介
        fileName: "", // 文件名
        file: null
      },
      rules: {
        type: [{ required: true, message: "请输入类别", trigger: "blur" }],
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        fileName: [{ required: true, message: "请选择文件", trigger: "change" }]
      },
      addFormUploadPercentage: 0,
      editFormUploadPercentage: 0,
      editDialogFormVisible: false,
      editFormInfo: {
        type: "",
        title: "",
        introduce: "",
        fileName: "",
        file: null,
        userId: 1
      }
    };
  },
  async mounted() {
    await getWarnTeachCategory().then(res => {
      this.category = [...res];
    });
    await this.initWarning();
  },
  methods: {
    async initWarning() {
      this.isLoadingWarning = true;
      const params = {
        page: this.currentPage - 1,
        size: this.curPageSize
      };
      // 类别
      if (this.searchType) {
        params.category = this.searchType;
      }
      // 题目
      if (this.searchTitle) {
        params.title = this.searchTitle;
      }
      // 时间
      if (this.searchTime instanceof Array) {
        params.uploadStartTime = parseTime(new Date(this.searchTime[0]));
        params.uploadEndTime = parseTime(new Date(this.searchTime[1]));
      }
      // 上传人
      if (this.searchPerson) {
        params.uploader = this.searchPerson;
      }
      await getWranTeach(params).then(
        res => {
          this.warnList = [
            ...res.content.map(item => {
              return {
                ...item,
                type: item.category,
                title: item.title,
                introduce: item.briefIntroduction,
                uploader: item.uploader,
                uploadtime: item.uploadTime
              };
            })
          ];
          this.totalColumn = res.totalElements;
          this.isLoadingWarning = false;
        },
        () => {
          this.isLoadingWarning = false;
        }
      );
    },
    async initCategory() {
      await getWarnTeachCategory().then(res => {
        this.category = [...res];
      });
    },
    handleSizeChange(val) {
      // 每页多少条
      this.curPageSize = val;
      this.initWarning();
    },
    handleCurrentChange(val) {
      // 当前是多少页
      this.currentPage = val;
      this.initWarning();
    },
    exportFile() {
      // 导出文件
    },
    handleRecordSizeChange(val) {
      this.curRecordPageSize = val;
    },
    handleRecordCurrentChange(val) {
      this.curRecordPage = val;
    },
    cancelAddForm() {
      this.addFormInfo.type = "";
      this.addFormInfo.title = "";
      this.addFormInfo.introduce = "";
      this.addFormInfo.fileName = "";
      this.addFormInfo.file = null;
      this.addFormInfo.userId = "";
      this.addDialogFormVisible = false;
    },
    uploadAddForm() {
      // formData
      // multipart/formdata
      //
      this.$refs.addDataForm.validate(valid => {
        if (valid) {
          if (
            !(
              this.addFormInfo.file.name.endsWith(".mp4") ||
              this.addFormInfo.file.name.endsWith(".m3u8") ||
              this.addFormInfo.file.name.endsWith(".pdf")
            )
          ) {
            this.$message.error("只支持mp4、m3u8、pdf类型的文件");
            return;
          }
          const mForm = new FormData();
          mForm.append("briefIntroduction", this.addFormInfo.introduce);
          mForm.append("category", this.addFormInfo.type);
          mForm.append("file", this.addFormInfo.file);
          mForm.append("title", this.addFormInfo.title);
          axiosFile({
            url: "/api/warningEducation",
            method: "POST",
            data: mForm,
            onUploadProgress: progressEvent => {
              // progressEvent. loaded
              // progressEvent. total
              // this.curUploadProgress = (())
              console.log(
                progressEvent,
                "progressEvent, progressEvent, progressEvent"
              );
              this.addFormUploadPercentage = parseInt(
                "" + progressEvent.loaded / progressEvent.total
              );
            }
          })
            .then(res => {
              this.addDialogFormVisible = false;
              this.initCategory();
              this.$message({
                type: "success",
                message: "添加成功"
              });
              this.initWarning();
            })
            .catch(() => {
              this.$message.error("添加失败");
            });
        }
      });
    },
    addDialogData() {
      this.addFormInfo.type = "";
      this.addFormInfo.title = "";
      this.addFormInfo.introduce = "";
      this.addFormInfo.fileName = "";
      this.addFormInfo.file = null;
      this.addFormUploadPercentage = 0;
      // 获取用户id
      this.addFormInfo.userId = 0;
      this.addDialogFormVisible = true;
    },
    // 编辑对话框
    editDialogData() {
      //
      // editDialog
      this.editDialogFormVisible = true;
      this.editFormInfo.type = this.multipleSelection[0].type;
      this.editFormInfo.title = this.multipleSelection[0].title;
      this.editFormInfo.introduce = this.multipleSelection[0].introduce;
      this.editFormInfo.fileName = this.multipleSelection[0].filePath;
      this.editFormInfo.id = this.multipleSelection[0].id;
    },
    // 删除对话框
    deleteDialogData() {
      console.log(
        this.multipleSelection,
        "this.multipleSelection this.multipleSelection this.multipleSelection"
      );
      this.$confirm("此操作将删除选中项, 是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteWarnTeach(this.multipleSelection.map(item => item.id)).then(
            res => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.initWarning();
              this.initCategory;
            },
            () => {
              this.$message.error("删除失败!");
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.isEditable = true;
      this.isDeleteable = true;
      if (this.multipleSelection.length === 1) {
        this.isEditable = false;
      }
      if (this.multipleSelection.length > 0) {
        this.isDeleteable = false;
      }
    },
    addType() {
      // 跳转到新增页面
      this.$router.push({
        path: "warn/warntype"
      });
    },
    cancelEditForm() {
      this.editDialogFormVisible = false;
    },
    uploadEditForm() {
      // formdata axios
      this.$refs.editDataForm.validate(valid => {
        if (valid) {
          if (
            !(
              this.editFormInfo.fileName.endsWith(".mp4") ||
              this.editFormInfo.fileName.endsWith(".m3u8") ||
              this.editFormInfo.fileName.endsWith(".pdf")
            )
          ) {
            this.$message.error("只支持mp4、m3u8、pdf类型的文件");
            return;
          }
          const mForm = new FormData();
          mForm.append("briefIntroduction", this.editFormInfo.introduce);
          mForm.append("category", this.editFormInfo.type);
          mForm.append("id", this.editFormInfo.id);
          mForm.append("title", this.editFormInfo.title);
          if (this.editFormInfo.fileName && this.editFormInfo.file) {
            mForm.append("file", this.editFormInfo.file);
          }
          axiosFile({
            url: "/api/warningEducation/update",
            method: "POST",
            data: mForm,
            onUploadProgress: progressEvent => {
              console.log(progressEvent);
              this.editFormUploadPercentage = parseInt(
                "" + progressEvent.loaded / progressEvent.total
              );
            }
          })
            .then(res => {
              console.log(res, "axiosFile axiosFile axiosFile");
              this.$message({
                type: "success",
                message: "修改成功"
              });
              this.editDialogFormVisible = false;
              this.initCategory();
              this.initWarning();
            })
            .catch(() => {
              this.$message.error("修改失败");
            });
        }
      });
    },
    chosenAddFile() {
      console.log(
        this.$refs.addDataFileRef.files,
        "this.$refs.addDataFileRef this.$refs.addDataFileRef"
      );
      // this.$refs.addDataFileRef.files
      this.addFormInfo.fileName = "";
      this.addFormInfo.file = null;
      if (this.$refs.addDataFileRef.files.length) {
        this.addFormInfo.fileName = this.$refs.addDataFileRef.files[0].name;
        this.addFormInfo.file = this.$refs.addDataFileRef.files[0];
      }
    },
    chosenEditFile() {
      // this.editFormInfo.fileName = ''
      // this.editFormInfo.file = null
      if (this.$refs.editDataFileRef.files.length > 0) {
        this.editFormInfo.fileName = this.$refs.editDataFileRef.files[0].name;
        this.editFormInfo.file = this.$refs.editDataFileRef.files[0];
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.search-wrapper {
  display: flex;
  margin: 20px 0;
}
.tools-wrapper {
  display: flex;
  margin: 20px 0;
}
.upload-file-wrapper {
  display: flex;
  .file-wrapper {
    width: 240px;
    height: 100px;
    background: aliceblue;
  }
}
.datamanage-wrapper {
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
  .tool-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .search-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .table-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
}
</style>
