<template>
  <div class="sql-grid" style="width:100%;height:100%;display:flex;flex-direction: column;">
    <ActionPane
        :actions="actions"
        :func-map="funcMap"
        class="action"
        ref="actionPane"
        v-show="showActionPane && this.gridGuid && this.actions.length > 0"
    ></ActionPane>
    <FilterPane
        :columns="columns"
        :filters="filters"
        @on-filter="filterTable"
        class="filter"
        v-if="showFilterPane && this.gridGuid"
        v-show="isLoaded"
    ></FilterPane>
    <div style="overflow-y: scroll">
      <TreeTable
          ref="treeTable"
          :is-loading="isLoading"
          :items="data"
          :columns="columns"
          @on-selection-change='selectionClick'
      />
    </div>
  </div>
</template>
<script>
  import DataApi from '../../data/grid-sql'
  // import ColumnUtils from './column-utils'
  import FilterPane from '../../components/filter-pane'
  import ActionPane from './../grid/action-pane'
  import TreeTable from '../../tree-table/index'
  import ImageViewer from '../../libs/image-viewer'
  import GridInfoFuncs from '../../extern/grid-info-funcs'
  import '../../v-table/themes-base/index.css'
  import TableSetting from '../../components/table-setting'
  export default {
    name: 'Grid',
    data() {
      return {
        // 重置按钮权
        a: [{name: '1'},{name: '2'}],
        columns: [],
        rowBtnLimit: [],
        configVersion: 0,
        pageIndex: 1,
        pageSize: 10000,
        total: 0,
        data: undefined,
        actions: [],
        filters: [],
        whereItems: [],
        isLoading: false,
        isLoaded: false,
        selectItems: [],
        selectItem: undefined,
        // 是否初始化完成
        isInitialized: false,
        imageViewer: null,
        // 计算总页数
        calcTotal: true,
        // 显示额外信息
        infoFunc: false,
        infoFuncHtml: '',
        cellEditFunc: '',
        // 明细是否可见
        detailVisible: true,
        // 分页保存的数据
        pagerSelectedItems: [],
        // 是否显示所有
        isSelectingAll: false,
      }
    },
    provide() {
      return {
        isHavePermision: this.isHavePermision
      }
    },
    // mixins: [ColumnUtils],
    props: {
      /*是否显示Action面板*/
      showActionPane: {
        type: Boolean,
        default: true,
      },
      /*是否自动初始化,在某些情况下，不希望自动初始化*/
      autoInit: {
        type: Boolean,
        default: true,
      },
      /**/
      funcMap: {
        type: Object,
      },
      /*是否显示Action面板*/
      showActionPane: {
        type: Boolean,
        default: true,
      },

      /* 是否显示FilterPane */
      showFilterPane: {
        type: Boolean,
        default: true,
      },
      /*GridGuid*/
      gridGuid: {
        type: String,
      },
      /* 主网格GUID，主子网格需要 */
      mainGuid: {
        type: [String, Number],
      },

      /* guid field */
      guidField: {
        type: String,
        default: 'guid',
      },

      /* 请求的不同的service */
      queryUrl: {
        type: String,
        default: '/data-service',
      },

      gridType: {
        type: String,
      },

      /**
       * 行数据，在一些弹出应用中，可以通过这个传递主网格中显示的数据
       */
      rowData: {
        type: Object,
      },

    },
    watch: {
      mainGuid: {
        handler(newVal) {
          this.refresh()
        },

        immediate: true,
      },
      data(newVal) {
        if (this.canPagerSelect) {
          console.log(this.pagerSelectedItems)
          // 选中设置项
          newVal.forEach((item) => {
            let fIndex = this.pagerSelectedItems.indexOf(item.guid)
            if (~fIndex) {
              item['_checked'] = true
            }
          })
        }
      },
    },
    components: {
      TreeTable,
      FilterPane,
      ActionPane,
    },
    computed: {},
    methods: {
      selectionClick(rowData, column) {
        console.log(rowData, 'rowData')
        this.selectItems = [].concat(rowData)
        if(rowData.length) {
          this.selectItem = rowData[0]
        } else {
          this.selectItem = undefined
        }
      },
      getRowData() {
        return this.selectItem
      },
      /*确认是单选*/
      ensureSingleSelect() {
        if (this.selectItems.length == 0) {
          this.$Modal.warning({
            title: this.$t('it.grid.warning'),
            content: this.$t('it.grid.selectone'),
          })
          return false
        } else if (this.selectItems.length > 1) {
          this.$Modal.warning({
            title: this.$t('it.grid.warning'),
            content: this.$t('it.grid.onlyone'),
          })

          return false
        }
        return true
      },
      /*确认是多选*/
      ensureMultiSelect() {
        if (this.selectItems.length == 0) {
          this.$Modal.warning({
            title: this.$t('it.grid.warning'),
            content: this.$t('it.grid.select'),
          })

          return false
        }

        return true
      },
      /*刷新数据*/
      refresh() {
        this.pageIndex = 1
        let model = this.getQueryModel(true)
        this.isLoading = true
        DataApi.queryData(this.queryUrl, model, this.gridType)
          .then((res) => {
            res.data.forEach(val => {
              val.expanded =  false
              val.isChecked = false
              val.isShow = false
            })
            this.data = this.setTreeData(res.data)
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })

        //去掉过滤中的选中项
        this.selectItems = []
        this.selectItem = undefined
      },
      setTreeData(data) {
        let cloneData = JSON.parse(JSON.stringify(data)) // 对源数据深度克隆
        let tree = [];
        let temp = {};
        cloneData.forEach((d) => {
          let item = Object.assign({}, d);
          temp[item.guid] = item;
          if (item.parent_guid) {
            let parent = temp[item.parent_guid];
            if (parent) {
              if (!parent["children"]) {
                parent["children"] = [];
              }
              parent["children"].push(item);
            } else {
              tree.push(item);
            }
          } else {
            tree.push(item);
          }
        });

        return tree;
      },
      // 处理tree-table 返回数据
      translateDataToTree(data) {
        //没有父节点的数据
        let parents = data.filter(value =>  value.parent_guid == 0 || value.parent_guid == null)

        //有父节点的数据
        let children = data.filter(value => value.parent_guid !== 0 && value.parent_guid != null)

        //定义转换方法的具体实现
        let translator = (parents, children) => {
          //遍历父节点数据
          parents.forEach((parent) => {
            //遍历子节点数据
            children.forEach((current, index) => {
              //此时找到父节点对应的一个子节点
              if (current.parent_guid == parent.guid) {
                //对子节点数据进行深复制，这里只支持部分类型的数据深复制，对深复制不了解的童靴可以先去了解下深复制
                let temp = JSON.parse(JSON.stringify(children))
                //让当前子节点从temp中移除，temp作为新的子节点数据，这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
                temp.splice(index, 1)
                //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
                translator([current], temp)
                //把找到子节点放入父节点的children属性中
                typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
              }
            })
          })
        }
        //调用转换方法
        translator(parents, children)
        //返回最终的结果
        return parents
      },
      setupActions(conf) {
        let actions = []
        let confActions = conf.actions.filter((item) => {
          if (item.permisions) {
            return this.propActions.includes(item.permisions)
          } else {
            return true
          }
        })
        for (let a of confActions) {
          let act = {
            caption: a.caption,
            action: a.func_guid,
            isDblClickFunc: a.is_dbl_click_func,
          }

          actions.push(act)
        }
        this.actions = actions
      },
      setupFilters(conf) {
        let filters = []
        for (let f of conf.filters) {
          let filter = {
            editor: f.editor,
            type: f.type,
            label: f.caption,
            code: f.field,
            op: f.operator,
            width: f.width,
            ds: f.ds,
            defValue: f.def_value,
            can_clear: f.can_clear,
          }
          filters.push(filter)
        }

        this.filters = filters
      },
      /**
       * 加载当前页，不跳转，保留当前页状态
       */
      reloadCurrPage() {
        let model = this.getQueryModel(true)
        this.isLoading = true
        this.selectItems = []
        this.selectItem = undefined
        return new Promise((resolve, reject) => {
          DataApi.queryData(this.queryUrl, model, this.gridType)
            .then((res) => {
              res.data.forEach(val => {
                val.expanded =  false
                val.isChecked = false
                val.isShow = false
              })
              this.data = this.setTreeData(res.data)
              this.$refs.treeTable.dataList = []
              this.isLoading = false
              resolve()
            })
            .catch(() => {
              this.isLoading = false
              reject()
            })
        })
      },
      /*点击过滤*/
      filterTable(fa) {
        this.whereItems = this.wrapperWhereItems(fa)

        this.refresh()
      },
      wrapperWhereItems(fa) {
        let where = [].concat(fa)

        return where
      },
      getTableData() {
        this.isLoading = true
        DataApi.queryData(
          this.queryUrl,
          this.getQueryModel(),
          this.gridType
        )
          .then((res) => {
            this.data = this.translateDataToTree(res.data)
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      },

      /**
       * 构造查询模型
       * @param withTotal 是否获取总页数
       */
      getQueryModel(withTotal) {
        return {
          guid: this.gridGuid,
          with_total: withTotal,
          _where: this._getWhere(),
          // 这个数据在单文件中显示
          default_where: Object.assign(
            {},
            this.defaultWhere,
            this.$$defaultWhere
          ),
          row_data: this.rowData,
          permissionType: this.$roleName,
        }
      },

      _getWhere() {
        if (this.mainGuid) {
          return JSON.stringify(
            this.whereItems.concat({
              code: '__main_guid__',
              op: 'equal',
              value: this.mainGuid,
            })
          )
        } else {
          return JSON.stringify(this.whereItems)
        }
      },

      init() {
        if (!this.gridGuid) {
          return
        }

        if (this.isInitialized) {
          return
        }

        this.isInitialized = true
        this.isLoading = true
        DataApi.queryConfig(this.queryUrl, this.gridGuid, this.gridType)
          .then((config) => {
            this.columns = config.columns.map(val => {
              return {
                title: val.caption,
                code: val.code,
                width: val.width
              }
            })
            this.columns.unshift({
              type: 'selection'
            })
            this.isLoaded = true
            this.configVersion = config.version
            this.setupActions(config)
            this.setupFilters(config)
            this.setInfoFunc(config.info_func)
            this.cellEditFunc = config.cell_edit_func || ''

            if (!this.showFilterPane) {
              // 没有显示filterPane，不能直接查询数据
              this.isLoading = false
            }
            if (this.defaultPagerSelectedItems) {
              this.pagerSelectedItems = [].concat(
                this.defaultPagerSelectedItems
              )
            }
          })
          .catch(() => {
            this.isLoading = false
          })
      }
    },
    mounted() {
      this.$on('refresh-current-page', this.reloadCurrPage)
    },
    beforeDestroy() {
      this.$off('refresh-current-page', this.reloadCurrPage)
    },
    created() {
      if (this.autoInit) {
        this.init()
      }
    }
  }
</script>
<style scoped lang="less">
  .sql-grid {
    .action {
      padding: 8px 8px 8px 20px;
    }

    .filter {
      padding: 8px 8px 8px 20px;
    }

    .grid {
      flex: 1;
      padding-bottom: -8px;
    }

    .pager {
      padding: 8px 8px 8px 10px;
      display: flex;

      .tool-buttons {
        .info-func {
          margin-right: 20px;
        }
      }
    }

    .grid-image-big {
      img {
        margin: 4px;
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }
    }

    .grid-image-small {
      img {
        margin: 2px;
        width: 36px;
        height: 36px;
        border-radius: 4px;
      }
    }

    .titleEdit {
      background: url(../../assets/edit.png) right no-repeat;
      background-size: 12px;
      background-position: 92% 44%;
    }
  }
</style>
