<template>
  <div class="data-list-view">
    <el-row>
      <el-date-picker v-model="date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
    </el-row>
    <el-row>
      <el-table v-if="tableData" stripe border size="medium"
                style="max-width: 1040px; width: 100%"
                current-row-key="ID" :data="tableData">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="提交时间" prop="addTime" width="160"></el-table-column>
        <el-table-column v-for="(field, index) in fieldMap"
                         :key="field.label + '-' + index"
                         :label="field.label"
                         :min-width="(field.label.length * 16 + 24).toString()">
          <div slot-scope="scope" v-html="getDataValue(field, scope.row, scope.column)"></div>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <div slot-scope="scope">
            <el-button type="text" @click="$router.push('/plugins/customForm/customFormPreview/' + scope.row.ID)">
              <i class="fa fa-fw fa-eye data-item-action"></i>预览
            </el-button>
          </div>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-pagination :page-size="pagination.pageSize"
                     :total="pagination.total"
                     :pager-count="10"
                     :current-page.sync="pagination.pageIndex"
                     :page-sizes="pagination.pageSizes"
                     @size-change="onPageSizeChange"
                     prev-text="上一页"
                     next-text="下一页"></el-pagination>
    </el-row>
  </div>
</template>
<script>
import $util from '@src/common/util.js'

export default {
  props: {
    model: {
      type: Object,
      required: true
    }
  },
  mounted () {
    if (this.model && this.model.ID) {
      this.fieldMap = JSON.parse(this.model.nameLabelMap)
      axios.get(`/ui/customforms/getSiteUrl/${this.model.siteID}`).then(res => {
        if (res.data.status === 1) {
          this.siteUrl = res.data.data
          this.onDataChange()
        }
      })
    }
  },
  watch: {
    model: {
      handler () {
        if (this.model && this.model.ID) {
          this.fieldMap = JSON.parse(this.model.nameLabelMap)
          axios.get(`/ui/customforms/getSiteUrl/${this.model.siteID}`).then(res => {
            if (res.data.status === 1) {
              this.siteUrl = res.data.data
              this.onDataChange()
            }
          })
        }
      },
      deep: true
    },
    date: {
      handler () {
        this.onDataChange()
      },
      deep: true
    },
    'pagination.pageSize': 'onDataChange',
    'pagination.pageIndex': 'onDataChange'
  },
  data () {
    return {
      getting: false,
      data: [],
      date: [],
      fieldMap: [],
      tableData: null,
      siteUrl: '',
      pagination: {
        pageSize: 20,
        pageIndex: 1,
        total: 0,
        pageSizes: [20, 50, 100]
      }
    }
  },
  methods: {
    onPageSizeChange (size) {
      this.pagination.pageSize = size
    },
    onDataChange () {
      this.tableData = null
      if (this.model && this.model.ID && !this.getting) {
        this.getting = true
        let dateTag = this.date && this.date[0] && this.date[1]
        axios.get(`/ui/customforms/dataList/${this.model.ID}`, {
          params: {
            pageSize: this.pagination.pageSize,
            pageIndex: this.pagination.pageIndex - 1,
            startDate: dateTag ? $util.formatDate(this.date[0], 'yyyy-MM-dd') : '',
            endDate: dateTag ? $util.formatDate(this.date[1], 'yyyy-MM-dd') : ''
          }
        }).then(async res => {
          if (res.data.status === 1) {
            this.pagination.total = res.data.total
            res.data.data.forEach(item => { item.content = JSON.parse(item.content) })
            this.data = res.data.data
            this.tableData = await this.checkField(this.fieldMap, this.data)
          } else {
            this.clearData()
          }
        }).catch(() => { this.clearData() }).finally(() => { this.getting = false })
      } else {
        this.clearData()
      }
    },
    clearData () {
      this.data = []
      this.tableData = null
      this.pagination.total = 0
    },
    async checkField (fields, data) {
      let tableData = []
      for (let i = 0, dlen = data.length; i < dlen; i++) {
        let item = data[i]
        let itemData = {}
        for (let j = 0, flen = fields.length; j < flen; j++) {
          let field = fields[j]
          let res = []
          for (let k = 0, clen = field.controls.length; k < clen; k++) {
            let control = field.controls[k]
            let value = item.content[control.name]
            if (value || control.type === 'AddressWidget') {
              let valStr = ''
              valStr += control.prefix || ''

              switch (control.type) {
                case 'SwitchWidget':
                  valStr = value ? '是' : '否'
                  break

                case 'AddressWidget':
                  valStr += item.content[control.name + '-province'] || ''
                  valStr += valStr ? ' - ' : ''
                  valStr += item.content[control.name + '-city'] || ''
                  valStr += valStr ? ' - ' : ''
                  valStr += item.content[control.name + '-county'] || ''
                  break

                case 'UploadWidget':
                  let rRes = await axios.get(`/ui/customforms/getResources/${value}`)
                  if (rRes.data.status === 1 && rRes.data.data) {
                    let resource = rRes.data.data
                    valStr = `<a target="_blank" href="${this.siteUrl + resource.path}" download="${resource.oldName}">${resource.oldName}</a>`
                  }
                  break

                default:
                  valStr = Object.prototype.toString.call(value) === '[object Array]' ? '[' + value.join(', ') + ']' : value
                  break
              }

              valStr = valStr.replace(/[\r]?\n/gm, '<br/>')
              valStr += control.suffix || ''

              res.push(`<span class="custom-form-data-list-item-row">${valStr}</span>`)
            } else {
              res.push('')
            }
          }

          itemData[field.label] = res.join('<br/>')
        }

        itemData.ID = item.ID
        itemData.addTime = item.addTime
        tableData.push(itemData)
      }
      return tableData
    },
    getDataValue (field, row, col) {
      let value = row[field.label]
      let currentWidget = this.getStrWidth(value, 14) + 30
      if (currentWidget > col.minWidth) col.minWidth = currentWidget
      return value
    },
    getStrWidth (str, size) {
      let span = document.createElement('span')
      span.style.fontSize = size + 'px'
      span.innerHTML = str
      document.body.appendChild(span)
      let rect = span.getBoundingClientRect()
      let width = rect.width
      document.body.removeChild(span)
      return width
    }
  }
}
</script>

<style scoped>
  .data-list-view {
    margin-top: 10px;
  }

  .data-item-action:hover {
    color: #28b06e;
  }
</style>

<style>
  .data-list-view span.custom-form-data-list-item-row {
    display: inline-block;
    width: 100%;
    border-top: 1px solid #d9d9d9;
    margin-top: 2px;
  }

  .data-list-view span.custom-form-data-list-item-row:first-child {
    border-top: none;
    margin-top: 0;
  }
</style>
