<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-row">
        <div class="filter-group">
          <div class="filter-lable"> 关键字：</div>
          <el-input v-model="KEYWORDS" placeholder="搜索" clearable style="width: 200px;" @clear="getQuery"/>
        </div>
        <el-button v-waves class="ml-10" type="primary" icon="el-icon-search" @click="getQuery">
          搜索
        </el-button>
        <el-button v-waves type="success" icon="el-icon-refresh" @click="goKeyReset">
          重置
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="CORP_NAME" label="企业名称" />
      <el-table-column prop="DOCKING_KEY" label="对接KEY" align="center" />
      <el-table-column prop="DOCKING_IV" label="对接IV" />
      <el-table-column prop="DOCKING_URL" label="对接URL" />
      <el-table-column label="操作" align="center" width="360">
        <template slot-scope="{row}">
          <div class="clear_interval">
            <el-button type="success" icon="el-icon-delete" size="mini" @click="handleEdit(row.CORPINFO_ID)">编辑</el-button>
            <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.CORPINFO_ID)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="600px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;">
        <el-form-item label="企业名称" prop="CORP_NAME">
          <el-select v-model="form.CORP_NAME" :disabled="dialogType==='edit'" filterable clearable placeholder="请选择企业" style="width: 100%">
            <el-option v-for="item in corpList" :key="item.CORPINFO_ID" :label="item.CORP_NAME" :value="item.CORPINFO_ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="对接KEY" prop="DOCKING_KEY">
          <el-input id="DOCKING_KEY" ref="DOCKING_KEY" v-model="form.DOCKING_KEY" maxlength="255" placeholder="这里输入对接KEY..." title="对接KEY"/>
        </el-form-item>
        <el-form-item label="对接IV" prop="DOCKING_IV">
          <el-input id="DOCKING_IV" ref="DOCKING_IV" v-model="form.DOCKING_IV" maxlength="255" placeholder="这里输入对接IV..." title="对接IV"/>
        </el-form-item>
        <el-form-item label="对接URL" prop="DOCKING_URL">
          <el-input id="DOCKING_URL" ref="DOCKING_URL" v-model="form.DOCKING_URL" maxlength="255" placeholder="这里输入对接URL..." title="对接URL"/>
        </el-form-item>
        <el-form-item label="企业CODE" prop="CODE">
          <el-input id="CODE" ref="CODE" v-model="form.CODE" maxlength="255" placeholder="这里输入企业CODE..." title="企业CODE"/>
        </el-form-item>
        <el-form-item label="企业APPID" prop="APPID">
          <el-input id="APPID" ref="APPID" v-model="form.APPID" maxlength="255" placeholder="这里输入企业APPID..." title="企业APPID"/>
        </el-form-item>
        <el-form-item label="企业SECRET" prop="SECRET">
          <el-input id="SECRET" ref="SECRET" v-model="form.SECRET" maxlength="255" placeholder="这里输入企业SECRET..." title="企业SECRET"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
