<template>
  <div class="h-full flex flex-col roleStyle">
    <!-- 头部 -->
    <div class="bg-white flex justify-between team-header">
      <div class="flex items-center justify-between w-full">
        <div></div>
        <div>
          <el-button type="primary" @click="changeRole()">添加角色</el-button>
          <el-button type="primary">修改默认角色</el-button>
        </div>
      </div>
    </div>
    <!-- 内容 -->
    <div class="flex-1 flex">
      <div class="flex-1 p-5 overflow-auto">
        <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col">
          <div class="flex-1 p-3">
            <el-table :data="filterTableData" style="width: 100%;height: 100%;" v-bind:loading="allLoading.tableLoading">
              <el-table-column label="角色" prop="rolename" width="300" />
              <el-table-column label="描述" prop="roleDescribe" />
              <el-table-column align="right" width="386">
                <template #header>
                  <el-input v-model="searchRoleName" placeholder="请输入关键字搜索" />
                </template>
                <template #default="scope">
                  <el-button @click="changeRole(scope.row)">编辑角色</el-button>
                  <el-button type="primary" @click="distributionPermissions(scope.row)">分配权限</el-button>
                  <el-button>导出权限</el-button>
                  <el-button type="danger" @click="deteleRole(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 添加角色/编辑角色 -->
    <el-dialog v-model="allDialogVisible.roleDialogVisible" :title="roleTitle" width="600" :before-close="handleClose">
      <div>
        <el-form ref="roleFormRef" :model="roleFrom" label-width="auto">
          <el-form-item prop="name" label="角色名称" :rules="[
            {
              required: true,
              message: '请输入角色名称',
              trigger: 'blur',
            },
          ]">
            <el-input v-model="roleFrom.name" placeholder="请输入角色名称" clearable />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="roleFrom.description" placeholder="请输入描述" type="textarea" clearable />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="allDialogVisible.roleDialogVisible = false">取消</el-button>
          <el-button type="primary" v-bind:loading="allLoading.roleLoading" @click="addRole(roleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog v-model="allDialogVisible.permissionsDialogVisible" :title="`分配权限-${permissionsDataItem.rolename}`" width="800"
      :before-close="handleClose">
      <div class="permissionsData">
        <div v-for="(item, index) in permissionsData" :key="index" class="list">
          <div class="itemName" v-if="item.name.indexOf('详情') == -1">
            <el-checkbox size="large" v-model="item.checked" style="width: 16px; font-weight: bold;"
              @change="changeCheckBox(item, true)">{{ item.name }}</el-checkbox>
          </div>
          <div class="flex-1 flex item">
            <div v-for="(list, listIndex) in item.functionList" :key="listIndex" class="itemName">
              <el-checkbox size="large" v-model="list.checked" style="width: 16px;"
                @change="changeCheckBox(item, false)">{{ list.name }}</el-checkbox>
            </div>

            <div v-for="(list, listIndex) in item.children" :key="listIndex" class="itemName">
              <el-checkbox size="large" v-model="list.checked" style="width: 16px;"
                @change="changeCheckBox(item, false)">{{ list.name }}</el-checkbox>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-bind:loading="allLoading.permissionsLoading" @click="edtPermissions()">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, inject, computed } from 'vue';
import { post } from "@/utils/request";
import { GETROLELIST, DETELEROLE, EDITROLE, GETAUTORITY, SAVEPERM } from "./api.ts";
import { FormInstance, ElMessageBox } from 'element-plus'
import { useStore } from '@/store/index'
import { getFromValue, resetFromValue } from '@/utils/tools'

interface roleRuleForm {
  id: string
  name: string
  description: string
}

const { getUserInfoVal } = useStore()
const globalPopup = inject<GlobalPopup>('globalPopup')

const companyId = reactive(getUserInfoVal('companyId') || '')
const searchRoleName = ref('') // 搜索条件
const tableData: any = ref([]) // 表格数据
const permissionsData: any = ref([]) // 权限数据
const permissionsDataItem: any = ref({}) // 选中的权限数据
const roleTitle = ref('添加角色') // 弹窗标题
const roleFormRef = ref<FormInstance>() // 表单ref
const roleFrom = reactive<roleRuleForm>({ // 表单数据
  id: '',
  name: '',
  description: ''
})

