<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :md="24" :lg="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-form
            :model="formItem"
            :label-width="100"
            :rules="rules"
            ref="roleRef"
          >
            <el-form-item label="角色名称" prop="RoleName">
              <el-input v-model="formItem.RoleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="RoleDescription">
              <el-input
                v-model="formItem.RoleDescription"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row type="flex" justify="center" :style="{ marginTop: '20px' }">
      <el-col :md="24" :lg="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>菜单功能</span>
            </div>
          </template>
          <div>
            <div class="menu_box">
              <el-row type="flex" justify="center" align="middle">
                <el-col :md="6" :lg="6">
                  <el-tag color="primary">一级菜单</el-tag>
                </el-col>
                <el-col :md="18" :lg="18">
                  <div>
                    <el-row type="flex" justify="center">
                      <el-col :md="6" :lg="6">
                        <el-tag color="success">二级菜单</el-tag>
                      </el-col>
                      <el-col :md="18" :lg="18">
                        <el-tag color="warning">功能</el-tag>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div
              v-for="menu in MenuAndFunctions"
              :key="menu.Name"
              class="menu_box"
            >
              <el-row type="flex" justify="center" align="middle">
                <el-col :md="6" :lg="6">
                  {{ menu.Name }}
                </el-col>
                <el-col
                  :md="18"
                  :lg="18"
                  :style="{ marginTop: '5px', marginBottom: '5px' }"
                >
                  <div v-for="subMenu in menu.Children" :key="subMenu.Name">
                    <el-row type="flex" justify="center">
                      <el-col
                        :md="6"
                        :lg="6"
                        :style="{ marginTop: '5px', marginBottom: '5px' }"
                      >
                        <el-checkbox v-model="subMenu.Checked">
                          {{ subMenu.Name }}</el-checkbox
                        >
                      </el-col>
                      <el-col
                        :md="18"
                        :lg="18"
                        :style="{ marginTop: '5px', marginBottom: '5px' }"
                      >
                        <span
                          v-for="fun in subMenu.Functions"
                          :key="fun.Name"
                          style="margin-right: 20px"
                        >
                          <el-checkbox v-model="fun.Checked">{{
                            fun.Name
                          }}</el-checkbox>
                        </span>
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
            </div>
            <el-button
              style="margin-top: 20px"
              type="primary"
              :loading="buttonLoading"
              @click="handleEdit"
              >{{ Id != -1 ? '立即修改' : '立即创建' }}</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, ref } from 'vue'
import { getMenuList } from '@/api/menu'
import { getFunctionList } from '@/api/function'
import { useRoute, useRouter } from 'vue-router'

import { getRoleDetail, editRole } from '@/api/role'
import { ElMessage } from 'element-plus'
export default {
  setup() {
    const roleRef = ref(null)
    const router = useRouter()
    const route = useRoute()
    const { Id } = route.params
    const state = reactive({
      //当前是编辑还是新增(Id:-1)
      Id,
      //当前角色具有的菜单和功能权限
      MenuAndFunctions: [],
      formItem: {
        RoleName: '',
        RoleDescription: ''
      },
      RoleMenuList: [],
      RoleFunctionList: [],
      buttonLoading: false,
      rules: {
        RoleName: [
          { required: 'true', message: '请输入角色名称', trigger: ['change'] }
        ],
        RoleDescription: [
          { required: 'true', message: '请输入角色描述', trigger: ['change'] }
        ]
      }
    })

    onMounted(async () => {
      await init()
    })

    const init = async () => {
      const Id = state.Id
      if (Id !== '-1') {
        const response = await getRoleDetail({ Id })
        if (response.BussinessCode !== 0) {
          ElMessage.error(response.BussinessMsg)
          return
        }
        const data = response.BussinessData
        state.formItem.RoleName = data.Name
        state.formItem.RoleDescription = data.Description
        state.RoleMenuList = data.RoleMenuList
        state.RoleFunctionList = data.RoleFunctionList
      }
      await loadAllMenuAndFunction()
    }

    const loadAllMenuAndFunction = async () => {
      const response1 = await getMenuList()
      if (response1.BussinessCode === 0) {
        state.MenuAndFunctions = response1.BussinessData
        // 补充没有二级菜单的（用一级菜单填充）
        state.MenuAndFunctions.forEach((item) => {
          if (item.Children.length === 0) {
            item.Children.push({
              Id: item.Id,
              Code: item.Code,
              Name: item.Name,
              Functions: [],
              Checked: false
            })
          } else {
            item.Children.forEach((sm) => {
              sm.Functions = []
              sm.Checked = false
            })
          }
        })
      } else {
        ElMessage.error(response1.BussinessMsg)
      }

      const response2 = await getFunctionList({ PageSize: 10000, PageNum: 1 })
      if (response2.BussinessCode === 0) {
        const functionData = response2.BussinessData
        // 将功能放入二级菜单中
        functionData.forEach((item) => {
          state.MenuAndFunctions.forEach((m) => {
            m.Children.forEach((sm) => {
              if (sm.Id === item.MenuId) {
                sm.Functions.push({
                  Id: item.Id,
                  Code: item.Code,
                  Name: item.Name,
                  Checked: false
                })
              }
            })
          })
        })
        loadRoleMenuAndFunction()
      } else {
        ElMessage.error(response2.BussinessMsg)
      }
    }

    const loadRoleMenuAndFunction = async () => {
      state.RoleMenuList.forEach((rm) => {
        state.MenuAndFunctions.forEach((menu) => {
          menu.Children.forEach((subMenu) => {
            if (subMenu.Id === rm.MenuId) {
              subMenu.Checked = true
            }
          })
        })
      })
      state.RoleFunctionList.forEach((rf) => {
        state.MenuAndFunctions.forEach((menu) => {
          menu.Children.forEach((subMenu) => {
            subMenu.Functions.forEach((fun) => {
              if (fun.Id === rf.FunctionId) {
                fun.Checked = true
              }
            })
          })
        })
      })
    }

    const handleEdit = async () => {
      roleRef.value.validate(async (vaild) => {
        if (vaild) {
          //勾选的id
          let menuIds = ''
          let functionIds = ''
          state.MenuAndFunctions.forEach((menu) => {
            menu.Children.forEach((sm) => {
              if (sm.Checked) menuIds += sm.Id + ','
              sm.Functions.forEach((fun) => {
                if (fun.Checked) functionIds += fun.Id + ','
              })
            })
          })
          menuIds = menuIds.substring(0, menuIds.lastIndexOf(','))
          functionIds = functionIds.substring(0, functionIds.lastIndexOf(','))

          const response = await editRole({
            RoleId: state.Id === '-1' ? '' : state.Id,
            RoleName: state.formItem.RoleName,
            RoleDescription: state.formItem.RoleDescription,
            MenuIds: menuIds,
            FunctionIds: functionIds
          })
          state.buttonLoading = false
          if (response.BussinessCode !== 0) {
            console.log(response.BussinessMsg)
            return
          }
          router.push('/right/role_list')
        }
      })
    }

    return {
      roleRef,
      handleEdit,
      ...toRefs(state)
    }
  }
}
</script>

<style type="text/css">
.menu_box {
  width: 100%;
  border-bottom: dashed 1px #ccc;
  padding: 10px;
  box-sizing: border-box;
}
</style>
