<!-- 角色管理 -->
<template>
  <div class="detail_container">
    <div class="bg-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> 系统管理 </el-breadcrumb-item>
        <el-breadcrumb-item to="/system/role"> 角色管理 </el-breadcrumb-item>
        <el-breadcrumb-item> {{route.query.id ? "编辑" : "新建"}} </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main_container">
      <div class="top_form bg-scroll">
        <el-form
          ref="form"
          :rules="rules"
          :model="formData"
          class="role_form"
        >
          <el-form-item prop="role_name" label="角色名称">
            <el-input v-model="formData.role_name" maxlength="50" show-word-limit />
          </el-form-item>
          <el-form-item prop="role_desc" label="描述">
            <el-input
              class="decs_box"
              type="textarea"
              v-model="formData.role_desc"
              maxlength="300" 
              show-word-limit
              :autosize="{ minRows: 5 }"
            ></el-input>
          </el-form-item>

          <el-form-item label="数据权限" prop="data_purview">
            <el-radio-group v-model="formData.data_purview">
              <el-radio :label="3">全平台所有</el-radio>
              <el-radio :label="2">本组织所有</el-radio>
              <el-radio :label="1">仅自己</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单功能权限" prop="permission_arr">
            <bg-permission
              :values="formData.permission_arr"
              :options="permissionData"
              :props="defaultProps"
              @changeMenu="changeMenu"
            />
          </el-form-item>
          <el-form-item label="是否启用" prop="state" class="state_item">
            <el-switch
              class="bg-switch-ele"
              v-model="formData.state"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>

        </el-form>
      </div>
      <div class="bottom_action">
        <el-button @click="goList">
          取消
        </el-button>
        <el-button type="primary" @click="saveRole">
          保存
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, toRefs, ref, onBeforeMount, nextTick } from 'vue'
import axios from '../../../../../request/http.js'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const form = ref(null)
const checkMenuLength = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请选择所需菜单'))
  } else {
    callback()
  }
}

const roleState = reactive({
  form,
  formData: {
    role_name: "",
    role_desc: "",
    data_purview: 3,
    state: 1,
    permission_arr: [],
  }, // 表单项
  rules: {
    role_name: [
      { required: true, message: "请输入角色名称", trigger: "blur" },
    ],
    
    data_purview: [
      { required: true, message: "请选择数据权限", trigger: "change" },
    ],
    state: [
      { required: true, message: "请选择是否启用", trigger: "change" },
    ],
    permission_arr: [
      { required: true, type: "array", validator: checkMenuLength, trigger: "change" }
    ]
  }, // 表单校验规则
  defaultProps: {
    name: 'menu_name',
    value: 'id',
    children: 'Child',
  }, // 菜单框默认配置
  permissionData: [], // 菜单数据
})
const getMenuTree = () => {
  axios
    .get(`/apaas/system/v5/menu/tree`)
    .then((res) => {
      if (res.data.code == 200) {
        roleState.permissionData = res.data.data || []
      }else {
        ElMessage.error(res.data.data)
      }
    })
} // 获取菜单数据

const changeMenu = (val) => {
  roleState.formData.permission_arr = val
} // 修改选中的菜单

const getRoleDetail = () => {
  axios
    .get(`/apaas/system/v5/role/detail/${route.query.id}`)
    .then((res) => {
      if (res.data.code == 200) {
        let { role_name, role_desc, data_purview, state, menus } = res.data.data
        let permission_arr = []
        if (menus && menus.length > 0) {
          menus.forEach(e => {
            permission_arr.push(e.id)
          })
        }
        roleState.formData = {
          role_name,
          role_desc,
          data_purview,
          state,
          permission_arr:[...permission_arr]
        }
        console.log(roleState.formData.permission_arr)
      }else {
        ElMessage.error(res.data.data)
      }
    })
} // 获取角色详情

const saveRole = () => {
  roleState.form.validate(valid => {
    if (valid) {
      let params = {
        role_name: roleState.formData.role_name,
        role_desc: roleState.formData.role_desc,
        state: roleState.formData.state,
        data_purview: roleState.formData.data_purview,
        menu_ids: [...roleState.formData.permission_arr]
      }
      if (!route.query.id) { // 新增
        axios
          .put(`/apaas/system/v5/role/create`,params)
          .then((res) => {
            if (res.data.code == 200) {
              ElMessage.success(res.data.msg)
              router.push('/system/role')
            }else {
              ElMessage.error(res.data.data)
            }
          })
      }else { // 编辑
        params.id = +route.query.id
        axios
          .post(`/apaas/system/v5/role/update`,params)
          .then((res) => {
            if (res.data.code == 200) {
              ElMessage.success(res.data.msg)
              router.push('/system/role')
            }else {
              ElMessage.error(res.data.data)
            }
          })
      }
    }
  })
} // 新增或编辑角色的保存
const goList = () => {
  router.push("/system/role")
}

onBeforeMount(() => {
  getMenuTree()
  if (route.query.id) {
    // 有id表示是编辑，请求详情，回显
    getRoleDetail()
  }
})
    
const {
  formData,
  rules,
  defaultProps,
  permissionData,
} = toRefs(roleState)
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    flex-grow: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    background-color: #fff;
    box-shadow: 0px 1px 4px 0px rgba(0,7,101,0.15);
    border-radius: 6px;
    margin: 0 0 16px;
    position: relative;
    height: calc(100% - 62px);
    .top_form {
      height: calc(100% - 68px);
      padding: 30px 0 0 40px;
      .role_form {
        width: 1048px;
        :deep().el-form-item {
          display: block;
          margin-bottom: 24px;
          .el-form-item__label {
            display: block;
          }
          .el-input__count {
            bottom: -20px;
            right: 4px;
            color: #a9b1c7;
          }
        }
        .state_item {
          display: flex;
        }
      }
    }
    .bottom_action {
      height: 68px;
      border-top: 1px solid #e6e9ef;
      padding: 16px;
      text-align: right;
      .el-button {
        width: 92px;
      }
    }
  }
}

</style>