<template>
  <div>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" v-if="queryColumns.length > 0" style="margin-bottom: 8px;">
      <a-form layout="horizontal" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col v-for="(query, index) in queryColumns" :key="query.colCode"
                 :span="query.queryFormatJson.compColSpan || 6"
                 v-if="query.queryIsShow !== 'N'">
            <a-form-item :label="$locale(query.colName)" :labelCol="typeof query.queryFormatJson.labelColSpan !== 'undefined' ? {span: query.queryFormatJson.labelColSpan} : labelCol" :wrapperCol="typeof query.queryFormatJson.wrapperColSpan !== 'undefined' ? {span: query.queryFormatJson.wrapperColSpan} : wrapperCol">
              <view-select-tag
                v-if="query.showType === 'page'"
                :placeholder="$locale(query.colName)"
                v-model="query.queryDefaultValue"
                :viewCode="query.queryFormatJson.viewCode"
                :keyField="query.queryFormatJson.keyField"
                :labelField="query.queryFormatJson.labelField"
                :multi="query.queryFormatJson.multiple"
              />
              <query-field v-else :placeholder="$locale(query.colName)" v-model="query.queryDefaultValue"
                           :type="query.showType"
                           :linkageMap="linkageMap"
                           @setLinkageMap="changeQueryField(query, $event)"
                           :showConfig="query.queryFormatJson"
                           :dictOptions="dictOptions" :dictOptionsFlg="dictOptionsFlg"></query-field>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col v-for="(query, index) in queryColumns" :key="query.colCode"
                   :span="query.queryFormatJson.compColSpan || 6"
                   v-if="query.queryIsShow === 'N'">
              <a-form-item :label="$locale(query.colName)" :labelCol="typeof query.queryFormatJson.labelColSpan !== 'undefined' ? {span: query.queryFormatJson.labelColSpan} : labelCol" :wrapperCol="typeof query.queryFormatJson.wrapperColSpan !== 'undefined' ? {span: query.queryFormatJson.wrapperColSpan} : wrapperCol">
                <view-select-tag
                  v-if="query.showType === 'page'"
                  :placeholder="$locale(query.colName)"
                  v-model="query.queryDefaultValue"
                  :viewCode="query.queryFormatJson.viewCode"
                  :keyField="query.queryFormatJson.keyField"
                  :labelField="query.queryFormatJson.labelField"
                  :multi="query.queryFormatJson.multiple"
                />
                <query-field v-else :placeholder="$locale(query.colName)" v-model="query.queryDefaultValue"
                             :type="query.showType"
                             :linkageMap="linkageMap"
                             @setLinkageMap="changeQueryField(query, $event)"
                             :showConfig="query.queryFormatJson"
                             :dictOptions="dictOptions" :dictOptionsFlg="dictOptionsFlg"></query-field>
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="6">
              <span style="margin-top: 4px;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">{{ $locale('m.common.button.query') }}</a-button>
                <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $locale('m.common.button.reset') }}</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px" v-if="needToggleSearchStatus">
                  {{ toggleSearchStatus ? this.$locale('m.common.button.fold') : this.$locale('m.common.button.expand') }}
                  <ych-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a>
              </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

<!--    <WidgetItem :chartData="chartData" v-on="$listeners" :stores="stores" @setRootPk="setPk"/>-->
  </div>
</template>

<script>

// import { WidgetItem } from '../modules/widgetDesigner/packages'
import { postAction } from '../../utils/manage'
import YchConstant from '../../utils/YchConstant'
import QueryField from '../tag/QueryField'
import ViewSelectTag from '../viewSelect/ViewSelectTag'
import { initDictOptionMap } from '../Common/dict/YchDictSelectUtil'
import RelationUtil from "./RelationUtil";
import {handleCreateFunc, handleExecFunc} from '../../utils/actions'
import locleUtil from "../../utils/LocleUtil";

