<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="考察人员">
              <j-search-select-tag
                v-model="queryParam.incarceratedUser"
                :async="true"
                dict="mr_incarcerated_user,name,id"
                placeholder="请选择考察人员">
              </j-search-select-tag>
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="问卷名称">
              <a-input v-model="queryParam.name" placeholder="请输入问卷名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="测评类型">
              <j-dict-select-tag v-model="queryParam.type" dictCode="Inspection_type"
                                 placeholder="请选择测评类型" />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="11" :md="12" :sm="24" :xl="10">
              <a-form-item label="创建日期">
                <j-date v-model="queryParam.createTime" :show-time="true" class="query-group-cust"
                        date-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择开始时间"></j-date>
                <span class="query-group-split-cust"></span>
                <j-date v-model="queryParam.updateTime" :show-time="true" class="query-group-cust"
                        date-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择结束时间"></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <span class="table-page-search-submitButtons" style="float: left;overflow: hidden;">
              <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
              <a-button icon="reload" style="margin-left: 8px" type="primary" @click="searchReset">重置</a-button>
              <a style="margin-left: 8px" @click="handleToggleSearch">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
              <!--              <a-button v-if="selectedRowKeys.length > 0" icon="download" style="margin-left: 12px" type="primary"-->
              <!--                        @click="handleExportXls('未成年人问卷调查结果表')">导出-->
              <!--      </a-button>-->
              <a-dropdown v-if="selectedRowKeys.length > 0">
                <a-menu slot="overlay">
                  <a-menu-item key="1" @click="batchDel">
                    <a-icon type="delete" />
                    删除
                  </a-menu-item>
                </a-menu>
                <a-button style="margin-left: 8px"> 批量操作
                  <a-icon type="down" />
                </a-button>
              </a-dropdown>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
        style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="ipagination"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :scroll="{x:true}"
        bordered
        class="j-table-force-nowrap"
        rowKey="id"
        size="middle"
        @change="handleTableChange">
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <!-- 字符串超长截取省略号显示 -->
        <span slot="name" slot-scope="text">
          <j-ellipsis :length='30' :value='text' />
        </span>
        <span slot="resultName" slot-scope="text, record">
          <a target="_blank" v-if="record.resultName !== undefined && record.resultName!==''" :href="record.resultPath">{{ record.resultName }}</a>
          <!--<span v-if="record.resultName !== undefined && record.resultName!==''">{{record.resultName}}</span>-->
          <a-upload
            v-else
            :action='uploadResultAction'
            :beforeUpload='beforeFileUpload'
            :data='uploadData(record)'
            :headers='headers'
            :multiple='false'
            :showUploadList='false'
            accept='.doc,.pdf,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            name='file'
            @change='(info) => uploadChange(info)'>
            <a>上传结果</a>
          </a-upload>
          <!--<j-upload v-else v-model='resultName' :multiple='false' :number='1' text='上传' @change="uploadChange"></j-upload>-->
        </span>
        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>详情</a>
          <!--          <a-divider type='vertical' />-->
          <!--          <a @click='fileUploadBtn(record)'>上传</a>-->
          <a-divider type='vertical' />
          <a @click="handleExportXls('未成年人问卷调查结果表',record)">导出</a>
          <a-divider type='vertical' />
          <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.questionnaire,record.wxUserId)'>
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <mr-questionnaire-survey-results-modal ref="modalForm" @ok="modalFormOk"></mr-questionnaire-survey-results-modal>
  </a-card>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { filterObj } from '@/utils/util'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import MrQuestionnaireSurveyResultsModal from './modules/MrQuestionnaireSurveyResultsModal'
import { deleteAction, downFile } from '@api/manage'
import JEllipsis from '@/components/jeecg/JEllipsis'
import { Base64 } from 'js-base64'

