<template>
  <custom-query-view
    :key="'customDialogView' + key"
    ref="customQueryView"
    name="字符串"
    :custdialog="customDialog"
    :permission="'w'"
    style="width: 100%; height: 100%"
    :style="{
      minHeight: (!tableHeight || !tableMaxHeight) && '400px',
    }"
    :tool-buttons="toolButtons"
    :column-buttons="columnButtons"
    :query-bind-options="queryBindOptions"
    :table-max-height="tableMaxHeight"
    @exports="exports"
    @toolButtonClick="toolButtonClick"
    @columnBtnClick="columnBtnClick"
  ></custom-query-view>
</template>

<script>
  import customQueryView from './main.vue'
  import { saveAs } from 'file-saver'

  export default {
    name: 'HtCustomDialogView',
    components: { customQueryView },
    props: {
      alias: {
        type: String,
        default: '',
      },
      queryBindOptions: {
        type: Object,
        default: null,
      },
      sqlViewId: {
        type: String,
        default: '',
      },

      tableMaxHeight: {
        type: [Number, String],
        default: '',
      },
    },
    data() {
      return {
        viewId: this.sqlViewId,
        tableData: [],
        pageResult: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
        dialogExportVisible: false,
        autofocus: false,
        displayFields: [],
        searchFields: [],
        baseSearchQuery: {},
        tableKey: 0,
        combineSearchFields: [],
        quickSearchProps: '',
        queryView: {},
        needPage: true,
        toolButtons: [],
        columnButtons: [],
        key: 0,
      }
    },
    computed: {
      customDialog() {
        return {
          name: '请选择',
          icon: '',
          custDialog: {
            selectNum: 1,
            conditions: [],
            mappingConf: [],
            custQueryJson: [],
            alias: this.queryView.customDialogAlias,
          },
          resultField: [],
          allowInput: false,
        }
      },
    },
    watch: {
      sqlViewId: {
        handler(val) {
          this.refresh(this.alias)
        },
        immediate: true,
        deep: true,
      },
    },
    created() {
      if (this.alias) {
        this.refresh(this.alias)
      }
    },
    mounted() {},
    methods: {
      refresh(alias) {
        if (alias) {
          this.$requestConfig.getQuerySqldefByAlias(alias).then((data) => {
            this.displayFields = data.metafields
            this.searchFields = data.metafields.filter(
              (e) => e.isSearch && !e.isCombine
            )
            this.combineSearchFields = data.metafields.filter(
              (e) => e.isSearch && e.isCombine
            )
            this.quickSearchProps = this.combineSearchFields
              .map((e) => e.fieldName)
              .join(',')
            this.queryView = data
            this.needPage = this.queryView.customDialog.needPage
            this.tableKey = this.tableKey + 1
            // this.$refs.queryViewList.load()
            this.toolButtons = JSON.parse(this.queryView.buttonDef)
              .filter(
                (e) =>
                  !e.inRow &&
                  e.urlPath.replaceAll('(', '').replaceAll(')', '') !==
                    'exports'
              )
              .map((e) => {
                return {
                  text: e.name,
                  func: e.urlPath.replaceAll('(', '').replaceAll(')', ''),
                }
              })
            this.columnButtons = JSON.parse(this.queryView.buttonDef)
              .filter(
                (e) =>
                  e.inRow &&
                  e.urlPath.replaceAll('(', '').replaceAll(')', '') !==
                    'exports'
              )
              .map((e) => {
                return {
                  text: e.name,
                  func: e.urlPath.replaceAll('(', '').replaceAll(')', ''),
                  triggerType: e.triggerType,
                  urlPath: e.urlPath,
                }
              })
            this.key = this.key + 1
            this.$nextTick(() => {
              this.$refs.customQueryView.showDialog()
            })
          })
        }
      },
      exportData() {},
      //加载列表
      loadTableData: function (param, cb) {
        !param && (param = {})
        param.pageBean = this.pageResult
        if (!this.needPage) {
          param.pageBean = {
            page: 1,
            pageSize: -1,
            total: 0,
          }
        }
        param = {
          data: param,
          method: this.queryView.customDialog.requestType,
          url: this.queryView.customDialog.url,
        }
        this.$requestConfig
          .doQueryByRest(param)
          .then((resp) => {
            this.tableData = resp.rows
            this.pageResult = {
              page: resp.page,
              pageSize: resp.pageSize,
              total: resp.total,
            }
          })
          .finally(() => cb && cb())
      },
      handleSelectionChange(a, b) {
        console.log(a, b)
      },
      handleSizeChange: function (size) {
        //每页下拉显示数据
        this.pageResult.pageSize = size
        if (this.$refs.queryViewList) {
          this.$refs.queryViewList.load()
        } else {
          this.loadTableData()
        }
      },
      handleCurrentChange: function (currentPage) {
        //点击第几页
        this.pageResult.page = currentPage
        if (this.$refs.queryViewList) {
          this.$refs.queryViewList.load()
        } else {
          this.loadTableData()
        }
      },
      exports(that) {
        let selection = that.$refs.multipleExportTable.$refs.htTable.selection
        let displayfield = that.displayfield
        displayfield = displayfield.filter((e) => {
          return selection.some((a) => a.field === e.field)
        })
        let queryParam = that.finalQueryParam
        if (!selection.length) {
          this.$message.warning('请选择导出字段')
          return
        }
        const loading = this.$loading({
          lock: true,
          text: '导出中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        queryParam.data.pageBean.pageSize = -1
        queryParam.exportFields = displayfield
        queryParam.listKey = this.queryView.customDialog.listKey
        this.$requestConfig
          .exportQueryByRest(queryParam)
          .then(({ data, headers }) => {
            const fileName = decodeURIComponent(
              headers['content-disposition'].split(';')[1].split('filename=')[1]
            )
            const blob = new Blob([data])
            saveAs(blob, fileName)
          })
          .catch((e) => {
            console.error(e)
          })
          .finally(() => {
            loading.close()
            that.dialogExportVisible = false
          })
      },
      printList() {},
      exportCancel() {},
      handleExportSelectAll() {},
      handleExportSelectionChange() {},
      toolButtonClick(func, that) {
        this.$emit('toolButtonClick', func, that)
      },
      columnBtnClick(func, that, row) {
        this.$emit('columnBtnClick', func, that, row)
      },
    },
  }
</script>

<style lang="scss">
  .summary-table {
    margin: 8px 24px;

    .project-column {
      .cell {
        font-size: 16px;
        color: #333;
        font-weight: bold;
      }
    }

    .summary-num {
      .summary-table-field {
        font-size: 18px;
        color: #4ba232;
        font-weight: bold;
      }
    }
  }

  .custom-summary {
    padding: 10px 24px 24px 24px;
  }
  ::v-deep {
    .el-container {
      height: calc(100% - 30px) !important;
    }
  }
</style>
