<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="TITLE" label="问卷标题" />
      <el-table-column prop="BEGIN_TIME" label="开始时间" align="center" />
      <el-table-column prop="END_TIME" label="结束时间" align="center" />
      <el-table-column prop="IS_PUBLISH" label="状态" align="center" width="120">
        <template slot-scope="{row}">
          <template v-if="row.IS_PUBLISH=='0'">
            <div>未发布</div>
          </template>
          <template v-else-if="row.IS_PUBLISH=='1'">
            <div class="color-red">已发布</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="520">
        <template slot-scope="{row}">
          <div class="clear_interval">
            <el-button v-show="row.IS_PUBLISH == '0'" :disabled="!row.QUESTION_ID" type="info" icon="el-icon-switch-button" size="mini" @click="handleEditState(row.SURVEY_ID,'1')">发布</el-button>
            <el-button v-show="row.IS_PUBLISH == '1'" class="green-btn" icon="el-icon-switch-button" size="mini" @click="handleSurvey(row.SURVEY_ID)">查看问卷数据</el-button>
            <el-button v-if="row.IS_PUBLISH=='0'" type="primary" icon="el-icon-info" size="mini" @click="handleEdit(row.SURVEY_ID)">编辑问卷</el-button>
            <el-button v-if="row.IS_PUBLISH=='1'" type="primary" icon="el-icon-info" size="mini" @click="goInfo(row.SURVEY_ID)">涉及企业</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.SURVEY_ID)">删除</el-button>
            <el-button type="success" icon="el-icon-document" size="mini" @click="handleQuestion(row)">查看问卷内容</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新建问卷</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :visible.sync="dialogFormInfo" :title="dialogType==='info'?'查看':'查看'" width="800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="padding:0 40px 0 20px">
        <el-form-item label="通知企业" required>
          <div class="uo-flex">
            <el-input v-model="form.corpinfoNames" autosize type="textarea" placeholder="请选择通知企业..." disabled style="width: 100%" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormInfo = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="800px">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="padding:0 40px 0 20px">
        <el-form-item label="问卷标题" prop="TITLE">
          <el-input id="TITLE" ref="TITLE" v-model="form.TITLE" maxlength="255" placeholder="这里输入问卷标题..." title="问卷标题"/>
        </el-form-item>
        <el-form-item label="开始日期" prop="BEGIN_TIME">
          <el-date-picker v-model="form.BEGIN_TIME" style="width: 100%;" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="结束日期" prop="END_TIME">
          <el-date-picker v-model="form.END_TIME" style="width: 100%;" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="选择通知企业" required>
          <div class="uo-flex">
            <el-input v-model="form.corpinfoNames" autosize type="textarea" placeholder="请选择通知企业..." disabled style="width: 490px" />
            <el-button type="primary" style="margin-left:10px" icon="el-icon-arrow-down" @click="handleCorp">请选择</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button v-show="dialogType != 'info'" type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormUser" title="查看" width="800px">
      <div class="filter-container">
        <el-input v-model="KEYWORDS_USER" placeholder="搜索" class="filter-item" clearable style="width: 200px;" />
        <div class="filter-lable w80">是否十小：</div>
        <el-select v-model="issmall" placeholder="请选择" clearable style="width: 100px" class="filter-item" >
          <el-option v-for="item in issmallList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getCorpList">
          搜索
        </el-button>
        <el-button v-waves type="success" icon="el-icon-refresh" @click="goKReset">
          重置
        </el-button>
      </div>
      <el-table v-loading="corpListLoading" ref="multipleTable_corp" :row-key="getCorpRowKey" :data="corpVarList" :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="COMPANY_AREA" label="所属区域" />
        <el-table-column prop="ADDRESS" label="注册地址" />
        <el-table-column prop="LR_NAME" label="法定代表人" />
      </el-table>
      <pagination :total="userTotal" :page.sync="userListQuery.page" :limit.sync="userListQuery.limit" style="margin-top: 10px" @pagination="getCorpList" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmUser">确 定</el-button>
        <el-button @click="dialogFormUser = false">关 闭</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
      },
      corpListLoading: true,
      KEYWORDS_USER: '',
      userListQuery: {
        page: 1,
        limit: 10
      },
      userTotal: 0,
      total: 0,
      config: config,
      KEYWORDS: '',
      varList: [],
      pd: [],
      issmall: '1',
      issmallList: [{ label: '是', value: '1' }, { label: '否', value: '0' }],
      corpVarList: [],
      form: {
        TITLE: '',
        BEGIN_TIME: '',
        END_TIME: '',
        IS_PUBLISH: '',
        TYPE: '2',
        dialogVisible: false,
        fileIsType: true,
        trainingSection: [],
        relatedTerm: [],
        captureIsType: true,
        corpinfoIds: ''
      },
      hideUpload: false, // 显示图片
      fileList: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogFormUser: false,
      dialogFormInfo: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      // pdf预览
      dialogViewPdf: false,
      serverurl: config.fileUrl,
      pdfUrl: '',
      pageNum: 1,
      pageTotalNum: 1, // 总页数
      loadedRatio: 0, // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
      rules: {
        TITLE: [{ required: true, message: '问卷标题不能为空', trigger: 'blur' }],
        BEGIN_TIME: [{ required: true, message: '开始日期不能为空', trigger: 'blur' }],
        END_TIME: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: []
      },
      teacherAllList: [],
      vidStateList: [{ value: '0', label: '启用' },
        { value: '1', label: '禁用' }
      ]
    }
  },
  created() {
    this.getList()
    this.getDict()
    // this.getIdcList()
  },
  methods: {
    getRowKey(row) {
      return row.SURVEY_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getQuery()
    },
    getCorpRowKey(row) {
      return row.CORPINFO_ID
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/survey/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        console.log(this.varList)
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    confirmUser() {
      const _selectData = this.$refs.multipleTable_corp.selection
      const ids = _selectData.map((item, index) => {
        return item.CORPINFO_ID
      }).join(',')
      const names = _selectData.map((item, index) => {
        return item.CORP_NAME
      }).join(',')
      this.form.corpinfoIds = ids
      this.form.corpinfoNames = names
      this.dialogFormUser = false
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.getDict()
      this.dialogFormEdit = true
    },

    goInfo(ID) {
      this.resetForm()
      // this.getDict()
      this.dialogType = 'info'
      requestFN(
        '/survey/goEdit',
        {
          SURVEY_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        const CORPINFO_NAME = []
        for (let i = 0; i < data.itemList.length; i++) {
          CORPINFO_NAME.push(data.itemList[i].CORPINFO_NAME)
        }
        this.form.corpinfoNames = CORPINFO_NAME.join(',')
        this.form.fileIsType = false
        this.form.captureIsType = false
        this.dialogFormInfo = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 修改
    handleEdit(id) {
      this.$refs.form && this.$refs.form.clearValidate()
      this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/survey/goEdit',
        {
          SURVEY_ID: id
        }
      ).then((data) => {
        console.log(data)
        this.form = data.pd
        const CORPINFO_NAME = []
        const corpinfoIds = []
        for (let i = 0; i < data.itemList.length; i++) {
          CORPINFO_NAME.push(data.itemList[i].CORPINFO_NAME)
          corpinfoIds.push(data.itemList[i].CORPINFO_ID)
        }
        this.form.corpinfoNames = CORPINFO_NAME.join(',')
        this.form.corpinfoIds = corpinfoIds.join(',')
      }).catch((e) => {

      })
      this.dialogFormEdit = true
    },
    validStr(str) {
      if (str != null && str != '' && typeof (str) != 'undefined' && str != 0) { return true }
      return false
    },

    handleCorp() {
      this.KEYWORDS_USER = ''
      this.dialogFormUser = true
      this.getCorpList()
      this.getQuery()
      this.$refs.multipleTable_corp.clearSelection()
    },
    goKReset() {
      this.KEYWORDS_USER = ''
      this.getCorpList()
    },
    getCorpList() {
      this.corpListLoading = true
      requestFN(
        '/corpinfo/list?showCount=' + this.userListQuery.limit + '&currentPage=' + this.userListQuery.page,
        {
          KEYWORDS: this.KEYWORDS_USER,
          issmall: this.issmall,
          tm: new Date().getTime()
        }
      ).then((data) => {
        console.log(data.varList)
        this.corpListLoading = false
        this.corpVarList = data.varList
        this.userTotal = data.page.totalResult
        this.$refs.multipleTable.clearSelection()
      }).catch((e) => {
        this.corpListLoading = false
      })
    },

    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.corpinfoIds) {
            this.$message({
              message: '请选择要通知的企业',
              type: 'error'
            })
          } else {
            this.listLoading = true
            requestFN(
              '/survey/' + this.dialogType,
              this.form
            ).then((data) => {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.listLoading = false
              this.dialogFormEdit = false
              this.getList()
            }).catch((e) => {
              this.listLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    handleQuestion(row) {
      this.$parent.SURVEY_ID = row.SURVEY_ID
      this.$parent.activeName = 'Question'
      this.$parent.IS_PUBLISH = row.IS_PUBLISH
    },
    handleSurvey(ID) {
      this.$parent.SURVEY_ID = ID
      this.$parent.activeName = 'Surveyinfo'
    },
    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(
          '/survey/delete',
          {
            SURVEY_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.DATACOURSEWARE_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/surveyquestion/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() {
      var keys = 'surveyquestion:add,surveyquestion:del,surveyquestion:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.surveyquestionfhadminadd		// 新增权限
        this.del = data.surveyquestionfhadmindel		// 删除权限
        this.edit = data.surveyquestionfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    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 = {
        TITLE: '',
        BEGIN_TIME: '',
        END_TIME: '',
        TYPE: '2',
        IS_PUBLISH: '',
        fileIsType: true,
        captureIsType: true
      }
      // 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) {
      this.$confirm('确定要发布吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        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>
