<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="标题" prop="instructionsTitle">
        <el-input
          v-model="queryParams.instructionsTitle"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <treeselect
          style="width: 200px"
          v-model="queryParams.materialsTypeId"
          :options="materialstypeOptions"
          :normalizer="materialnormalizer"
          placeholder="请选择物资类型"
        />
      </el-form-item>
      <el-form-item label="类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="类型">
          <el-option
            v-for="dict in dict.type.file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button
          v-no-more-click
          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
          v-no-more-click
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iscs:instructions:add']"
          >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          v-no-more-click
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['iscs:instructions:remove']"
          >批量删除
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="materialsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="说明编号"
        align="center"
        prop="instructionsId"
        width="200"
      >
      </el-table-column>
      <el-table-column
        prop="orderNum"
        label="排序"
        width="100"
      ></el-table-column>
      <el-table-column
        label="标题"
        align="center"
        prop="instructionsTitle"
      />
      <el-table-column
        label="物资类型"
        align="center"
        prop="materialsTypeName"
      />
      <el-table-column label="类型" align="center" prop="fileType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.file_type"
            :value="scope.row.fileType"
          />
        </template>
      </el-table-column>
      <el-table-column label="文件" align="center" prop="fileUrl">
        <template slot-scope="scope">
          <a :href="scope.row.fileUrl" target="_blank" style="color: #1890ff"
            >查看</a
          >
        </template>
      </el-table-column>
      <el-table-column label="添加时间" prop="createTime" align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iscs:instructions:edit']"
            >修改
          </el-button>
          <el-button
            v-no-more-click
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iscs:instructions:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加或修改物资对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body >

      <div slot="title" class="dialog-title">
        <i></i>
        <span class="title">{{ title }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number
            style="width: 350px"
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="标题" prop="instructionsTitle">
          <el-input
            style="width: 350px"
            v-model="form.instructionsTitle"
            placeholder="请输入标题"
          />
        </el-form-item>
        <el-form-item label="物资类型" prop="materialsTypeId">
          <treeselect
            style="width: 350px"
            v-model="form.materialsTypeId"
            :options="materialstypeOptions"
            :normalizer="materialnormalizer"
            placeholder="选择物资类型"
          />
        </el-form-item>
        <el-form-item label="类型" prop="fileType">
          <el-select
            v-model="form.fileType"
            placeholder="文件类型"
            style="width: 350px"
          >
            <el-option
              v-for="dict in dict.type.file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文件" prop="fileUrl">
          <div v-if="form.fileUrl">
            <div v-if="isVideo(form.fileUrl)">
              <video
                :src="form.fileUrl"
                width="300"
                height="200"
                controls
              ></video>
            </div>
            <div v-if="isPdf(form.fileUrl)">
              <embed
                :src="form.fileUrl"
                width="300"
                height="200"
                type="application/pdf"
              />
            </div>
            <el-button
              v-no-more-click
              type="danger"
              size="mini"
              @click="deleteFile"
              >删除</el-button
            >
          </div>
          <div v-else>
            <el-button
              v-no-more-click
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleFileUpload"
              v-hasPermi="['iscs:sop:import']"
              >导入</el-button
            >
          </div>
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm" :loading="loadingDialog"
        >{{ loadingDialog?'正在上传':'确认' }}
        </el-button>
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".mp4, .pdf"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :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">
          <span>mp4、pdf格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button v-no-more-click @click="upload.open = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInstructions,
  getInstructionsInfo,
  addInstructions,
  updateInstructions,
  delInstructions,
} from "@/api/mes/instructions/index.js";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import Template from "@/views/print/printtemplate/list.vue";
import { listType } from "@/api/mes/material/typeindex";
import { getToken } from "@/utils/auth";

export default {
  name: "Team",
  components: {
    Template,
    Treeselect,
  },
  dicts: ["material_status", "file_type"],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      loadingDialog:false,//弹框新增的等待效果
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      materialsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      createTime: "",
      queryParams: {
        current: 1,
        size: 10,
        instructionsTitle: "",
      },
      // 表单参数
      form: {
        fileUrl: "",
      },
      // 表单校验
      rules: {
        materialsName: [
          { required: true, message: "物资名称不能为空", trigger: "blur" },
        ],
        materialsTypeId: [
          { required: true, message: "物资类型不能为空", trigger: "blur" },
        ],
      },
      materialstypeOptions: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
      },
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },

  methods: {
    isVideo(url) {
      return url && (url.endsWith(".mp4") || url.includes("mp4"));
    },
    isPdf(url) {
      return url && (url.endsWith(".pdf") || url.includes("pdf"));
    },
    handleFileUpload() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    deleteFile() {
      this.form.fileUrl = ""; // 删除文件
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询物资信息列表 */
    getList() {
      this.loading = true;
      listInstructions(this.queryParams).then((response) => {
        console.log(response, "获取物资说明 ");
        this.materialsList = response.data.records;
        this.total = response.data.total;
        this.machinerytypeList = this.handleTree(
          response.data.records,
          "materialsTypeId",
          "parentId",
          "children"
        );
        this.loading = false;
      });
    },
    /** 查询物资类型下拉树结构 */
    getTreeselect() {
      const data = {
        current: 1,
        size: -1,
      };
      listType(data).then((response) => {
        console.log(response, "物资类型树形结构");
        this.materialstypeOptions = this.handleTree(
          response.data.records,
          "materialsTypeId",
          "parentId",
          "children"
        );
      });
    },
    /** 查询物资类型下拉树结构 */
    materialnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.materialsTypeId,
        label: node.materialsTypeName,
        children: node.children,
      };
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response,file, fileList,'文件上传成功回返')
      this.form.fileUrl = response.url;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        instructionsTitle: "",
        fileType: "",
        fileUrl: "",
        orderNum: 0,
      };
      this.resetForm("form");
      this.autoGenFlag = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.instructionsId);
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增物资说明";
      this.optType = "add";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getInstructionsInfo(row.instructionsId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物资说明";
        this.optType = "edit";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.loadingDialog = true;

          if (this.form.instructionsId != null) {
            updateInstructions(this.form).then((response) => {
              console.log(response, "修改返回");
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.loadingDialog = false;  // 结束加载
            });
          } else {
            console.log(this.form, "新增参数");
            addInstructions(this.form).then((response) => {
              console.log(response, "新增返回");
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.loadingDialog = false;  // 结束加载
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const instructionsId = row.instructionsId || this.ids;
      this.$modal
        .confirm('是否确认删除所选数据项？')
        .then(function () {
          return delInstructions(instructionsId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped>
.el-input-width {
  width: 380px !important;
}
.el-loading-parent--relative {
  position: relative;
}
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.7);
}
</style>