// import { upload } from '@/utils/upload'
import pdf from 'vue-pdf'
import SelectTree from '@/components/SelectTree'
export default {
  components: { Pagination, pdf, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      KEYWORDS_USER: '',
      dates: [],
      userListQuery: {
        page: 1,
        limit: 10
      },
      userTotal: 0,
      total: 0,
      config: config,
      KEYWORDS: '',
      FEEDBACK_TYPE: '',
      varList: [],
      pd: [],
      corpVarList: [],
      corpList: [],
      form: {
        CORPINFO_ID: '',
        DOCKING_KEY: '',
        DOCKING_IV: '',
        DOCKING_URL: '',
        CODE: '',
        APPID: '',
        SECRET: ''
      },
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormUser: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      // pdf预览
      dialogViewPdf: false,
      serverurl: config.fileUrl,
      pdfUrl: '',
      pageNum: 1,
      pageTotalNum: 1, // 总页数
      loadedRatio: 0, // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
      rules: {
        CORPINFO_ID: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
        DOCKING_KEY: [{ required: true, message: '对接KEY不能为空', trigger: 'blur' }],
        DOCKING_IV: [{ required: true, message: '对接IV不能为空', trigger: 'blur' }],
        DOCKING_URL: [{ required: true, message: '对接URL不能为空', trigger: 'blur' }],
        CODE: [{ required: true, message: '对接CODE不能为空', trigger: 'blur' }],
        APPID: [{ required: true, message: '对接APPID不能为空', trigger: 'blur' }],
        SECRET: [{ required: true, message: '对接SECRET不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDict()
    // this.getIdcList()
  },
  methods: {
    getRowKey(row) {
      return row.SURVEY_ID
    },
    handleAdd() {
      this.dialogType = 'add'
      this.$refs.form && this.$refs.form.clearValidate()
      this.resetForm()
      this.dialogFormEdit = true
      this.getCorpList()
    },
    getCorpList() {
      requestFN(
        '/responsibleperson/CorplistAll',
        {
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.corpList = data.varList
        }
      }).catch((e) => {

      })
    },
    handleEdit(ID) {
      this.$refs.form && this.$refs.form.clearValidate()
      this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/responsibleperson/goEdit',
        {
          CORPINFO_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
      }).catch((e) => {
        this.listLoading = false
      })
      this.dialogFormEdit = true
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          requestFN(
            '/responsibleperson/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.FEEDBACK_TYPE = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/responsibleperson/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          FEEDBACK_TYPE: this.FEEDBACK_TYPE,
          CREAT_TIME: this.CREAT_TIME
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.hasButton()
        this.total = data.page.totalResult
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },

    validStr(str) {
      if (str != null && str != '' && typeof (str) != 'undefined' && str != 0) { return true }
      return false
    },
    beforeDataFileUpload(file) {
      const types = ['doc', 'docx', 'pdf']
      const fileSuffix = file.name.slice(file.name.lastIndexOf('.') + 1)
      const isImage = types.includes(fileSuffix.toLowerCase())
      if (this.fileList.length > 0) {
        this.$message.error('文件超出个数限制!')
        return false
      }
      if (!isImage) {
        this.$message.error('上传文件格式只能是PDF 格式!')
        return false
      } else {
        const filistMap = {}
        filistMap.name = file.name
        filistMap.file = file
        this.fileList.push(filistMap)
        this.form.cfile = file
        this.form.COURSEWAREFILES = file
        this.$forceUpdate()
        return true
      }
    },
    handleRemoveData(file, fileList) { // 文件列表移除文件时的钩子
      if (file.file) {
        const types = ['doc', 'docx', 'pdf']
        const isImage = types.includes(file.file.type)
        if (isImage) {
          this.fileList = []
        }
      }
    },
    beforeCaptureFileUpload(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.ccfile = file
        this.form.COURSEWARECAPTURE = file
        this.$forceUpdate()
        return false
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.form.dialogImageUrl = file.url
      this.form.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    handleEditChange(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    // pdf 预览
    goViewPdf(filePath) {
      this.pageNum = 1
      this.pdfUrl = this.serverurl + filePath
      this.dialogViewPdf = true
    },
    // 上一页
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },

    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/responsibleperson/delete',
          {
            CORPINFO_ID: id
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.CORPINFO_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/responsibleperson/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      this.add = true
      this.del = true		// 删除权限
      this.edit = true	// 修改权限
    },
    // 获取数据字典数据
    getDict: function() {
      // requestFN(
      //   '/dictionaries/getLevels',
      //   {
      //     DICTIONARIES_ID: '532282f9c48346b8b646531909c739df'
      //   }
      // ).then((data) => {
      //   this.LearnerCategoryList = data.list
      // }).catch((e) => {
      //
      // })
      // requestFN(
      //   '/dictionaries/getLevels',
      //   {
      //     DICTIONARIES_ID: '3c0d9b5e74834adfacb76139e5d731e5'
      //   }
      // ).then((data) => {
      //   this.dicListMap.outlineDicList = data.list
      // }).catch((e) => {
      // })
    },
    resetForm() {
      this.form = {
        CORPINFO_ID: '',
        DOCKING_KEY: '',
        DOCKING_IV: '',
        DOCKING_URL: '',
        CODE: '',
        APPID: '',
        SECRET: ''
      }
      // if (this.$refs.pxTree) {
      //   this.$refs.pxTree.clearHandle()
      // }
      // if (this.$refs.gwTree) {
      //   this.$refs.gwTree.clearHandle()
      // }
      // if (this.$refs.dataUpload || this.fileList.length > 0) {
      //   this.fileList = []
      //   // this.form.ccfile = ''
      //   // this.form.COURSEWARECAPTURE = ''
      //   this.hideUpload = false
      //   this.$refs.dataUpload.clearFiles()
      // }
      // if (this.$refs.dataCaptureUpload) {
      //   this.form.cfile = ''
      //   this.$refs.dataCaptureUpload.clearFiles()
      // }
    },
    getDicListByPID(pId, listName) {
      requestFN(
        '/dictionaries/listAllDictToParId',
        {
          parentId: pId
        }
      ).then((data) => {
        this.dicListMap[listName] = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    // getIdcList() {
    //   this.getDicListByPID('052369aa22d242118236cde52d0c67ea', 'trainDicList')
    //   this.getDicListByPID('f6a7c4f5602f46e291d06b1390a3f820', 'postDicList')
    //   this.getDicListByPID('d538d11e4eec409ab428f5d2f3c67c24', 'trainingSectionList') // 培训板块
    //   this.getDicListByPID('4459d3ff36d1475d8b2266da959fcc44', 'relatedTermList') // 相关词条
    //   this.getTeacher()
    // },
    // 修改
    handleEditState(ID, state) {
      requestFN(
        '/survey/editState',
        {
          SURVEY_ID: ID,
          IS_PUBLISH: state
        }
      ).then((data) => {
        this.$message({
          message: '发布成功',
          type: 'success'
        })
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    delFujian(item) {
      this.form.fileIsType = true
      this.form.COURSEWAREFILES = ''
    },
    delFujianTupian(item) {
      this.form.captureIsType = true
      this.form.COURSEWARECAPTURE = ''
      this.form.ccfile = ''
      this.hideUpload = false
    }

  }
}

</script>
<style lang="scss">
  .hide .el-upload--picture-card {
    display: none;
  }
  div.popContainer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
  }
</style>
