<template>
  <div class="page-management-organization">
    <SearchTable
      title="组织管理"
      ref="searchTableRef"
      v-model="formData"
      @reset="handleClear"
      @submit="handleSubmit"
    >
      <template #slot-form>
        <el-col :span="isTablet ? 12 : 6" :style="{ marginBottom: isTablet ? '16px' : '0px' }">
          <el-form-item label="所属组织" label-width="82px">
            <el-input v-model="formData.parentName" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="isTablet ? 12 : 6" :style="{ marginBottom: isTablet ? '16px' : '0px' }">
          <el-form-item label="子组织名称" label-width="82px">
            <el-input v-model="formData.organName" placeholder="请输入子组织名称" clearable />
          </el-form-item>
        </el-col>
      </template>
      <template #slot-action-bar>
        <el-button :disabled="isShowBack" type="primary" icon="el-icon-top" @click="handleBack">返回上级组织</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddOrganization">新增子组织</el-button>
      </template>
      <template #slot-table>
        <el-table-column label="所属组织" prop="parentOrganName" min-width="120px" />
        <el-table-column label="子组织名称" prop="organName" min-width="160px" />
        <el-table-column label="子组织类型" min-width="140px">
          <template slot-scope="scope">
            {{ ['', '车厂', '经销商', '车企子组织'][scope.row.bizType] }}
          </template>
        </el-table-column>
        <el-table-column label="管理员姓名" prop="organAdminName" min-width="120px" />
        <el-table-column label="管理员账号" prop="organAdminAccount" min-width="140px" />
        <el-table-column label="管理员手机" prop="organAdminPhone" min-width="140px" />
        <el-table-column label="创建时间" prop="createTime" min-width="160px" />
        <el-table-column label="状态" prop="status" min-width="80px">
          <template slot-scope="scope">
            <div class="status-wrap">
              <i :class="scope.row.status == 0 ? 'red' : 'green'" class="status-point" />
              {{ ['未启用', '已启用'][scope.row.status] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120px">
          <template slot-scope="scope">
            <!-- <el-button type="text">禁用</el-button> -->
            <el-button type="text" @click="handleEditOrganization(scope.row)">编辑</el-button>
            <span class="separator" />
            <el-dropdown @command="command => handleDropDownCommand(command, scope.row)">
              <el-button type="text">
                更多<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown" class="ui-dropdown">
                <el-dropdown-item command="CHANGE_ADMIN">变更管理员</el-dropdown-item>
                <el-dropdown-item command="ACCOUNT_MANAGE">账户管理</el-dropdown-item>
                <el-dropdown-item command="EDIT_CHILD_ORG">编辑子组织</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </template>
    </SearchTable>
    <!-- 新增或更新管理员 -->
    <UpdateOrganization :visible.sync="updateOrgDialog.show" :type="updateOrgDialog.type" :data="updateOrgDialog.data" @refresh="handleRefresh" />
    <!--变更管理员弹框 start -->
    <ChangeAdmin :visible.sync="changeAdminDialog.show" :data="changeAdminDialog.data" from="organ" @refresh="handleRefresh" />
  </div>
</template>

<script>
import cache from '@/utils/cache'
import { queryOrganList } from '@/api/management'
import SearchTable from '@/components/SearchTable'
import UpdateOrganization from './components/UpdateOrganization'
import ChangeAdmin from '../dealer/components/ChangeAdmin'

// 组织下钻时保存的数据列表
const STORAGE_CODE = 'ORGAN_PARENT_LIST'

export default {
  name: 'OrganizationManage',
  components: { SearchTable, UpdateOrganization, ChangeAdmin },
  data() {
    return {
      formData: {
        ...this.getOrganFromRoute(),
        organName: ''
      },
      updateOrgDialog: {
        show: false,
        type: 'add',
        data: {}
      },
      changeAdminDialog: {
        show: false,
        data: {}
      },
      isTablet: window.OS.isTablet
    }
  },
  computed: {
    /**
     * 是否展示返回上一级的目录
     */
    isShowBack() {
      const { organId } = this.$route.query
      // 如果当前没有组织id，则清空缓存
      if (!organId) {
        cache.remove(STORAGE_CODE)
      }
      return !organId
    }
  },
  watch: {
    '$route'(to, from) {
      // 如果当前返回到第一级
      if (!to.query.organId) {
        this.formData = {
          ...this.getOrganFromRoute(),
          organName: ''
        }
      }
      // 刷新页面
      this.$refs.searchTableRef.handleSubmit()
    }
  },
  methods: {
    /**
     * 点击查询搜索的方法
     * @param formData 当前表单数据包括分页
     * @param callback 回调方法
     */
    async handleSubmit(formData, callback) {
      // 开始查询接口返回
      const { list, totalCount } = await queryOrganList(formData)
      // 回调渲染接口
      callback({ list, totalCount })
    },

    /**
     * 清空数据
     */
    handleClear() {
      this.formData.organName = ''
    },

    /**
     * 刷新数据
     */
    handleRefresh() {
      this.$refs.searchTableRef.handleSubmit()
    },

    /**
     * 新增组织管理
     */
    handleAddOrganization() {
      // 开始更新数据
      this.$set(this.updateOrgDialog, 'show', true)
      this.$set(this.updateOrgDialog, 'type', 'add')
      this.$set(this.updateOrgDialog, 'data', { bizType: 2 })
    },

    /**
     * 返回到上一级
     */
    handleBack() {
      // 获取缓存的数据
      const cacheData = cache.get(STORAGE_CODE, [])
      // 删除左后一条数据
      cacheData.splice(-1)
      // 先保存数据
      cache.set(
        STORAGE_CODE,
        cacheData
      )
      // 跳转页面
      this.toOrganRoute(cacheData[cacheData.length - 1])
    },

    /**
     * 编辑组织
     * @param row 当前行数据
     */
    handleEditOrganization(row) {
      // 开始更新数据
      this.$set(this.updateOrgDialog, 'show', true)
      this.$set(this.updateOrgDialog, 'type', 'edit')
      this.$set(this.updateOrgDialog, 'data', { ...row })
    },

    /**
     * 打开更换管理员弹框
     * @param row 当前行数据
     */
    handleOpenChangeAdminDialog(row) {
      this.changeAdminDialog = {
        show: true,
        data: row
      }
    },

    /**
     * 下拉触发命令
     * @param command 当前命令
     * @param row 当前行数据
     */
    handleDropDownCommand(command, row) {
      // 根据命令做操作
      switch (command) {
        case 'CHANGE_ADMIN':
          this.handleOpenChangeAdminDialog(row)
          break
        case 'ACCOUNT_MANAGE':
          this.$router.push({
            name: 'UserManagement',
            query: {
              organId: row.uuid,
              organName: row.organName
            }
          })
          break
        case 'EDIT_CHILD_ORG':
          // 先保存数据
          cache.set(
            STORAGE_CODE,
            [
              ...cache.get(STORAGE_CODE, []),
              {
                organId: row.uuid,
                organName: row.organName
              }
            ]
          )
          // 跳转页面
          this.toOrganRoute({
            organId: row.uuid,
            organName: row.organName
          })
          break
      }
    },

    /**
     * 获取组织管理信息
     */
    getOrganFromRoute() {
      // 从路由中获取组织id和组织名称
      let { organId, organName } = this.$route.query
      // 如果当前没有组织id，则从缓存中取
      if (!organId) {
        organId = this.$store.getters.organId
        organName = this.$store.getters.organName
      }
      return { parentId: organId, parentName: organName }
    },

    /**
     * 跳转到组织的路由中
     * @param query 当前需要携带在路由中的数据
     */
    toOrganRoute(query = {}) {
      // 组织id和组织名称
      const { organId, organName } = this.$store.getters
      // 构建表单数据
      this.formData = {
        ...this.formData,
        organName: '',
        parentId: query.organId || organId,
        parentName: query.organName || organName
      }
      // 跳转页面
      this.$router.replace({
        name: 'OrganizationManagement',
        query
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-management-organization {
  .status-wrap {
    align-items: center;
    display: flex;
    .status-point {
      border-radius: 3px;
      display: inline-block;
      width: 6px;
      height: 6px;
      margin-right: 8px;
      &.green {
        background-color: #25C343;
      }
      &.red {
        background-color: #FF4D4F;
      }
    }
  }
  .separator {
    background: #DCDFE6;
    display: inline-block;
    width: 1px;
    height: 14px;
    margin: 0 2px -2px;
  }
}
</style>