export default {
  name: 'MrQuestionnaireSurveyResultsList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    MrQuestionnaireSurveyResultsModal, JEllipsis
  },
  data() {
    var that = this
    let ellipsis = (v, l = 40) => (<j-ellipsis value={that.textReplaceAll(v)} length={l} />)
    return {
      uploadResultAction: window._CONFIG['domianURL'] + '/inspect/questionnaireSurveyResults/uploadQuestionnaireResult',
      headers: {},
      containerId: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 }
      },
      description: '测评问卷',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '考察人员',
          align: 'center',
          dataIndex: 'incarceratedUserName'
        },
        {
          title: '微信账号',
          align: 'center',
          dataIndex: 'wxUserId_dictText',
          customRender: (text) => {
            //字典值翻译通用方法
            return Base64.decode(text)
          }
        },
        {
          title: '测评类型',
          align: 'center',
          dataIndex: 'type_dictText'
        },
        {
          title: '问卷名称',
          align: 'center',
          dataIndex: 'name',
          customRender: (t) => ellipsis(t),
          key: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '测评日期',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '测评结果',
          align: 'center',
          dataIndex: 'resultName',
          key: 'resultName',
          scopedSlots: { customRender: 'resultName' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 160,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/inspect/questionnaireSurveyResults/list',
        delete: '/inspect/questionnaireSurveyResults/delete',
        deleteBatch: '/inspect/questionnaireSurveyResults/deleteBatch',
        exportXlsUrl: '/inspect/questionnaireSurveyResults/exportXls1',
        importExcelUrl: 'inspect/questionnaireSurveyResults/importExcel',
        doCheck: 'inspect/questionnaireSurveyResults/doCheck',
        uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload'
      },
      dictOptions: {},
      superFieldList: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onChange: page => {
          this.ipagination.current = page
          this.loadData()
        },
        onShowSizeChange: size => {
          this.ipagination.pageSize = parseInt(this.ipagination.pageSizeOptions[size])
          this.loadData()
        }
      },
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      /* 筛选参数 */
      filters: {},
      queryParam: { delflag: 0 },
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      uploadValidatorRules: {
        resultPath: [
          { required: true, message: '请上传文件!' }
        ]
      },
      uploadModel: {},
      disableUploadSubmit: false,
      uploadVisible: false,
      confirmLoading: false
    }
  },
  created() {
    this.getSuperFieldList()
    const token = Vue.ls.get(ACCESS_TOKEN)
    //---------------------------- begin 图片左右换位置 -------------------------------------
    this.headers = { 'X-Access-Token': token }
    this.containerId = 'container-ty-' + new Date().getTime()
    //---------------------------- end 图片左右换位置 -------------------------------------
  },

  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    beforeFileUpload(file) {
      let fileName = file.name
      let pos = fileName.lastIndexOf('.')
      let lastName = fileName.substring(pos, fileName.length)
      // console.log(lastName, lastName.toLowerCase())
      if (
        lastName.toLowerCase() !== '.pdf' &&
        lastName.toLowerCase() !== '.doc' &&
        lastName.toLowerCase() !== '.docx'
      ) {
        this.$message.error('文件必须为.pdf .doc .docx类型')
        return false
      }
      return true
    },
    uploadChange(info) {
      var that = this
      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} ${info.file.response.message}`, 3, function() {
            that.loadData()
          })
        } else {
          this.$message.error(`${info.file.response.message}`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`上传失败`)
      }
    },
    uploadData(record) {
      return { 'questionnaire': record.questionnaire, 'wxUserId': record.wxUserId }
    },
    textReplaceAll: function(text) {
      var reg = /<[^<>]+>/g
      var afterText = text.replace(reg, '').replace(/&nbsp;/ig, '').replace(/&ldquo;/ig, '').replace(/&rdquo;/ig, '')
      return afterText
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    getQueryParams() {
      // 获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      // 获取查询条件
      var queryParam = this.queryParam
      var isorter = this.isorter

      var param = Object.assign(sqp, queryParam, isorter, this.filters)

      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'datetime', value: 'createTime', text: '创建日期' })
      fieldList.push({ type: 'string', value: 'name', text: '问卷名称', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'question', text: '题目', dictCode: '' })
      fieldList.push({ type: 'Text', value: 'answer', text: '答案', dictCode: '' })
      fieldList.push({ type: 'int', value: 'type', text: '类型', dictCode: '' })
      fieldList.push({ type: 'string', value: 'incarceratedUser', text: '管制人员', dictCode: '' })
      this.superFieldList = fieldList
    },
    handleEdit: function(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = false
      this.$nextTick(() => {
        this.$refs.modalForm.getOrderMain()
      })
    },
    handleExportXls(fileName, record) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = {}
      // if (this.selectionRows.length > 1) {
      //   this.$message.warning('只能导出一个文件')
      //   return
      // } else {
      param.questionnaire = record.questionnaire
      param.wxUserId = record.wxUserId
      fileName = record.name
      // }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        console.log(data)
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }

        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          console.log(url)
          let link = document.createElement('a')

          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          console.log(link)
          document.body.appendChild(link)
          link.click()

          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    batchDel: function() {
      console.log(this.selectionRows)
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectionRows.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        var ids = ''
        var wxUserIds = ''
        var questionnaires = ''
        for (var a = 0; a < this.selectionRows.length; a++) {
          // ids += this.selectionRows[a] + ','
          wxUserIds += this.selectionRows[a].wxUserId + ','
          questionnaires += this.selectionRows[a].questionnaire + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            that.loading = true
            console.log(wxUserIds)
            console.log(questionnaires)
            deleteAction(that.url.deleteBatch, { wxUserIds: wxUserIds, questionnaires: questionnaires }).then((res) => {
              if (res.success) {
                //重新计算分页问题
                that.reCalculatePage(that.selectedRowKeys.length)
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    handleDelete: function(questionnaire, wxUserId) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      console.log(questionnaire, wxUserId)
      deleteAction(that.url.delete, { wxUserId: wxUserId, questionnaire: questionnaire }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>

<style>
.link_btn {
  display: inline-block;
}

.link_btn .ant-btn {
  border-color: rgba(255, 255, 255, 0);
  background-color: rgba(255, 255, 255, 0);
  box-shadow: none;
  padding: 0;
  color: #1890FF;
}

.link_btn .ant-btn i {
  display: none;
}

.link_btn .ant-btn > .anticon + span {
  margin-left: 0;
}
</style>