<template>
  <div class="role">
    <searchBox :btn-option-list="btnOptionList" @operateForm="operateForm"></searchBox>

    <div class="content-table">
      <ComTable
        :columns="columns"
        :table-data="tableData"
        @handlePagesizeChange="handlePagesizeChange"
        ref="comTable"
        :table-option="tableOption"
        :page-option="pageOption"
      >
        <template #is_open="record">
          <!-- 0:禁用; 1:启用 -->
          <a-tag :color="record.is_open == 0 ? 'red' : 'green'">{{
            record.is_open == 0 ? '禁用' : '启用'
          }}</a-tag>
        </template>
        <template #permission="record">
          <!-- 0:禁用; 1:启用 -->
          <span>{{ record.permission.map((item) => item.name).toString() }}</span>
        </template>

        <template #action="record">
          <OperateCom :record="record" :operate-list="operateList" @operateForm="operateForm" />
        </template>
      </ComTable>
    </div>
    <a-modal
      v-model:open="formModal"
      width="950px"
      style="top: 80px"
      :footer="null"
      :destroy-on-close="true"
    >
      <!-- action:edit add -->
      <EditCom
        :show-flag="formModal"
        :record="record"
        @operateForm="operateForm"
        type="role"
        :action="formStatus"
      ></EditCom>
    </a-modal>
  </div>
</template>

