<template>
  <el-dialog
    :title="`${userItem.realName}-位置点权限设置`"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="2%"
    width="48%"
    @closed="close"
  >
    <el-form v-if="userItem && userItem.tenantId">
      <el-form-item :label="$t('ec.user.tenant')" style="padding-left: 12px;">
        <ec-user-tenant ref="ecUserTenant" v-model="userItem.tenantId" @getData="getUserTenantData" />
      </el-form-item>
    </el-form>

    <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.id)" />
      </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>

  </el-dialog>
</template>

<script>

/**
 * 租户机构管理 页面也使用该组件
 * */

import { getCurrTenantTreeData as getLocationTreeData, userlocations, setUserLocations, delUserLocations } 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: 'UserLocation',
  props: {
    showModal: {
      type: Boolean,
      default: false,
      required: false
    },
    orgLocations: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      userItem: {},
      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: 100, slots: { default: 'locationStatus' }}
      ],
      locationToolbar: {
        id: 'member-orgLocationAuth-toolbar',
        // custom: true,
        slots: {
          buttons: 'location_buttons'
        },
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      selectedOrg: null,
      userLocationList: []
    }
  },
  watch: {
    showModal: {
      handler(val) {
        this.visible = val === true
      },
      immediate: true
    },
    orgTreeLoading(val) {
      this.emptyText = val ? '数据正在加载中...' : '暂无数据'
    },
    filterText(val) {
      this.$refs.orgTree.filter(val)
    }
  },
  methods: {
    init(user) {
      this.visible = true
      this.selectedOrg = null
      this.expand = false
      this.locationAuths = []
      this.userItem = user
      this.getUserLocation()
      this.getLocationTreeData()
    },
    getUserTenantData(userTenantId) {
      this.getLocationTreeData(userTenantId)
    },
    async getUserLocation() {
      const { data } = await userlocations({ userId: this.userItem.id })
      this.userLocationList = data
    },
    async getLocationTreeData(tenantId) {
      this.locationTrees = []
      try {
        this.loading = true
        const { data } = await getLocationTreeData({ tenantId: tenantId || this.userItem.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) {
      if (!this.userLocationList) {
        return false
      }
      return this.userLocationList.includes(cellValue)
    },
    assignLocation() {
      this.$confirm(`是否赋予所选位置点权限?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const locationIds = this.$refs.locationTree.getCheckboxRecords().map(item => item.id)
        await setUserLocations(locationIds, { userId: this.userItem.id })
        await this.getUserLocation()
        this.$notify.success('授权成功')
      })
    },
    cancelLocationAssign() {
      this.$confirm(`是否取消所选位置点权限?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const locationIds = this.$refs.locationTree.getCheckboxRecords().map(item => item.id)
        await delUserLocations(locationIds, { userId: this.userItem.id })
        await this.getUserLocation()
        this.$notify.success('成功取消授权')
      })
    },
    async assignOneLocation(status, rowId) {
      const locationIds = [rowId]
      let message
      if (status) {
        await setUserLocations(locationIds, { userId: this.userItem.id })
        message = '授权成功'
      } else {
        await delUserLocations(locationIds, { userId: this.userItem.id })
        message = '取消授权成功'
      }
      await this.getUserLocation()
      this.$notify.success(message)
    },
    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.userItem = ''
      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>
