<template>
  <el-dialog
    title="机构-位置点权限设置"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="2%"
    width="48%"
    @closed="close"
  >

    <vxe-virtual-tree
      ref="locationTree"
      row-key
      show-overflow
      show-header-overflow
      max-height="450px"
      resizable
      border
      highlight-hover-row
      class="vxe-table-element"
      sync-resize
      auto-resize
      :loading="loading"
      :toolbar="locationToolbar"
      :columns="locationColumns"
      :checkbox-config="{ checkStrictly: !checkStrictly, checkField: 'checked', halfField: 'indeterminate'}"
      :data="locationTrees"
      @checkbox-all="({selection}) => { locationAuths = selection}"
      @checkbox-change="({selection}) => { locationAuths = selection }"
    >
      <template v-slot:locationStatus="{ row }">
        <el-switch :value="locationAuthStatus(row.id)" active-color="#13ce66" :active-value="true" :inactive-value="false" @change="(status) => assignOneLocation(status, row)" />
      </template>

      <template v-slot:location_buttons>
        <el-button type="primary" @click="assignLocation()">授权</el-button>
        <el-button type="danger" @click="cancelLocationAssign()">取消授权</el-button>
        <el-button @click="toggleLocations">展开/折叠</el-button>
      </template>
    </vxe-virtual-tree>

    <footer class="footer">
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="close">关闭</el-button>
    </footer>
  </el-dialog>
</template>

<script>

import { getCurrTenantTreeData as getLocationTreeData } from 'ecip-web/api/vue/mapping/baseTenantSectionApi'
import { getTreeData as getOrgTreeData } from 'ecip-web/api/vue/org/saasOrgApi'
import { filterNode } from 'ecip-web/utils/tableUtil'

export default {
  name: 'OrgLocationAuthVue',
  props: {
    showModal: {
      type: Boolean,
      default: false,
      required: false
    },
    orgLocations: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      orgTreeLoading: false,
      expand: false,
      checkStrictly: true,
      filterText: '',
      emptyText: '暂无数据',
      orgTrees: [], //  机构树
      locationTrees: [], //  设备位置点树
      locationAuths: [], //  已选机构权限
      locationColumns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: '名称', field: 'name', minWidth: 200, treeNode: true, showOverflow: true },
        { title: '编号', field: 'code', minWidth: 200, showOverflow: true },
        // { title: '启用状态', field: 'status', formatter: ['dict', 'enableState'] },
        { title: '授权状态', minWidth: 130, slots: { default: 'locationStatus' }}
      ],
      locationToolbar: {
        id: 'member-orgLocationAuth-toolbar',
        // custom: true,
        slots: {
          buttons: 'location_buttons'
        },
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      selectedOrg: null,
      copyOrgLocations: []
    }
  },
  watch: {
    showModal: {
      handler(val) {
        this.visible = val === true
      },
      immediate: true
    },
    orgTreeLoading(val) {
      this.emptyText = val ? '数据正在加载中...' : '暂无数据'
    },
    filterText(val) {
      this.$refs.orgTree.filter(val)
    },
    orgLocations(val) {
      this.copyOrgLocations = JSON.parse(JSON.stringify(val))
    }
  },
  methods: {
    init(item) {
      this.selectedOrg = null
      this.expand = false
      this.locationAuths = []
      this.getLocationTreeData(item)
    },
    async getLocationTreeData(item) {
      this.locationTrees = []
      try {
        this.loading = true
        const { data } = await getLocationTreeData({ tenantId: item.tenantId })
        this.locationTrees = data
      } finally {
        this.loading = false
      }
    },
    async getOrgTreeData(item) {
      this.orgTrees = []

      try {
        this.orgTreeLoading = true
        const { data } = await getOrgTreeData({}, { tenantId: item.tenantId })
        this.orgTrees = data
      } finally {
        this.orgTreeLoading = false
      }
    },

    locationAuthStatus(cellValue) {
      const i = this.copyOrgLocations.findIndex((item) => item.id === cellValue)
      return i !== -1
    },
    assignLocation() {
      const array = this.$refs.locationTree.getCheckboxRecords()
      if (array.length) {
        array.forEach((item) => {
          const i = this.copyOrgLocations.findIndex(child => child.id === item.id)
          if (i === -1) {
            this.copyOrgLocations.push(item)
          }
        })
      } else {
        this.$message.warning('请至少选择一项')
      }
    },
    cancelLocationAssign() {
      const array = this.$refs.locationTree.getCheckboxRecords()
      if (array.length) {
        array.forEach((item) => {
          const i = this.copyOrgLocations.findIndex(child => child.id === item.id)
          if (i !== -1) {
            this.copyOrgLocations.splice(i, 1)
          }
        })
      } else {
        this.$message.warning('请至少选择一项')
      }
    },
    async assignOneLocation(status, item) {
      if (status) {
        this.copyOrgLocations.push(item)
      } else {
        for (let i = 0; i < this.orgLocations.length; i++) {
          if (this.copyOrgLocations[i].id === item.id) {
            this.copyOrgLocations.splice(i, 1)
            break
          }
        }
      }
    },
    toggleLocations() {
      this.expand = !this.expand
      this.$refs.locationTree.setAllTreeExpansion(this.expand)
    },
    filterNode(value, data, node) {
      return filterNode(value, data, node, 'name')
    },
    nodeClick(node, Node) {
      this.$refs.locationTree.clearCheckboxRow()
      this.selectedOrg = node
    },
    close() {
      this.visible = false
      this.$emit('close', false)
    },
    submit() {
      this.$emit('change', JSON.parse(JSON.stringify(this.copyOrgLocations)))
      this.visible = false
      this.$emit('close', false)
    }
  }

}
</script>

<style  lang="scss" scoped>
.footer{
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
</style>
