<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="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option
            v-for="dict in dict.type.iit_file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['iit:file:add']">新增
        </el-button>
        <!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['iit:file:edit']">修改
                </el-button>-->

      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="ID" align="center" prop="id" width="60" :show-overflow-tooltip="true"/>
      <el-table-column label="名称" align="left" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="文件名称" align="left" prop="fileName" :show-overflow-tooltip="true" width="350"/>
      <el-table-column label="文件类型" align="center" prop="fileType" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iit_file_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="推送次数" align="center" prop="pushTimes" width="100"/>
      <el-table-column label="文件备注" align="left" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="上传用户" align="left" prop="userName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="上传时间" align="left" prop="createTime" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iit:info:edit']">修改
                    </el-button>-->
<!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['iit:file:remove']">删除
          </el-button>-->
          <el-button size="mini" type="text" icon="el-icon-s-promotion" @click="handlePush(scope.row)"
                     v-hasPermi="['iit:file:edit']">文件推送
          </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 :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="50px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="fileType">
              <el-select v-model="form.fileType" placeholder="请选择文件类型">
                <el-option
                  v-for="dict in dict.type.iit_file_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="文件" prop="fileUrl">
          <file-upload v-model="form.fileUrl"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="5" v-model="form.remark" 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 :title="title" :visible.sync="pushOpen" width="900px" append-to-body>
      <div style="display: flex; justify-content: center;">
        <el-transfer
          filterable
          :filter-method="filterUser"
          filter-placeholder="请输入用户姓名"
          v-model="selectedUser"
          :data="filteredUserList"
          :props="{key: 'userId', label: 'nickName'}"
          :titles="['可选用户', '已选用户']"
          :button-texts="['移除', '添加']"
          :left-default-checked="[]"
          :right-default-checked="[]"
        >
          <template #left-footer>
            <span style="font-size: 12px; color: #909399;margin-left: 10px">共 {{ userList.length }} 人</span>
          </template>
          <template #right-footer>
            <span style="font-size: 12px; color: #909399;margin-left: 10px">已选 {{ selectedUser.length }} 人</span>
          </template>
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormPush">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addInfo, delInfo, getInfo, listInfo, updateInfo} from "@/api/iit/file";
import {listUser} from "@/api/system/user";
import {addPush} from "@/api/iit/push";

export default {
  name: "Info",
  dicts: ['iit_file_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件管理表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      pushOpen: false,
      // 文件推送ID
      pushId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        fileName: null,
        fileType: null,
      },
      userList: [],
      selectedUser: [],
      // 过滤后的用户列表
      filteredUserList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        fileType: [
          {required: true, message: "文件类型不能为空", trigger: "change"}
        ],
        fileUrl: [
          {required: true, message: "文件不能为空", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  // 组件挂载时加载初始数据
  mounted() {
    this.loadUserList();
  },
  methods: {
    formatFileSize(fileSize) {
      if (fileSize < 1024) {
        return fileSize.toFixed(0) + ' KB';
      } else {
        return (fileSize / 1024).toFixed(2) + ' MB';
      }
    },
    /** 查询文件管理列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    loadUserList(query) {
      return listUser({
        pageNum: 1,
        pageSize: 100,  // 适当增大初始加载量
        nickName: query
      }).then(response => {
        this.userList = response.rows;
        this.filteredUserList = response.rows;
      });
    },
    // 本地过滤方法
    filterUser(query, item) {
      this.lastQuery = query;
      if (!query) {
        this.filteredUserList = this.userList;
        return true;
      }
      return item.nickName.includes(query);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.pushOpen = false;
      this.pushId = null;
      this.selectedUser = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        fileName: null,
        fileType: null,
        fileSize: null,
        filePath: null,
        fileUrl: null,
        remark: null,
        createTime: null,
        userId: null,
        userName: null,
        deptId: 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 = "添加文件管理";
    },
    /** 文件推送 */
    handlePush(row) {
      this.pushId = row.id;
      this.pushOpen = true;
      this.title = "文件推送";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件管理";
      });
    },
    submitFormPush() {
      if (this.selectedUser.length <= 0) {
        this.$modal.msgError("请选择推送用户");
        return;
      }
      addPush({
        fileId: this.pushId,
        userIds: this.selectedUser
      }).then(response => {
        this.$modal.msgSuccess("推送成功");
        this.pushOpen = false;
        this.getList();
      });
      /*this.$modal.confirm('是否确认推送ID为"' + this.pushId + '"的文件？').then(function () {
        return addPush({
          fileId: this.pushId,
          userIds: this.selectedUser
        });
      }).then(() => {
        this.$modal.msgSuccess("推送成功");
        this.pushOpen = false;
        this.pushId = null;
        this.selectedUser = [];
        this.getList();
      }).catch(() => {
        console.log("取消推送")
      });*/
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除文件管理编号为"' + ids + '"的数据项？').then(function () {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('iit/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 自定义左右面板宽度 */
::v-deep .el-transfer-panel {
  width: 300px; /* 单个面板宽度 */
  height: 500px;
}

::v-deep .el-transfer-panel__body {
  height: 100%;
}

::v-deep .el-transfer-panel__list {
  height: 100%;
}

/* 自定义按钮区域样式 */
::v-deep .el-transfer__buttons {
  width: 210px; /* 按钮区域宽度 */
  padding: 0 10px;
}
</style>
