<template>
  <div v-if="selectedOrganize">
    <div class="gva-btn-list" style="margin-bottom: 15px;">
      <div class="text-black cursor-pointer text-lg leading-5" @click="totalCollapse">
        <div v-if="isCollapse" class="gvaIcon gvaIcon-arrow-double-right" />
        <div v-else class="gvaIcon gvaIcon-arrow-double-left" />
      </div>
      <el-text size="large" tag="b">用户管理，当前选中：{{ selectedOrganize.name }}（共{{ total }}人）</el-text>
    </div>
    <div class="gva-btn-list">
      <el-button type="primary" icon="plus" @click="addUser">新增用户</el-button>
    </div>
    <el-table :data="tableData" row-key="ID">
      <el-table-column align="left" label="账户" min-width="120" prop="userName" />
      <el-table-column align="left" label="姓名" min-width="120" prop="nickName" />
      <el-table-column align="left" label="部门" min-width="200">
        <template #default="scope">
          <el-cascader v-model="scope.row.organizeId" :options="props.organizeOptions" :show-all-levels="false"
            :props="{ multiple: false, checkStrictly: true, label: 'name', value: 'ID', disabled: 'disabled', emitPath: false }"
            :clearable="false" @visible-change="(flag) => { changeOrganize(flag, scope.row) }" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="角色" min-width="200">
        <template #default="scope">
          <el-cascader v-model="scope.row.authorityIds" :options="authOptions" :show-all-levels="false" collapse-tags
            :props="{ multiple: true, checkStrictly: true, label: 'authorityName', value: 'authorityId', disabled: 'disabled', emitPath: false }"
            :clearable="false" @visible-change="(flag) => { changeAuthority(scope.row, flag, 0) }"
            @remove-tag="(removeAuth) => { changeAuthority(scope.row, false, removeAuth) }" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="手机号" min-width="120" prop="phone" />
      <el-table-column align="left" label="邮箱" min-width="220" prop="email" />
      <el-table-column align="left" label="启用" min-width="80">
        <template #default="scope">
          <el-switch v-model="scope.row.enable" inline-prompt :active-value="1" :inactive-value="2"
            @change="() => { switchEnable(scope.row) }" />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" link icon="edit" @click="openEdit(scope.row)" />
          <el-button type="primary" link icon="Tools" @click="resetPasswordFunc(scope.row)" />
          <el-button type="danger" link icon="delete" @click="deleteUserFunc(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <div class="gva-pagination">
      <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @current-change="handleChangePage"
        @size-change="handleChangePageSize" />
    </div>
  </div>
  <div v-else>
    <el-text size="large" tag="b">请选择部门</el-text>
  </div>
  <UserEdit ref="elUserEditRef" :authOptions="authOptions" :organizeOptions="props.organizeOptions"
    @on-save="handleSaveUser" />
</template>

<script setup>

import {
  getUserList,
  setUserAuthorities,
  setUserInfo,
  deleteUser,
  resetPassword
} from '@/api/user'
import { getAuthorityList } from '@/api/authority'
import { nextTick, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { equalArr } from '@/utils/arr'
import UserEdit from '@/view/organize/components/userEdit.vue'

defineOptions({
  name: 'User',
})

const props = defineProps({
  organizeOptions: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['collapse'])

const isCollapse = ref(false)
const totalCollapse = () => {
  isCollapse.value = !isCollapse.value
  emit('collapse', isCollapse.value)
}

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const selectedOrganize = ref(null)
// 分页
const handleChangePageSize = (val) => {
  pageSize.value = val
  getTableData()
}
const handleChangePage = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getUserList({ page: page.value, pageSize: pageSize.value, organizeId: selectedOrganize.value.ID })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

// 初始化相关
const authOptions = ref([])
const setAuthorityOptions = (AuthorityData, optionsData) => {
  AuthorityData &&
    AuthorityData.forEach(item => {
      if (item.children && item.children.length) {
        const option = {
          authorityId: item.authorityId,
          authorityName: item.authorityName,
          children: []
        }
        setAuthorityOptions(item.children, option.children)
        optionsData.push(option)
      } else {
        const option = {
          authorityId: item.authorityId,
          authorityName: item.authorityName
        }
        optionsData.push(option)
      }
    })
}
const setOptions = (authData) => {
  authOptions.value = []
  setAuthorityOptions(authData, authOptions.value)
}
const initPage = async () => {
  const res = await getAuthorityList({ page: 1, pageSize: 999 })
  setOptions(res.data.list)
}
initPage()

watch(() => tableData.value, () => {
  setAuthorityIds()
})

const openList = async (row) => {
  selectedOrganize.value = row
  getTableData()
}

const resetPasswordFunc = (row) => {
  ElMessageBox.confirm(
    '是否将此用户密码重置为123456?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const res = await resetPassword({
      ID: row.ID,
    })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.msg,
      })
    } else {
      ElMessage({
        type: 'error',
        message: res.msg,
      })
    }
  })
}
const setAuthorityIds = () => {
  tableData.value && tableData.value.forEach((user) => {
    user.authorityIds = user.authorities && user.authorities.map(i => {
      return i.authorityId
    })
  })
}

const deleteUserFunc = async (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteUser({ id: row.ID })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      await getTableData()
    }
  })
}

const elUserEditRef = ref(null)
const addUser = () => {
  elUserEditRef.value.openEdit({ organizeId: selectedOrganize.value.ID })
}

const openEdit = (user) => {
  elUserEditRef.value.openEdit(user)
}

const handleSaveUser = () => {
  getTableData()
}

const tempAuth = {}
const changeAuthority = async (row, flag, removeAuth) => {
  if (flag) {
    if (!removeAuth) {
      tempAuth[row.ID] = [...row.authorityIds]
    }
    return
  }

  if (equalArr(tempAuth[row.ID], row.authorityIds)) {
    return
  }
  await nextTick()
  const res = await setUserAuthorities({
    ID: row.ID,
    authorityIds: row.authorityIds
  })
  if (res.code === 0) {
    ElMessage({ type: 'success', message: '角色设置成功' })
  } else {
    if (!removeAuth) {
      row.authorityIds = [...tempAuth[row.ID]]
      delete tempAuth[row.ID]
    } else {
      row.authorityIds = [removeAuth, ...row.authorityIds]
    }
  }
}

let oldOrganizeId = -1
const changeOrganize = async (flag, row) => {
  if (flag) {
    // 展开时，临时存储信息
    oldOrganizeId = row.organizeId
    return
  }

  // 关闭时，判断是否有变化
  if (oldOrganizeId === row.organizeId) {
    // 无变化
    return
  }
  const res = await setUserInfo(row)
  if (res.code === 0) {
    ElMessage({ type: 'success', message: '部门设置成功' })
    getTableData()
  } else {
    row.organizeId = oldOrganizeId
  }
}

const switchEnable = async (row) => {
  await nextTick()
  const req = {
    ...row
  }
  const res = await setUserInfo(req)
  if (res.code === 0) {
    ElMessage({ type: 'success', message: `${req.enable === 2 ? '禁用' : '启用'}成功` })
    await getTableData()
    userInfo.value.headerImg = ''
    userInfo.value.authorityIds = []
  }
}

defineExpose({ openList })

</script>