<script>
import { columnList, roleOptions } from '../../../public/config/columnList'
import { getReq, postReq } from '@/request/api.js'
import ComTable from '@/components/ComTable'
import OperateCom from '@/components/OperateCom'
import EditCom from '@/components/EditCom.vue'
import { ConsoleSqlOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { createVNode } from 'vue'

import searchBox from '@/components/SearchBox.vue'
export default {
  name: '',
  components: {
    searchBox,
    EditCom,
    ComTable,
    OperateCom
  },
  props: {},
  data() {
    return {
      tableData:[],

      formModal: false,
      formState: {},
      formStatus: 'add', //表单状态辑状态 add:新增 edit:编辑
      pageOption: {
        pageSize: 10,
        page: 1
      },
      btnOptionList: [],
      paramsDate: {},
      tableOption: {
        select: false
      }
    }
  },
  computed: {},
  created() {
    let info = []
    let col = columnList.find((i) => i.page == 'role').columns
    if (col.length) {
      col.forEach((item) => {
        info.push(this.$setWidth(item))
      })
    }
    this.columns = info
  },

  mounted() {
    this.operateList = this.$getBtns(['查看', '修改', '删除'])
    this.btnOptionList = this.$getBtns(['新增'])
    this.getList()
  },

  methods: {
    async getList() {
      this.$refs.comTable.loading = true

      const { page, pageSize } = this.pageOption

      const params = {
        ...this.paramsDate,
        page_size: pageSize,
        page
      }

      try {
        const res = await getReq('/queryRoleList', params)
        if (res.errcode === 0) {
          this.$refs.comTable.loading = false

          this.tableData = res.data

          this.pageOption = {
            page: res.page,
            pageSize: res.page_size,
            count: res.count
          }
        } else {
          const err = { tip: res.errmsg }
          throw err
        }
      } catch (error) {
        this.$refs.comTable.loading = false

        //统一处理报错提示
      }
    },
    mergePermissionData(routeData, permissionData) {
      // 创建权限ID快速索引
      const permissionMap = new Map()

      // 构建权限配置映射表（含子权限处理）
      const flattenPermissions = (data) => {
        data.forEach((item) => {
          // 初始化权限项的默认值（关键修改）
          const permissionItem = {
            ...item,
            key: item.permission_id,
            is_add: Boolean(+item.is_add) || false,
            is_del: Boolean(+item.is_del) || false,
            is_edit: Boolean(+item.is_edit) || false,
            is_view: Boolean(+item.is_view) || false,
            // 确保子权限容器存在
            children: item.children ? [...item.children] :undefined
          }

          permissionMap.set(item.permission_id, permissionItem)

          // 递归处理子权限
          if (item.children?.length) {
            flattenPermissions(item.children)
          }
        })
      }

      // 初始化扁平化处理
      flattenPermissions(permissionData)

      // 递归构建合并后的树形结构
      const buildTree = (data) => {
        return data
          .map((routeItem) => {
            const permissionItem = permissionMap.get(routeItem.permission_id) || {
              key: routeItem.permission_id,
              is_add: false,
              is_del: false,
              is_edit: false,
              is_view: false
            }

            // 基础合并：路由结构+权限配置
            const mergedItem = {
              ...routeItem,
              ...permissionItem,
              // 初始化子权限容器
              children: routeItem.children ? buildTree(routeItem.children) : undefined
            }

            // 特殊处理：父级权限的联动计算
            this.calculateParentPermissions(mergedItem)

            return mergedItem
          })
          .filter(Boolean) // 过滤无效节点
      }

      return buildTree(routeData)
    },
    calculateParentPermissions(node) {
      if (node.children?.length) {
        node.is_view = node.children.some((child) => child.is_view === '1') ? true : false
        node.is_add = node.children.some((child) => child.is_add === '1') ? true : false
        node.is_edit = node.children.some((child) => child.is_edit === '1') ? true : false
        node.is_del = node.children.some((child) => child.is_del === '1') ? true : false
      }
    },


 
    operateForm(type, record = {}) {
      this.formStatus = type
      switch (type) {
      case 'add':
        this.formState = {}
        this.getRuleFormInfo()

        break
      case 'edit':
      case 'read':
        this.formState = record
        this.getRuleFormInfo(record)
        break

      case 'del':
        this.handleDelete([record.role_id], this.getList)

        break

      case 'back':
        this.formModal = false
        this.getList()
        break

      default:
        break
      }
    },
    //  删除操作
    async handleDelete(id, callback) {
      const that = this
      this.$Modal.confirm({
        title: '你确认删除数据吗?',
        icon: createVNode(ExclamationCircleOutlined),

        async onOk() {
          try {
            const res = await getReq('/deleteRole', { role_id: id })
            if (res.errcode === 0) {
              this.$message.success(res.errmsg)
              this.pageOption.page = 1
              callback()
            } else {
              throw res
            }
          } catch (error) {
            callback()
          }
        },
        onCancel() {},
        class: 'test'
      })
    },
    async getRuleFormInfo(record) {
      function getInfo(data, url) {
        return new Promise((reslove, reject) => {
          getReq(data, url).then((res) => {
            reslove(res.data)
          })
        })
      }

      let row = {}
      if (record && record.role_id) {
        this.record = record
        row = record
      }
      const perList = await this.getPermissionList()

      function markCheckedPermissions(tree, rolePerms) {
        return tree.map((perm) => {
          // 深拷贝权限项，避免污染原始数据
          const node = { ...perm };
    
          // 检查当前权限是否被角色勾选
          const isChecked = rolePerms.some(
            (rp) => rp.permission_id === node.permission_id
          );
          console.log(isChecked,rolePerms,"isChecked")
          node.checked = isChecked;

          // 递归处理子权限
          if (node.children && node.children.length > 0) {
            // 找到角色权限中对应的子权限列表
            const roleChildPerms = rolePerms.find(
              (rp) => rp.permission_id === node.permission_id
            )?.children || [];
            node.children = markCheckedPermissions(node.children, roleChildPerms);
          }else {
            node.children =undefined
          }

          return node;
        });
      }

      const newData = markCheckedPermissions(perList, record.permission);



      this.processedData = this.mergePermissionData(
        newData,
        record && record.permission.length ? record.permission : []
      )
      // const newData = JSON.parse(JSON.stringify(this.processedData))



      this.formModal = true
      roleOptions.forEach((e, index) => {
        e.list.forEach((i) => {
          if (i.key == 'permission') {
            i.tableData =  this.processedData
           
          } else {
            e.ruleForm[i.key] = row ? row[i.key] : ''
          }
        })
      })


    },
    async getPermissionList() {
      let arr = []
      const res = await getReq('/queryPermissionList', { page_size: 1000, page: 1 })

      if (res.errcode === 0) {
        arr = res.data

      }

      return arr
    },
    handlePagesizeChange(pageOption) {
      this.pageOption.pageSize = pageOption.pageSize
      this.pageOption.page = pageOption.page
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.role {
  height: 100%;

  padding:  20px;
  .content-table {
    height: calc(100% - 52px);
  }
}
</style>
