<template>
  <div v-if="canDisplay" ref="columnCard" class="box-card">
    <div v-loading="loading">
      <div v-if="currentComponents">
        <component
          :is="currentComponents"
          :show-data="showData"
          :column-title="baseColumn.name"
          :is-hide-pagination="isHidePagination"
          :show-title="baseColumn.showTitle"
          :custom-column-height="baseColumn.colHeight"
          :page-size="baseColumn.refeshTime"
          :combination-model="designColumn.model"
          :more-url="baseColumn.colUrl"
          :filter-type="designColumn.filterType"
          :filter-scope="designColumn.filterScope"
          :alias="baseColumn.alias"
          :appid="baseColumn.appid"
          :isPublic="baseColumn.isPublic"
          left-bar-top="3px"
          :is-show-delete="false"
          @click-process="handleClickProcess"
          :custom-style="baseColumn.templateStyle"
        ></component>
      </div>
      <!--  <custom-dialog-show-detail
        v-if="isCustomDialog"
        ref="customDialogShowDetail"
        :alias="customDialog.alias"
        :custom-dialog="customDialog"
      /> -->
      <templatePreview
        v-if="isTemplate"
        :template-key="templateKey"
        single="true"
      ></templatePreview>
    </div>
  </div>
</template>
<script>
  import req from '@/request'
  /*   import CustomDialogShowDetail from '@/components/form/CustomDialogShowDetail.vue' */
  import hotentUiUtils from 'hotent-ui/src/utils.js'
  import { getColumnByAlias, getEchartsData } from '@/api/portal.js'

  export default {
    name: 'HtColumn',
    components: {
      /*    CustomDialogShowDetail, */
    },
    props: {
      columnAlias: {
        type: String,
        default: null,
        required: false,
      },
      // 是否来自于预览页面
      fromPreview: {
        type: Boolean,
        default: false,
      },
      isTab: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        data: {},
        isCommon: false,
        isChart: false,
        isReport: false,
        isCustomDialog: false,
        chartId: '',
        reportOption: {},
        loading: true,
        html: '<span>本栏目无模板</span>',
        column: {},
        customDialog: { alias: '' },
        pageBean: { page: 1, pageSize: 10, total: 0, showTotal: true },
        canDisplay: false,
        isTemplate: false,
        templateKey: '',
        currentComponents: '',
        baseColumn: {},
        designColumn: {},
        showData: null,
      }
    },
    computed: {
      templateParent() {
        return this
      },
      isHidePagination() {
        return this.baseColumn.needPage == '1' ? false : true
      },
    },
    watch: {
      'pageBean.page': function (val) {
        if (val && val > 0 && this.column.needPage == 1) {
          this.load()
        }
      },
    },
    mounted() {
      this.load()
    },
    methods: {
      openMore(url) {
        this.$router.push({ path: url })
      },
      refresh() {
        this.load()
      },
      load() {
        if (!this.columnAlias) {
          return
        }
        this.loading = true
        getColumnByAlias(this.columnAlias).then((response) => {
          let data = response
          if (data == null) {
            this.canDisplay = false
            this.loading = false
            return
          }
          this.column = data
          this.currentComponents = data.colType
          this.baseColumn = {
            ...data,
            showTitle: data.showTitle == 1 ? true : false,
          }
          this.designColumn = JSON.parse(data.dataParam)
          if (
            ['processCenter', 'combination', 'processPublicity'].includes(
              this.designColumn.colType
            )
          ) {
            this.showData = this.designColumn.selectType
          }
          if (
            ['statisticalChart', 'dataSheets'].includes(
              this.designColumn.colType
            )
          ) {
            let dataList = []
            dataList.push({
              dataType: this.designColumn.dataType,
              currentDataType: this.designColumn.currentDataType,
            })

            this.showData = dataList
          }
          if (
            this.designColumn.colType === 'news' ||
            this.designColumn.colType === 'swipeSlide'
          ) {
            this.showData = this.designColumn.announcementOrPictures
          }
          if (this.designColumn.colType === 'custom') {
            this.designColumn.templateHtml2 = Base64.decode(data.templateHtml)
            this.designColumn.templateJavaScript2 = Base64.decode(
              data.templateJavaScript
            )
            if (data && data.templateStyle) {
              this.designColumn.templateStyle2 = Base64.decode(
                data.templateStyle
              )
            }
            this.showData = data
          }
          //计算该栏目是否展示
          if (this.fromPreview) {
            this.canDisplay = true
          } else {
            this.canDisplay = this.column.displayRights
          }
          //如果无展示权限，则不进行栏目数据渲染了，并隐藏整个组件
          if (!this.canDisplay) {
            this.loading = false
            return
          }

          if (this.column.colType && this.column.colType == 1) {
            let dataParam = JSON.parse(this.column.dataParam)
            if (dataParam.chartType == 2) {
              this.chartId = dataParam.id
              this.isChart = true
              this.loading = false
            } else {
              this.isReport = true
              this.getChartsData(dataParam)
            }
          } else {
            //自定义对话框
            if (this.column.dataMode === 1) {
              this.getCustomDialogData()
            }
            //restful查询
            else if (this.column.dataMode === 3) {
              this.isCommon = true
              this.getDataToParse()
            } else if (this.column.dataMode === 4) {
              if (this.column.dataFrom) {
                let dataFrom = JSON.parse(this.column.dataFrom)
                this.templateKey = dataFrom.alias
              }
              this.isTemplate = true
              this.loading = false
            } else {
              this.isCommon = true
              this.dencodeHtml()
              this.loading = false
            }
          }
        })
      },
      //图标
      getChartsData(dataParam) {
        getEchartsData(dataParam.id).then(
          (response) => {
            if (response && response.value) {
              let opt = response.value
              if (opt.constructor == Array) {
                opt = opt[0]
              }
              this.reportOption = { ...opt }
            }
            this.loading = false
          },
          (err) => {
            this.loading = false
            this.html = `<span style='color:red;'>${err}</span>`
          }
        )
      },
      getDataToParse() {
        let column = this.column
        if (!column.dataFrom) {
          this.dencodeHtml()
          this.loading = false
          return
        }
        //post请求参数
        let queryParams = {}
        //如果需要分页
        if (column.needPage === 1) {
          queryParams.pageBean = this.pageBean
        }
        //get请求参数
        let urlParam = ''
        if (column.dataParam) {
          let ctx = {}
          const curUser = this.$store.state.login.currentUser
          if (curUser) {
            ctx.curUserAccount = curUser.account
            ctx.curUserId = curUser.userId
          }
          column.dataParam = hotentUiUtils.parseExp(column.dataParam, ctx)
        }
        let dataParam = JSON.parse(column.dataParam || '[]')
        if (dataParam) {
          for (var i = 0; i < dataParam.length; i++) {
            var value = dataParam[i]['value']
            var name = dataParam[i]['name']
            if (column.requestType == 'POST') {
              try {
                value = JSON.parse(value)
              } catch (e) {}
              queryParams[name] = value
              //如果参数中也设置了分页
              if (name === 'pageBean') {
                this.pageBean = value
              }
            } else {
              urlParam =
                i > 0
                  ? urlParam + '&' + name + '=' + value
                  : '?' + name + '=' + value
            }
          }
        }
        //请求获取数据
        if (column.requestType && column.requestType == 'POST') {
          req.post(column.dataFrom, queryParams).then(
            (response) => {
              this.data = response.data
              this.loading = false
              if (this.column.needPage === 1) {
                this.pageBean.page = this.data.page || 1
                this.pageBean.pageSize = this.data.pageSize || 10
                this.pageBean.total = this.data.total || 0
              }
              this.dencodeHtml()
            },
            (err) => {
              this.loading = false
              this.html = `<span style='color:red;'>${err}</span>`
            }
          )
        } else {
          req.get(column.dataFrom + urlParam).then(
            (response) => {
              this.data = response.data
              this.loading = false
              this.dencodeHtml()
            },
            (err) => {
              this.loading = false
              this.html = `<span style='color:red;'>${err}</span>`
            }
          )
        }
      },
      getCustomDialogData() {
        let this_ = this
        let dataFrom = JSON.parse(this.column.dataFrom || '{}')
        if (!dataFrom.alias) {
          this_.loading = false
          this_.isCommon = true
          this.dencodeHtml()
          return
        }
        let url =
          '${form}/form/customDialog/v1/getByAlias?alias=' + dataFrom.alias
        req.get(url).then(function (customDialog) {
          customDialog = customDialog.data
          //格式化对话框的显示字段、返回字段、条件字段、排序字段
          customDialog.displayfield = JSON.parse(customDialog.displayfield)
          for (let i = 0; i < customDialog.displayfield.length; i++) {
            customDialog.displayfield[i].field =
              customDialog.displayfield[i].field.toUpperCase()
          }
          customDialog.resultfield = JSON.parse(customDialog.resultfield)
          customDialog.sortfield = JSON.parse(customDialog.sortfield)
          customDialog.conditionfield = JSON.parse(customDialog.conditionfield)
          //列表
          if (customDialog.style == 0) {
            this_.customDialog = customDialog
            this_.isCustomDialog = true
            this_.loading = false
            setTimeout(() => {
              this_.$refs.customDialogShowDetail.initData() //显示自定义对话框列表预览弹框
            })
          }
        })
      },
      dencodeHtml() {
        let Base64 = require('js-base64').Base64
        if (this.column.templateHtml) {
          this.column.html = Base64.decode(this.column.templateHtml)
        }
      },
      handleClickProcess(process, type, tableData) {
        this.$emit('click-process', process, type, tableData)
      },
    },
  }
</script>
<style lang="scss" scoped>
  .box-card {
    border-radius: 12px;
    margin-top: 12px;
    background-color: #fff;
    overflow: hidden;

    .home-column__more {
      float: right;
      color: #959595;
    }
  }
</style>
