<template>
  <div class="app-container">
    <form-search :searchformShow="searchformShow" :validate-rules="searchRules" :extra-params="extraParams"
                 :coursewareUpload="coursewareUpload" @handleQuery="handleQuery" @resetQuery="resetQuery"></form-search>
    <el-card class="box-card" style="margin-bottom: 30px">
      <el-row :gutter="24">
        <el-col :span="4" v-if="viewName != 'Custom'">
          <h3
            style="
              padding-left: 11px;
              border-left: 2px solid #e6a700;
              color: #e6a700;
            "
          >{{ queryParams.wayType == 1 ? '章节目录' : '知识点目录' }}</h3>
          <div class="head-container">
            <el-input
              v-model="name"
              :placeholder="
                queryParams.wayType == 1 ? '请输入章节名称' : '请输入知识点名称'
              "
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container" style="overflow: hidden;">
            <el-tree
              v-loading="treeLoading"
              v-show="queryParams.wayType == 1"
              :data="deptOptions"
              :props="treeProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="treeDefault"
              @node-click="handleNodeClick"
            >
              <div slot-scope="{node, data}">
                <div :title="data.name">{{ data.name }}</div>
              </div>
            </el-tree>
            <el-tree
              v-loading="treeLoading"
              v-show="queryParams.wayType == 2"
              :data="KnowledgeOptions"
              :props="treeProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="treeKnowledge"
              @node-click="handleNodeClick"
            >
              <div slot-scope="{node, data}">
                <div :title="data.name">{{ data.name }}</div>
              </div>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="viewName == 'Custom' ? 24 : 20">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToCloudResourse']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToCloudResourse" :disabled="multiple">
                上传至云库
              </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToSchoolResourse']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToSchoolResourse" :disabled="multiple">
                上传至校本资源库
              </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToBoard']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToSchoolClass" :disabled="multiple">上传至班牌
              </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToStudent']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToSchoolStudent" :disabled="multiple">
                上传至学生端
              </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToParent']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToSchoolParent" :disabled="multiple">
                上传至家长端
              </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['front:personResource:uploadToQuestion']">
              <el-button plain icon="el-icon-upload2" size="small" @click="upToQuestion()" :disabled="multiple">上传至试题
              </el-button>
            </el-col>
            <el-table v-loading="loading" :data="resourcesList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="文件" align="center" prop="resourcesName" v-if="viewName == 'Index'">
                <template slot-scope="scope">
                  <resource-preview-button :row="scope.row">
                    <img style="width: 130px; height: 80px; cursor: pointer" :src="img.ship" alt/>
                  </resource-preview-button>
                </template>
              </el-table-column>
              <el-table-column label="文件名" align="center" prop="resourcesName"/>
              <el-table-column label="发布人" align="center" prop="createBy"/>
              <el-table-column label="时间" align="center" prop="createTime"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <resource-preview-button v-if="viewName != 'Index'" :row="scope.row" class="mr10"/>
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                        @pagination="getList"/>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加或修改云库对话框 -->
    <el-dialog :title="title" v-loading="quesLoading" :visible.sync="quesDialog" width="800px" append-to-body>
      <el-form ref="formQuestion" :model="form" :rules="rules2" label-width="80px" v-if="quesDialog">
        <el-form-item label="题目编号" prop="questionId">
          <el-input v-model="form.questionId" placeholder="题目编号"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitQuestion">确 定</el-button>
        <el-button @click="cancelQuestion">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改云库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="open">
        <el-form-item label="资源名称" prop="resourcesName">
          <el-input v-model="form.resourcesName" 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>
    <upload-dialog
      v-if="dialogVisible"
      :title="title"
      :pageName="pageName"
      :isZdy="isZdy"
      :selectType="selectType"
      :dialogVisible="dialogVisible"
      @handleClose="handleClose"
      @dialogVisibleClose="dialogVisibleClose"
    ></upload-dialog>
  </div>
</template>

