<!--
 * @Author: ysh
 * @Date: 2025-03-05 09:15:54
 * @LastEditors: wrh
 * @LastEditTime: 2025-10-16 12:34:56
-->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-row>
          <div class="title">
            集中学习
            <div class="line"></div>
          </div>
          <resource-tree @getTreeData="getTreeDataFn" :fields="fields1" @clickNode="queryField">
          </resource-tree>
        </el-row>
        <el-divider />
        <el-row>
          <div class="title">
            专业领域
            <div class="line"></div>
          </div>
          <resource-tree @getTreeData="getTreeDataFn" :fields="fields" @clickNode="queryField">
          </resource-tree>
        </el-row>
      </el-col>
      <el-col :span="18">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="资料名称" prop="title">
            <el-input v-model="queryParams.title" placeholder="请输入资料名称" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="上传人" prop="uploader">
            <el-select v-model="queryParams.uploader" filterable clearable @change="handleQuery">
              <el-option v-for="item in $store.state.user.userList" :key="item.userId" :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传部门" prop="uploadDept">
            <el-select v-model="queryParams.uploadDept" filterable clearable @change="handleQuery">
              <el-option v-for="item in $store.state.user.deptList" :key="item.deptId" :label="item.deptName"
                :value="item.deptId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传时间" prop="uploadTime">
            <el-date-picker clearable v-model="queryParams.uploadTime" 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="['oa:resource: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="['oa:resource: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="['oa:resource:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['oa:resource:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getResourceList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="resourceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="资料id" align="center" prop="resourceId" />
          <el-table-column label="上传人" align="center" prop="uploader">
            <template slot-scope="scope">
              {{ getUserName(scope.row.uploader) }}
            </template>
          </el-table-column>
          <el-table-column label="上传部门" align="center" prop="uploadDept">
            <template slot-scope="scope">
              {{ getDeptName(scope.row.uploadDept) }}
            </template>
          </el-table-column>
          <el-table-column label="资料名称" align="center" prop="title" />
          <el-table-column label="上传附件" align="center" prop="sourcePath" :formatter="formatterPath" />
          <el-table-column label="专业领域" align="center" prop="field" />
          <el-table-column label="类型" align="center" prop="type" />
          <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学时" align="center" prop="hours" />
          <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-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['oa:resource:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['oa:resource: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" />

        <!-- 添加或修改cmc学习资料对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="资料名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入资料名称" />
            </el-form-item>
            <el-form-item label="上传附件" prop="sourcePath">
              <FileUpload v-if="form.sourcePath == null || form.sourcePath == ''" :isShowTip="false" :limit="1"
                :filePathName="'教育学习/学习资料'" :fileType="['pdf', 'mp4']" :fileSize="10240" @input="getDocumentPath">
              </FileUpload>
              <div v-if="form.sourcePath">
                <el-link type="primary" @click="reviewWord(`${baseUrl}${'/profile/upload' + form.sourcePath}`)">
                  {{ getFileName(form.sourcePath) }}
                </el-link>
                <el-link class="ml20" type="warning" :href="`${baseUrl}${'/profile/upload' + form.sourcePath}`"
                  :underline="false" target="_blank">
                  <span class="el-icon-download">下载文件</span>
                </el-link>
                <el-link class="ml20" type="danger" @click="handleDeleteDocument" :underline="false"
                  v-hasPermi="['oa:resource:edit']">
                  <span class="el-icon-delete">删除文件</span>
                </el-link>
                <!-- <FileUpload v-if="taskName == '参培申请'" :limit="1" :filePathName="'参培/佐证附件'"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'rar', 'zip']" @input="getDocumentPath"></FileUpload> -->
              </div>
              <div style="font-size:12px;color:#e45656">
                tips:文档仅支持pdf格式，视频仅支持mp4格式
              </div>
            </el-form-item>
            <el-form-item label="资料类型" prop="type">
              <el-select v-model="form.type" clearable>
                <el-option label="视频" value="视频"></el-option>
                <el-option label="文档" value="文档"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="专业领域" prop="fieldId">
              <!-- <el-input v-model="form.fieldId" placeholder="请输入专业领域" /> -->
              <!-- <el-cascader :options="fieldOptions" v-model="form.fieldId" :show-all-levels="false"
                :props="{ children: 'children', label: 'field', value: 'fieldId' }">
                <template slot-scope="{ node, data }">
                  <span>{{ data.field }}</span>
                </template>
              </el-cascader> -->
              <el-tag>{{ form.field }}</el-tag>
              <el-tree ref="fieldIdTree" class="tree-border" :data="fieldOptions" show-checkbox
                :default-expanded-keys="this.form.fieldId ? [this.form.fieldId] : []" node-key="fieldId"
                empty-text="加载中，请稍候" :check-strictly="true" @check="handleChechChange"
                :props="{ children: 'children', label: 'field', value: 'fieldId' }">
              </el-tree>
            </el-form-item>
            <el-form-item label="学时" prop="hours">
              <el-input-number v-model="form.hours" :min="0" :precision="1"/>
            </el-form-item>
            <el-form-item label="上传人" prop="uploader">
              {{ getUserName(form.uploader) }}
            </el-form-item>
            <el-form-item label="上传部门" prop="uploadDept">
              {{ getDeptName(form.uploadDept) }}
            </el-form-item>
            <el-form-item label="上传时间" prop="uploadTime">
              {{ form.uploadTime }}
            </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-col>
    </el-row>
  </div>
</template>

<script>
import { listField } from "@/api/oa/study/resourceField";
import { listResource, getResource, delResource, addResource, updateResource, getListBelow } from "@/api/oa/study/resource";
import { parseTime } from "@/utils/ruoyi";
import resourceTree from './components/resourceTree.vue';
export default {
  components: { resourceTree },
  name: "Resource",
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // cmc学习资料表格数据
      resourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uploader: null,
        uploadDept: null,
        title: null,
        sourcePath: null,
        fieldId: null,
        type: null,
        uploadTime: null,
        hours: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      fields: [],
      fields1: [],
      fieldOptions: [],
      currentCheckedKey: null,
    };
  },
  watch: {
    'form.sourcePath'(val) {
      if (val) {
        let name = this.getFileName(val);
        if (name.includes('pdf')) {
          this.form.type = '文档'
        } else {
          this.form.type = '视频'
        }
      } else {
        this.form.type = ''
      }
    },
  },
  created() {
    this.getResourceList();
    this.getFieldList();
  },
  methods: {
    getList() {
      if (this.queryParams.fieldId != undefined && this.queryParams.fieldId != null)
        this.getAllListByFiedldId();
      else
        this.getResourceList();
    },
    /** 查询cmc学习资料列表 */
    getResourceList() {
      this.loading = true;
      listResource(this.queryParams).then(response => {
        this.resourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getFieldList() {
      listField({pageSize: 999}).then(response => {
        this.fields = [];
        this.fields1 = [];
        response.rows.forEach(element => {
          if (element.fieldId < 100)
            this.fields.push(element);
          else
            this.fields1.push(element);
        });
      });
    },
    getAllListByFiedldId() {
      this.loading = true;
      getListBelow(this.queryParams).then(response => {
        this.resourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        resourceId: null,
        uploader: null,
        uploadDept: null,
        title: null,
        sourcePath: null,
        fieldId: null,
        type: null,
        uploadTime: null,
        hours: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getResourceList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.resourceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.uploader = this.$store.getters.userId;
      this.form.uploadDept = this.$store.getters.deptId;
      this.form.uploadTime = parseTime(new Date(), '{y}-{m}-{d}');
      this.title = "新增学习资料";
      this.$nextTick(() => {
        this.$refs.fieldIdTree.setCheckedKeys([]);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const resourceId = row.resourceId || this.ids
      getResource(resourceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学习资料";
        this.$nextTick(() => {
          this.$refs.fieldIdTree.setCheckedKeys([this.form.fieldId]);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.resourceId != null) {
            updateResource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getResourceList();
            });
          } else {
            addResource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getResourceList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const resourceIds = row.resourceId || this.ids;
      this.$modal.confirm('是否确认删除cmc学习资料编号为"' + resourceIds + '"的数据项？').then(function () {
        return delResource(resourceIds);
      }).then(() => {
        this.getResourceList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('oa/resource/export', {
        ...this.queryParams
      }, `resource_${new Date().getTime()}.xlsx`)
    },
    getDocumentPath(val) {
      let arr = val.split('/upload')
      this.form.sourcePath = arr[1]
      if (val == "") {
        this.form.sourcePath = ""
      }
    },
    handleDeleteDocument() {
      this.$modal.confirm('是否确认删除该附件？').then(() => {
        this.form.sourcePath = '';
      }).catch(() => { });
    },
    formatterPath(row) {
      let name = this.getFileName(row.sourcePath)
      return name
    },
    queryField(data) {
      if (data) {
        this.queryParams.fieldId = data.fieldId
        this.getAllListByFiedldId();
      }
    },
    getTreeDataFn(data) {
      this.fieldOptions = this.removeEmptyChildren(data);
    },
    removeEmptyChildren(arr) {
      return arr.map(item => {
        // 创建新对象（不修改原对象）
        const newItem = { ...item };
        // 递归处理子节点
        if (newItem.children && Array.isArray(newItem.children)) {
          if (newItem.children.length === 0) {
            delete newItem.children; // 删除空数组属性
          } else {
            newItem.children = this.removeEmptyChildren(newItem.children); // 递归处理子节点
          }
        }

        return newItem;
      });
    },
    handleChechChange(currentNode, checkedStatus) {
      const checkedKeys = checkedStatus.checkedKeys;
      let currentId = currentNode.fieldId;
      // 如果选中超过1个节点
      if (checkedKeys.length > 1) {
        // 保留最后一个选中的节点
        const lastKey = checkedKeys.filter(item => item == currentId);
        this.$refs.fieldIdTree.setCheckedKeys([lastKey]);
        this.form.fieldId = currentId
        this.form.field = currentNode.field;
        return;
      }
      // 如果取消选中当前节点
      if (checkedKeys.length === 0) {
        this.currentCheckedKey = null;
        this.form.fieldId = null;
        this.form.field = null;
      } else {
        this.currentCheckedKey = checkedKeys[0];
        this.form.fieldId = currentId;
        this.form.field = currentNode.field;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  position: relative;
  font-weight: bold;
  font-size: 18px;
  padding-left: 40px;
  padding-bottom: 20px;

  .line {
    position: absolute;
    left: 22px;
    top: 3px;
    width: 5px;
    height: 20px;
    border-radius: 10px;
    background-color: #2893e5;
  }
}
</style>