export default {
  name: 'ReportWidgetRedirect',
  components: {
    // WidgetItem,
    QueryField,
    ViewSelectTag
  },
  props: {
    widgetCode: String,
    relationList: Array,
    refreshMap: Object,
    stores: {
      type: Object,
      default: () => {
        return {}
      }
    },
    parameterValue: {
      type: Array,
      default: () => []
    },
    tabConfig: Object
  },
  data() {
    return {
      needResetQueryConfig: false,
      chartData: {},
      queryColumns: [],
      toggleSearchStatus: false,
      needToggleSearchStatus: false,
      dictOptions: {},
      linkageMap: {},
      dictOptionsFlg: 0,
      url: {
        getWidgetAndData: YchConstant.PREFIX_EFORM + '/report/reportEngine/getWidgetAndData'
      },
      labelCol: {
        span: 8
      },
      wrapperCol: {
        span: 16
      },
    }
  },
  methods: {
    $locale(params){
      return locleUtil.getLocale(params)
    },
    setPk(record, code) {
      this.$emit('setPk', {
        record: record,
        itemCode: this.widgetCode,
      })
    },
    reLoad(codeChanged) {
      if (codeChanged) {
        this.chartData = {}
        this.needResetQueryConfig = true
      }
      // 如果是饼图或环图，强制报表重新渲染
      if(this.chartData && (this.chartData.chartType === 'Pie' || this.chartData.chartType === 'Donut')){
        this.chartData = {}
      }
      if (!this.widgetCode) {
        return
      }
      const queryValue = this.getQuery()
      postAction(this.url.getWidgetAndData + '?widgetCode=' + this.widgetCode, queryValue).then((res) => {
        if (res.success) {

          //加载前事件
          if (res.result.beforeScript) {
            const _that = this
            const func = handleCreateFunc(res.result.beforeScript, this)
            const func_result = handleExecFunc(func, {chartData: res.result}, function(chartData){
              _that.loadDataCallback(chartData);
            })
            if(!func_result) return;
          }
          this.loadDataCallback(res.result);

        } else {
          this.$message.warning(res.message)
        }
      })
    },
    loadDataCallback(chartData){
      if(chartData.data.length === 0){
        this.$message.warning(this.$locale('m.eform.formDesign.label.mei-you-tong-ji-shu-ju'))
        return;
      }

      if (chartData.chartType === 'Line' && chartData.xAxis && !chartData.xAxis.tickCount) {
        chartData.xAxis.tickCount = chartData.data.length
      }
      this.chartData = chartData

      // 多语言
      if (this.chartData) {
        if (this.chartData.title && this.chartData.title.text) {
          this.chartData.title.text = this.$locale(this.chartData.title.text)
        }
        if (this.chartData.yField && this.chartData.yField.desc) {
          this.chartData.yField.desc = this.$locale(this.chartData.yField.desc)
        }
        if (this.chartData.yAxis && this.chartData.yAxis.title && this.chartData.yAxis.title.text) {
          this.chartData.yAxis.title.text = this.$locale(this.chartData.yAxis.title.text)
        }
      }

      this.initQuery()

      // 如果没有数据，阻止了后面的渲染，影响了通过代码去赋值报表数据的场景，可以注释掉、或者放到渲染后面
      if(chartData.data.length === 0){
        this.$message.warning(this.$locale('m.eform.formDesign.label.mei-you-tong-ji-shu-ju'))
      }
    },
    initQuery() {
      if (!this.needResetQueryConfig) {
        return
      }
      this.needResetQueryConfig = false
      //查询条件
      this.queryColumns = this.chartData.queryShow || []

      const that = this
      this.queryColumns.forEach(query => {
        query.queryFormatJson = query.queryFormat ? JSON.parse(query.queryFormat) : {}

        if (query.queryFormatJson.dictOption && query.queryFormatJson.dictOption.dictCode) {
          that.dictOptions[query.queryFormatJson.dictOption.dictCode] = []
        }
      })
      this.needToggleSearchStatus = this.queryColumns.filter(vo => vo.queryIsShow === 'N').length > 0

      this.initDictConfig()
    },
    initDictConfig() {
      let dictCodes = Object.keys(this.dictOptions).join(',')
      if (dictCodes && dictCodes.length > 0) {
        initDictOptionMap(dictCodes).then((res) => {
          if (res.success) {
            Object.keys(this.dictOptions).forEach(key => {
              this.$set(this.dictOptions, key, res.result[key])
            })
            //触发查询框重新加载
            this.dictOptionsFlg = this.dictOptionsFlg + 1
          }
        })
      }
    },
    changeQueryField(query, value) {
      if (query.showType && query.colCode) {
        this.linkageMap = {...this.linkageMap}
        this.linkageMap[query.colCode] = value;
      }
    },
    getQuery() {
      const queryValue = []
      this.queryColumns.forEach(query => {
        //时间范围查询
        if (query.queryDefaultValue && query.queryDefaultValue.startsWith('[') && query.queryDefaultValue.endsWith(']')) {
          const queryDefaultValueJson = JSON.parse(query.queryDefaultValue)
          if (queryDefaultValueJson.length === 2) {
            const item_start = {
              colCode: query.colCode,
              queryValue: queryDefaultValueJson[0]
            }
            const item_end = {
              colCode: query.colCode + '-end',
              queryValue: queryDefaultValueJson[1]
            }
            queryValue.push(item_start)
            queryValue.push(item_end)
          }
        } else if (query.queryDefaultValue) {
          const item = {
            colCode: query.colCode,
            queryValue: query.queryDefaultValue
          }
          queryValue.push(item)
        }
      })

      return {
        queryValue: queryValue,
        fks: this.fks || [],
        parameterValue: this.parameterValue
      }
    },
    //查询
    searchQuery() {
      this.reLoad(false)
    },
    //重置
    searchReset() {
      this.queryColumns.forEach(vo => vo.queryDefaultValue = undefined)
      this.linkageMap = {}
      this.reLoad(false)
    },
    //展开
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    initRelation() {
      this.fks = RelationUtil.getChangedRelation({
        relationList: this.relationList,
        fks: this.fks,
        itemCode: this.widgetCode,
      })
    },
  },
  created() {
    // 把当前对象放入stores，方便其他对象使用
    if (!this.stores.$vm) {
      this.stores.$vm = {}
    }
    this.stores.$vm[this.widgetCode] = this
  },
  watch: {
    widgetCode: {
      handler() {
        this.initRelation()
        this.reLoad(true)
      },
      immediate: true
    },
    relationList: {
      handler() {
        const _fks = this.fks
        this.initRelation()
        if (_fks !== this.fks) {
          this.reLoad(false)
        }
      }
    }
  }
}
</script>