<script>
import { add, exportList } from '@/api/webApi/school'
import {
  getInfo,
  list,
  modifyPersonResourceInfo,
  remove,
  updataQuestion,
  upToCloudResourse,
  upToSchoolClass,
  upToSchoolParent,
  upToSchoolResourse,
  upToSchoolStudent
} from '@/api/webApi/person'
import { knowledgeTree, treeList } from '@/api/webApi/webQue.js'
import { mapGetters } from 'vuex'
import ResourcePreviewButton from '@/views/accurateTeaching/components/resource-preview-button'
import consts from '@/common/mx-const'

export default {
  components: { ResourcePreviewButton },
  data() {
    const blurText = async(rule, value, callback) => {
      const boolean = new RegExp('^[1-9][0-9]*$').test(value) // console.log(boolean)
      if (!boolean) {
        callback(new Error('请输入正整数'))
      }
    }
    return {
      quesDialog: false,
      quesLoading: false,
      questionId: '',
      coursewareUpload: false,
      treeLoading: false,
      searchformShow: {},
      searchRules: {},
      extraParams: {},
      dialogVisible: false,
      img: {
        ship: require('@/assets/images/ship.png')
      },
      treeProps: {
        children: 'children',
        label: 'name',
        code: 'id'
      },
      deptOptions: undefined,
      KnowledgeOptions: [],
      deptName: '',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      idsSel: [],
      resourcesNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 云库表格数据
      resourcesList: [],
      // 弹出层标题
      title: '',
      pageName: '',
      // 是否显示弹出层
      open: false,
      // 资源类型字典
      typeOptions: [],
      // 资源分类字典
      categoryOptions: [],
      // 是否删除字典
      delFlagOptions: [],
      // 查询参数
      queryParams: {
        wayType: '1',
        pageNum: 1,
        pageSize: 10,
        resourcesName: '',
        type: null,
        category: null,
        province: null,
        city: null,
        county: null,
        chapterId: null,
        resourcesUrl: '',
        bookId: null,
        subjectId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        resourcesName: [
          {
            required: true,
            message: '资源名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      rules2: {
        questionId: [
          {
            required: true,
            message: '题目编号不能为空',
            trigger: 'blur'
          },
          {
            validator: blurText,
            trigger: 'blur'
          }
        ]
      },

      viewName: '',
      name: '',
      isZdy: true,
      selectType: ''
    }
  },
  computed: {
    ...mapGetters(['currentUser']),
    userInfo() {
      // TODO: hht 22.1.5 兼容历史写法，待清理
      return this.currentUser
    }
  },
  created() {
    this.viewName = this.$route.name
    if (this.viewName == 'Index') {
      this.coursewareUpload = false
      this.searchformShow = {
        wayType: '1',
        subjectid: '',
        edition: '',
        slipid: ''
      }
      this.searchRules = {}
      this.extraParams = {}
    } else if (this.viewName == 'Personal') {
      this.coursewareUpload = true
      this.searchformShow = {
        subjectid: '',
        edition: '',
        slipid: '',
        coursewareType: ''
      }
      this.searchRules = this.createCoursewareRules()
      this.extraParams = this.createCoursewareParams()
    } else {
      this.coursewareUpload = true
      this.searchformShow = {
        subjectid: '',
        resourceType: ''
      }
      this.searchRules = {}
      this.extraParams = {}
    }
    this.getDicts('resource_type').then((response) => {
      this.typeOptions = response.data
    })
    this.getDicts('category').then((response) => {
      this.categoryOptions = response.data
    })
    this.getDicts('bool_flag').then((response) => {
      this.delFlagOptions = response.data
    })
  },
  watch: {
    // 根据名称筛选部门树
    name(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 查询个人资源库列表 */
    getList() {
      this.loading = true
      if (this.viewName == 'Index') {
        this.queryParams.category = '微课视频'
        this.pageName = '微课视频'
      } else if (this.viewName == 'Personal') {
        this.queryParams.category = '课件资源'
        this.pageName = '课件资源'
      } else {
        this.queryParams.category = '自定义'
        this.pageName = '自定义'
      }
      let Ajax = {
        subjectId: this.queryParams.subjectid, //科目
        bookId: this.queryParams.slipid, //学册
        chapterId: this.queryParams.chapterId, //章节
        coursewareType: this.queryParams.coursewareType,
        edition: this.queryParams.edition,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        category: this.queryParams.category,
        type: this.queryParams.resourceType,
        linkWay: this.queryParams.wayType
      }

      list(Ajax)
        .then((response) => {
          this.resourcesList = response.rows
          this.total = response.total
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    // 资源类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 资源分类字典翻译
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category)
    },
    // 是否删除字典翻译
    delFlagFormat(row, column) {
      return this.selectDictLabel(this.delFlagOptions, row.delFlag)
    },
    handleClose(type, name, selectData) {
      console.log('------------')
      console.log(type)
      console.log(name)
      console.log(selectData)
      let _this = this
      if (this.title == '上传至云库') {
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item
          }
          if (name) {
            Ajax.resourcesName = name
          }
          upToCloudResourse(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess('操作成功')
              _this.dialogVisible = false
            }
          })
        })
      } else if (this.title == '上传至校本资源库') {
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item
          }
          if (name) {
            Ajax.resourcesName = name
          }
          upToSchoolResourse(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess('操作成功')
              _this.dialogVisible = false
            }
          })
        })
      } else if (this.title == '上传至班牌') {
        console.log('上传至班牌')
        console.log(selectData)
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item,
            classId: selectData.checkedClass,
            studentCodes: selectData.checkedStudent
              ? selectData.checkedStudent.join(',')
              : ''
          }
          if (name) {
            Ajax.resourcesName = name
          }
          console.log('上传至班牌', Ajax)
          upToSchoolClass(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess('操作成功')
              _this.dialogVisible = false
            }
          })
        })
      } else if (this.title == '上传至学生端') {
        console.log('上传至学生端')
        console.log(selectData)
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item,
            classId: selectData.checkedClass,
            remark: selectData.remark,
            studentCodes: selectData.checkedStudent.join(',')
          }
          if (name) {
            Ajax.resourcesName = name
          }
          upToSchoolStudent(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess('操作成功')
              _this.dialogVisible = false
            }
          })
        })
      } else if (this.title == '上传至家长端') {
        console.log('上传至家长端')
        console.log(selectData)
        _this.ids.forEach((item, index) => {
          let Ajax = {
            resourseId: item,
            classId: selectData.checkedClass,
            remark: selectData.remark,
            studentCodes: selectData.checkedStudent.join(',')
          }
          if (name) {
            Ajax.resourcesName = name
          }
          upToSchoolParent(Ajax).then(() => {
            if (index == _this.ids.length - 1) {
              _this.msgSuccess('操作成功')
              _this.dialogVisible = false
            }
          })
        })
      }
    },
    upToCloudResourse() {
      this.isZdy = false
      let _this = this
      const resourcesIds = this.ids.join(',')
      this.title = '上传至云库'
      this.selectType = ''
      this.dialogVisible = true
    },
    upToSchoolResourse() {
      this.isZdy = true
      let _this = this
      const resourcesIds = this.ids.join(',')
      this.title = '上传至校本资源库'
      this.selectType = ''
      this.dialogVisible = true
    },
    upToSchoolClass() {
      this.isZdy = false
      let _this = this
      const resourcesIds = this.ids.join(',')
      this.title = '上传至班牌'
      this.selectType = 'class'
      this.dialogVisible = true
    },
    upToSchoolStudent() {
      this.isZdy = false
      let _this = this
      const resourcesIds = this.ids.join(',')
      this.title = '上传至学生端'
      this.selectType = 'student'
      this.dialogVisible = true
    },
    upToSchoolParent() {
      this.isZdy = false
      let _this = this
      const resourcesIds = this.ids.join(',')
      this.title = '上传至家长端'
      this.selectType = 'parent'
      this.dialogVisible = true
    },

    upToQuestion() {
      // 只能上传视频文件
      for (var idx = 0; idx < this.idsSel.length; idx++) {
        if (this.idsSel[idx].type != 1) {
          this.$message.warning('只能上传视频文件！')
          return
        }
      }
      this.quesDialog = true
    },
    submitQuestion() {
      this.$refs['formQuestion'].validate((valid) => {
        if (valid) {
          this.quesLoading = true
          this.ids.forEach((item, index) => {
            let paramObj = {
              questionId: this.form.questionId,
              resourseId: item
            }
            updataQuestion(paramObj)
              .then((response) => {
                this.msgSuccess('上传成功')
                this.quesLoading = false
                this.cancelQuestion()
              })
              .catch((err) => {
                console.log(err)
                this.quesLoading = false
              })
          })
        }
      })
    },
    cancelQuestion() {
      this.questionId = ''
      this.quesDialog = false
    },
    dialogVisibleClose() {
      this.dialogVisible = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        resourcesId: null,
        resourcesName: null,
        sourceId: null,
        category: null,
        chapterId: null,
        knowledgeBasicId: null,
        resourcesUrl: null,
        type: null,
        linkWay: null,
        bookId: null,
        customerId: null,
        subjectId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        remark: null
      }
    },
    /** 搜索按钮操作 */
    async handleQuery(data, type) {
      this.pageNum = 1
      this.queryParams = Object.assign(this.queryParams, data)
      this.queryParams.wayType = data.wayType || '1'
      await this.getTreeselect(type)
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery(data, type) {
      this.queryParams = data
      this.queryParams.chapterId = ''
      this.pageNum = 1
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.idsSel = selection.map((item) => item)
      this.ids = selection.map((item) => item.resourcesId)
      this.resourcesNames = selection.map((item) => item.resourcesName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    createCoursewareRules() {
      return {
        subjectid: [{ required: true, message: '科目必选' }],
        edition: [{ required: true, message: '版本必选' }],
        slipid: [{ required: true, message: '学册必选' }]
      }
    },
    createCoursewareParams() {
      const sharedParams = { source: consts.enum.librarySource.courseware }
      return {
        subjectid: sharedParams,
        edition: sharedParams,
        slipid: sharedParams
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加个人资源库'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const resourcesId = row.resourcesId || this.ids
      getInfo(resourcesId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改个人资源库'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.resourcesId != null) {
            modifyPersonResourceInfo(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            add(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const resourcesIds = row.resourcesId || this.ids
      this.$confirm(
        '是否确认删除个人资源库名称为"' + row.resourcesName + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return remove(row.resourcesId)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有个人资源库数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true
          return exportList(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
          this.exportLoading = false
        })
    },
    /** 查询章节下拉树结构 */
    async getTreeselect(type) {
      if (type == 'coursewareType') return
      if (this.queryParams.wayType == 1) {
        if (
          (type != 'slipid' && type != 'wayType') ||
          this.viewName == 'Custom'
        ) {
          this.deptOptions = []
          this.KnowledgeOptions = []
          this.queryParams.chapterId = ''
          return
        }
        let Ajax = {
          editionId: this.queryParams.edition, //版本
          subjectId: this.queryParams.subjectid, //科目
          pharseId: this.queryParams.pharseId, //pharseId
          gradeId: this.queryParams.slipid //学册
          // gradeid:301
        }
        this.deptOptions = []
        if (!Ajax.gradeId) return
        this.treeLoading = true
        this.queryParams.chapterId = ''
        const resTree = await treeList(Ajax)
        this.deptOptions = resTree.data
        this.treeLoading = false
      } else {
        if (
          (type != 'subjectid' && type != 'wayType') ||
          this.viewName == 'Custom'
        ) {
          this.deptOptions = []
          this.KnowledgeOptions = []
          this.queryParams.chapterId = ''
          return
        }
        let Ajax = {
          subjectId: this.queryParams.subjectid,
          pharseId: this.queryParams.pharseId
        }
        this.KnowledgeOptions = []
        if (!Ajax.subjectId) return
        this.treeLoading = true
        this.queryParams.chapterId = ''
        const resTree = await knowledgeTree(Ajax)
        let list = this.filterData(resTree.data, 0)
        this.KnowledgeOptions = list
        this.treeLoading = false
      }
    },
    filterData(data, index) {
      let children = []
      data.forEach((item) => {
        item.tier = index
        if (item.children && index < 2) {
          item.children = this.filterData(item.children, index + 1)
        } else {
          item.children = null
        }
        children.push(item)
      })
      return children
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (!data.children?.length) {
        this.pageNum = 1
        this.queryParams.chapterId = data.id
        this.getList()
      } else {
        this.queryParams.chapterId = ''
      }
    }
  }
}
</script>
