<script>
import cloneDeep from 'lodash.clonedeep'
import storeMixin from '@/common/store-mixin'
import SdSelect from '@/common/components/sd-select.vue'
import SdDataTable from '@/common/components/sd-data-table.vue'
import SdDataTableEx from '@/common/components/sd-data-table-ex.vue'
import components from './_import-components/sd-data-table-sys-import'

/**
 * 实现了管理员分级管理的SdDataTableEx
 * @displayName SdDataTableSys 高级数据表格(含分级管理)
 * @since 8.1.0.23
 */

export default {
  name: 'SdDataTableSys',
  components,
  mixins: [storeMixin],
  props: {
    filterExpressions: {
      type: Array,
      default: () => [],
    },
    ex: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      hierarchy: [],
    }
  },
  computed: {
    hierarchyOptions() {
      return (this.userInfo.belongedOrgIds || []).map((item) => ({
        id: item.id,
        name: item.text,
        title: item.text,
      }))
    },
    computedFilterExpressions() {
      const computedFilterExpressions = cloneDeep(this.filterExpressions)
      // 用户有分级机构，默认需按分级过滤数据
      if (this.hierarchy[0]) {
        computedFilterExpressions.push({
          dataType: 'long',
          name: 'belongedOrgId',
          op: 'eq',
          longValue: Number(this.hierarchy[0].id),
        })
      }
      return computedFilterExpressions
    },
  },
  watch: {
    hierarchy(val) {
      this.$emit('hierarchyChange', val?.[0])
    },
  },
  created() {
    if (this.hierarchyOptions[0]) {
      this.hierarchy = [{ ...this.hierarchyOptions[0] }]
    }
  },
  mounted() {
    // 转发SdDataTableEx中的方法
    for (const key in this.$refs.dataTable) {
      if (!(key in this) && typeof this.$refs.dataTable[key] === 'function') {
        this[key] = this.$refs.dataTable[key]
      }
    }
  },
  methods: {
    /**
     * 获取当前选择的分级信息
     */
    getHierarchy() {
      if (this.hierarchy[0]) {
        return { ...this.hierarchy[0] }
      }
      return null
    },
  },
  render(createElement) {
    // 当前用户有可管理的分级机构，则显示
    const headerPrefix =
      this.hierarchyOptions.length > 0 ? (
        <div>
          <label>可管理机构：</label>
          <SdSelect
            class={this.$style.hierarchySelector}
            {...{
              attrs: {
                value: this.hierarchy,
                options: this.hierarchyOptions,
              },
              on: {
                change: (val) => (this.hierarchy = val),
              },
            }}
          />
        </div>
      ) : (
        ''
      )
    return createElement(this.ex ? SdDataTableEx : SdDataTable, {
      ...{
        ref: 'dataTable',
        attrs: { ...this.$attrs, filterExpressions: this.computedFilterExpressions },
        on: {
          ...this.$listeners,
          formBtnClick: (evt, btn, { form, recordId }) => {
            if (btn.buttonId === 'save') {
              // 保存时，如果当前是新建 且 有分级机构，则设置分级机构的值
              if (!recordId && this.hierarchy[0]) {
                form.setFieldValue('belongedOrgId', this.hierarchy[0].id)
              }
            }
            this.$emit('formBtnClick', evt, btn, { form, recordId })
          },
        },
        scopedSlots: {
          ...this.$scopedSlots,
          headerPrefix: () => headerPrefix,
        },
      },
    })
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.hierarchy-selector {
  max-width: 150px;
}
</style>
