<template>
  <div :class="noPadding ? 'reportMainNoPadding' : 'reportMain'">
    <table class="reportTable" :style="config.style ? config.style : undefined">
      <tbody class="'reportTable'">
        <!--   标题   -->
        <tr v-if="showTitle && config.title.type && config.title.type !== ''">
          <td :class="noTopBorder ? 'tdWithNoTopBorder' : 'tdWithBorder'" colspan="12">
            <template v-if="config.title.type === 'titleKey'">
              {{ config.data[config.title.value] }}
            </template>
            <template v-else-if="config.title.type === 'titleValue'">
              {{ config.title.value }}
            </template>
          </td>
        </tr>
        <template v-for="(row, rowIndex) in config.content">
          <!--     数据对象是一个Obj     -->
          <template v-if="row.type === 'jsonKey'">
            <tr :key="rowIndex">
              <!--      表头        -->
              <td
                :class="noTopBorder ? 'tdWithNoTopBorder' : 'tdWithBorder'"
                :style="determineCellStyle(receivedFunction[rowIndex].labelFunction(config, item))"
                colspan="6">
                <template v-if="receivedFunction[rowIndex].labelFunction(config).type === 'key'">
                  {{ config.data[receivedFunction[rowIndex].labelFunction(config).content] }}
                </template>
                <template v-else-if="receivedFunction[rowIndex].labelFunction(config).type === 'value'">
                  {{ receivedFunction[rowIndex].labelFunction(config).content }}
                </template>
              </td>
              <!--      内容        -->
              <td
                :class="noTopBorder ? 'tdWithNoTopBorder' : 'tdWithBorder'"
                :style="determineCellStyle(receivedFunction[rowIndex].valueFunction(config))"
                colspan="6">
                <template v-if="displayOnly">
                  <template v-if="receivedFunction[rowIndex].valueFunction(config).type === 'key'">
                    {{ config.data[receivedFunction[rowIndex].valueFunction(config).content] }}
                  </template>
                  <template v-else-if="receivedFunction[rowIndex].valueFunction(config).type === 'value'">
                    {{ receivedFunction[rowIndex].valueFunction(config).content }}
                  </template>
                </template>
                <template v-else>
                  <template v-if="receivedFunction[rowIndex].valueFunction(config).originalKey">
                    <a-input v-model="config.data[receivedFunction[rowIndex].valueFunction(config).originalKey]"/>
                  </template>
                  <template v-else>
                    <a-input v-model="config.data[receivedFunction[rowIndex].valueFunction(config).content]"/>
                  </template>
                </template>
                <template v-if="receivedFunction[rowIndex].valueFunction(config).type === 'img'">
                  <template v-for="(img, imgIndex) in receivedFunction[rowIndex].valueFunction(config).content">
                    <span :key="imgIndex" class="imgText">
                      <a-icon type="link"/>
                      <span @click="openImgModal(img)">{{ formatImgName(img) }}</span>
                      <br/>
                    </span>
                  </template>
                </template>
              </td>
            </tr>
          </template>
          <!--     数据对象是一个Array     -->
          <template v-else-if="row.type === 'jsonArray'">
            <tr :key="rowIndex + '' + jsonArrayItemIndex" v-for="(item, jsonArrayItemIndex) in config.data[row.jsonArrayDataIndex]">
              <!--      表头        -->
              <td
                :class="noTopBorder ? 'tdWithNoTopBorder' : 'tdWithBorder'"
                :style="determineCellStyle(receivedFunction[rowIndex].labelFunction(config, item))"
                colspan="6">
                <template v-if="receivedFunction[rowIndex].labelFunction(config, item).type === 'key'">
                  {{ item[receivedFunction[rowIndex].labelFunction(config, item).content] }}
                </template>
                <template v-if="receivedFunction[rowIndex].labelFunction(config, item).type === 'value'">
                  {{ receivedFunction[rowIndex].labelFunction(config, item).content }}
                </template>
              </td>
              <!--      内容        -->
              <td
                :class="noTopBorder ? 'tdWithNoTopBorder' : 'tdWithBorder'"
                :style="determineCellStyle(receivedFunction[rowIndex].valueFunction(config, item))"
                colspan="6">
                <template v-if="displayOnly">
                  <template v-if="receivedFunction[rowIndex].valueFunction(config, item).type === 'key'">
                    {{ item[receivedFunction[rowIndex].valueFunction(config, item).content] }}
                  </template>
                  <template v-if="receivedFunction[rowIndex].valueFunction(config, item).type === 'value'">
                    {{ receivedFunction[rowIndex].valueFunction(config, item).content }}
                  </template>
                  <template v-if="receivedFunction[rowIndex].valueFunction(config, item).type === 'imgs'">
                    <template v-if="!item.imgs || item.imgs.length === 0">
                      <p style="margin: auto">无</p>
                    </template>
                    <template v-else>
                      <template v-for="(img, imgIndex) in item.imgs">
                        <div :key="imgIndex">
                          <img :src="img.path" style="max-width: 200px; max-height: 200px"/>
                          <p style="margin: auto">
                            {{ img.path.substring(img.path.lastIndexOf('/') + 1, img.path.lastIndexOf('.')) }}
                          </p>
                        </div>
                      </template>
                    </template>
                  </template>
                </template>
                <template v-else>
                  <template v-if="receivedFunction[rowIndex].valueFunction(config, item).originalKey">
                    <template v-if="receivedFunction[rowIndex].valueFunction(config, item).type === 'imgs'">
                      <upload
                        :model="{
                          type: 'image',
                          accept: ['*'],
                          resUploadStock: 1,
                          pathKey: 'cs'
                        }"
                        :outer-container-index="1"
                        :img-prefix="imgPrefix"
                        :service-name="serverName"
                        :images="checkImg(item.imgs)"
                        @setFiles="(...args) => {setImages(args, item, config.data)}"
                        :upload-style="'simple'"
                      />
                    </template>
                    <template v-else>
                      <a-input v-model="item[receivedFunction[rowIndex].valueFunction(config, item).originalKey]"/>
                    </template>
                  </template>
                  <template v-else>
                    <a-input v-model="item[receivedFunction[rowIndex].valueFunction(config, item).content]"/>
                  </template>
                </template>
              </td>
            </tr>
          </template>
        </template>
      </tbody>
    </table>
    <!--  图片展示弹框  -->
    <a-modal
      title="图片"
      width="80%"
      :visible="showImgModal"
      @ok="handleShowImgOk"
      @cancel="handleShowImgCancel"
      :z-index="1001"
      :destroyOnClose="true">
      <div style="width: 100%;display: flex;justify-content: center;align-items: center">
        <img :src="showImageSrc" alt="图片"/>
      </div>
    </a-modal>
  </div>