const allDialogVisible = reactive({
  roleDialogVisible: false,
  permissionsDialogVisible: false
})

const allLoading = reactive({
  tableLoading: false,
  roleLoading: false,
  permissionsLoading: false
})

const filterTableData = computed(() =>
  tableData.value.filter(
    (data: any) =>
      !searchRoleName.value ||
      data.rolename.toLowerCase().includes(searchRoleName.value.toLowerCase())
  )
)

function edtPermissions() {
  allLoading.permissionsLoading = true
  let moduleList = JSON.stringify(permissionsData.value)
  let role = permissionsDataItem.value.id
  post(SAVEPERM, { role, moduleList }).then(res => {
    if (res.code != 'ok') {
      globalPopup?.showError(res.msg)
      return
    }
    globalPopup?.showSuccess('保存成功')
    allDialogVisible.permissionsDialogVisible = false
    allLoading.permissionsLoading = false
    getRoleList()
  }).catch(() => {
    allLoading.permissionsLoading = false
  })
}

function changeCheckBox(item: any, flag: boolean) {
  if (flag) {
    item.functionList.forEach((list: any) => {
      list.checked = item.checked
    })
    return
  }
  const { id } = item
  let mainMenuList = permissionsData.value;
  mainMenuList.forEach((m: any) => {
    if (m.id == id) {
      var hasChecked = false;
      m.functionList.forEach((c: any) => {
        if (c.checked) {
          hasChecked = true;
        }
      })
      if (hasChecked) {
        console.log('执行')
        m.checked = hasChecked;
      }
    }
  });
}

function distributionPermissions(item: any) {
  const { id } = item
  permissionsDataItem.value = item
  post(GETAUTORITY, { role: id, companyId }).then(res => {
    if (res.code != 'ok') {
      globalPopup?.showError(res.msg)
      return
    }
    permissionsData.value = res.data
    allDialogVisible.permissionsDialogVisible = true
  }).catch(() => {
    allDialogVisible.permissionsDialogVisible = true
  })
}

function addRole(formEl: FormInstance | undefined) {
  if (!formEl) return
  let data = getFromValue(roleFrom)
  allLoading.roleLoading = true
  post(EDITROLE, { ...data, companyId }).then(res => {
    if (res.code != 'ok') {
      globalPopup?.showError(res.msg)
      return
    }
    globalPopup?.showSuccess('添加成功')
    allDialogVisible.roleDialogVisible = false
    allLoading.roleLoading = false
    getRoleList()
  }).catch(() => {
    allLoading.roleLoading = false
  })
}

function changeRole(item: any = false) {
  if (!item) {
    resetData()
    allDialogVisible.roleDialogVisible = true
  }
  const { id, rolename, roleDescribe } = JSON.parse(JSON.stringify(item))
  Object.assign(roleFrom, { id, name: rolename, description: roleDescribe })
  allDialogVisible.roleDialogVisible = true
}

function deteleRole(data: any) {
  ElMessageBox.confirm(
    `确定删除【${data.rolename}】角色吗？`, '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      post(DETELEROLE, { id: data.id }).then(res => {
        if (res.code != 'ok') {
          globalPopup?.showError(res.msg)
          return
        }
        globalPopup?.showSuccess('删除成功')
        getRoleList()
      })
    })
}

function getRoleList() {
  allLoading.tableLoading = true
  const companyId = getUserInfoVal('companyId') || ''
  post(GETROLELIST, { companyId }).then(res => {
    tableData.value = res.data
    allLoading.tableLoading = false
  }).catch(() => {
    allLoading.tableLoading = false
  })
}

function resetData() {
  let newRoleFrom = resetFromValue(roleFrom)
  Object.assign(roleFrom, newRoleFrom)
}

function handleClose(done: any) {
  done()
}

onMounted(() => {
  getRoleList()
});
</script>

<style lang="scss" scoped>
.roleStyle {
  .team-header {
    padding: 0.75rem 1.25rem;
  }

  .permissionsData {
    padding: 0 20px 0 40px;
    height: 56vh;
    overflow: auto;

    .bold {
      font-weight: bold;
    }

    .list {
      display: flex;
      justify-content: space-between;
    }

    .itemName {
      width: 180px;
      margin: 0 0 6px 0;
      font-size: 16px !important;
    }

    .item {
      flex-wrap: wrap;
    }
  }
}
</style>