</template>

<script>
import Upload from '@vue2-client/base-client/components/common/Upload'
import { nanoid } from 'nanoid'

export default {
  name: 'XReportJsonRender',
  components: {
    Upload
  },
  props: {
    // 配置
    config: {
      type: Object,
      required: true
    },
    // 表格没有边距
    noPadding: {
      type: Boolean,
      default: false
    },
    // 表格没有上边框，与noPadding搭配可以实现连续表格
    noTopBorder: {
      type: Boolean,
      default: false
    },
    // 命名空间
    serverName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
    // 是否展示标题
    showTitle: {
      type: Boolean,
      default: true
    },
    // 是否仅展示
    displayOnly: {
      type: Boolean,
      default: true
    },
    // 图片上传后添加前缀
    imgPrefix: {
      type: String,
      default: undefined
    }
  },
  data () {
    return {
      // 储存所有json传递的函数
      receivedFunction: [],
      // 控制弹框显隐
      showImgModal: false,
      // 弹框中图片路径
      showImageSrc: undefined
    }
  },
  methods: {
    checkImg (target) {
      if (target === undefined) {
        return []
      }
      target.forEach(obj => {
        if (obj.imgid) {
          obj.uid = obj.imgid.toString()
        } else {
          obj.uid = nanoid(6)
        }
        if (obj.url === undefined) {
          if (obj.path) {
            obj.url = obj.path
          }
        }
        if (obj.name === undefined) {
          const withOutEndFix = obj.url.split('.')[0]
          const temp = withOutEndFix.split('/')
          obj.name = temp[temp.length - 1]
        }
        if (obj.status === undefined) {
          obj.status = 'done'
        }
      })
      return target
    },
    setImages (args, item, config) {
      // 如果基础上传组件在初始化完成后，就调用emit了setImage，此时图片并没有变化，直接返回
      if (args[2] === 'created') {
        return
      }
      const result = {
        name: item.f_project,
        data: args[0],
        orignalData: config
      }
      this.$emit('updateImg', result)
    },
    // 判断单元格样式
    determineCellStyle (labelFunctionReturn, color = '#000', borderWidth = '1px') {
      if (labelFunctionReturn.style) {
        // 如果声明了边框颜色
        if (labelFunctionReturn.style.borderColor) {
          color = labelFunctionReturn.style.borderColor
        }
        // 如果声明了边框宽度
        if (labelFunctionReturn.style.borderWidth) {
          borderWidth = labelFunctionReturn.style.borderWidth
        }
      }
      // 正常边框单元格
      const withBorder = {
        border: borderWidth + ' solid ' + color,
        padding: '8px'
      }
      // 仅没有上边框单元格
      const NoTopBorder = {
        borderTopStyle: 'none',
        borderLeft: borderWidth + ' solid ' + color,
        borderRight: borderWidth + ' solid ' + color,
        borderBottom: borderWidth + ' solid ' + color,
        padding: '8px'
      }
      let result = {}
      // 判断表头是否有声明的样式
      if (labelFunctionReturn.style !== undefined) {
        if (this.noTopBorder) {
          result = { ...NoTopBorder, ...labelFunctionReturn.style }
        } else {
          result = { ...withBorder, ...labelFunctionReturn.style }
        }
      } else {
        if (this.noTopBorder) {
          result = { ...NoTopBorder }
        } else {
          result = { ...withBorder }
        }
      }
      return result
    },
    handleShowImgOk () {
      this.showImgModal = false
      this.showImageSrc = undefined
    },
    handleShowImgCancel () {
      this.showImgModal = false
      this.showImageSrc = undefined
    },
    openImgModal (img) {
      this.showImageSrc = img
      this.showImgModal = true
    },
    formatImgName (imgSrc) {
      return imgSrc.split('/').pop()
    }
  },
  beforeMount () {
    // 遍历配置，将所有JSON传递的方法保存到一个数组中，并用index来一一对应
    for (let i = 0; i < this.config.content.length; i++) {
      this.receivedFunction.push({
        // eslint-disable-next-line no-eval
        labelFunction: eval('(' + this.config.content[i].customFunctionForLabel + ')'),
        // eslint-disable-next-line no-eval
        valueFunction: eval('(' + this.config.content[i].customFunctionForValue + ')')
      })
    }
  }
}
</script>

<style scoped lang="less">
.imgSrc {
  color: rgb( 24,144,255 );
  font-size: 0.9em;
  margin: auto;
}
.imgSrc:hover {
  color: rgba(24, 144, 255, 0.8);
  font-size: 0.9em;
  cursor: pointer;
}
.reportMain {
  text-align: center;
  margin: 0 auto;
  font-size: 16px;
  color: #000;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
}

.reportMainNoPadding {
  text-align: center;
  margin: 0 auto;
  font-size: 16px;
  color: #000;
  background-color: #fff;
  border-radius: 8px;
}

.reportTitle {
  font-weight: bold;
}

.reportTable {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  word-break: break-all;
}

.tdWithBorder {
  border: 1px solid #000;
  padding: 8px;
}

.imgText:hover {
  color: rgb(24, 144, 255);
  cursor: pointer;
}

.tdWithNoTopBorder {
  border-top-style: none;
  border-left: 1px solid #000;
  border-right: 1px solid #000;
  border-bottom: 1px solid #000;
  padding: 8px;
}
</style>
