<script setup name="roleDrawer">
import { ref, watch, nextTick, getCurrentInstance, onMounted } from 'vue'
import { editRole, getUserRoleList, getDataPermissionMenu, saveNewRole, getUserRoleDetail } from '@/http/apis/systemManage/roleManage'
import { getSystemAllMenuList } from '@/http/apis/systemManage/menuManage'
const { proxy } = getCurrentInstance(),
  props = defineProps({
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    data: Object
  })

const emits = defineEmits(['close']),
  formRef = ref(),
  menuTreeRef = ref(),
  menuTree = ref([]),
  form = ref({
    id: undefined,
    name: undefined,
    manageRoleIds: undefined,
    describe: undefined,
    menuDataScopeList: [],
    menuDataScopeList2: [],
    menuData: []
  }),
  rules = {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    manageRoleIds: [{ required: false, message: '请选择可控角色', trigger: 'change' }]
  },
  customNodeClass = data => {
    return `bgc${data.manageRoleIds}`
  },
  submit = async formEl => {
    if (!formEl) {
      return
    }
    await formEl.validate(async valid => {
      if (valid) {
        const menuIds = menuTreeRef.value.getCheckedKeys()
        const postData = {
          ...form.value,
          menuIds: menuIds.map(i => { return i }),
          id: props.data?.id,
          manageRoleIds: form.value.manageRoleIds?.join(',') || '',
          menuData: undefined,
          menuDataScopeList2: undefined
        }
        if (props.data?.id) {
          await editRole(postData)
          proxy.$message.success('编辑成功！')
        } else {
          await saveNewRole(postData)
          proxy.$message.success('新增成功！')
        }
        emits('close', true)
      }
    })
  },
  // 获取初始选中id
  setChecked = (tree) => {
    const ids = []
    tree.forEach(data => {
      if (data.children) {
        setChecked(data.childern)
      } else {
        ids.push(data.id)
      }
    })
    return ids
  },
  controllableRoleList = ref([]),
  dataPermissionMenu = ref([]),
  compact = arr => arr.filter(res => res !== null), // 删除数组中的null
  handleMenuDataScopeList = (dataScope, menuId) => {
    form.value.menuDataScopeList2[menuId] = { dataScope, menuId }
    const res = compact(form.value.menuDataScopeList2)
    const resTransition1 = JSON.parse(JSON.stringify(res))
    form.value.menuDataScopeList = resTransition1
  }
onMounted(async () => {
})
watch(
  () => props.visible,
  async val => {
    if (val) {
      const controllableRole = await getUserRoleList()
      controllableRoleList.value = controllableRole.data.records
      if (props.data && props.data.id) {
        const userRoleDetail = await getUserRoleDetail({ id: props.data.id })
        menuTreeRef.value.setCheckedKeys(setChecked(userRoleDetail.data.menu))
        const dataScopeArr = []
        userRoleDetail.data.menuDataScopeList.forEach(element => {
          dataScopeArr.push(element.dataScope)
        })
        await nextTick()
        form.value = {
          id: props.data.id,
          name: props.data.name,
          manageRoleIds: userRoleDetail.data.manageRoleIdList,
          describe: userRoleDetail.data.describe,
          menuDataScopeList: [],
          menuDataScopeList2: [],
          menuData: dataScopeArr
        }
      } else {
        form.value.menuData = []
      }
      const dataPermissionMenuRes = await getDataPermissionMenu()
      dataPermissionMenu.value = dataPermissionMenuRes.data
      const res = await getSystemAllMenuList({ id: props.data && props.data.id || '' })
      menuTree.value = res.data
    } else {
      formRef.value.resetFields()
      form.value.id = undefined
      await nextTick()
      menuTreeRef.value.setCheckedKeys([])
    }
  }
)
</script>

<template>
  <el-drawer
    :model-value="visible"
    :title="props?.data?.id?'编辑角色':'新增角色'"
    size="50%"
    @close="emits('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="90px"
      label-suffix=":"
    >
      <div class="el-descriptions__title mb-16">基本信息</div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="角色名称"
            prop="name"
          >
            <el-input
              v-model="form.name"
              placeholder="请输入"
              :disabled="Boolean(!data?.isEdit&&data?.rulesId)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="可控角色"
            prop="manageRoleIds"
          >
            <el-checkbox-group v-model="form.manageRoleIds">
              <el-checkbox
                v-for="item in controllableRoleList"
                :key="item.id"
                :label="item.id"
              >{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item
        label="角色描述"
        prop="describe"
      >
        <el-input
          v-model="form.describe"
          type="textarea"
          maxlength="200"
          show-word-limit
          placeholder="请输入"
        />
      </el-form-item>
      <div class="el-descriptions__title mb-16">菜单权限</div>
      <el-form-item label-width="0px">
        <el-tree
          ref="menuTreeRef"
          :data="menuTree"
          class="w-full"
          show-checkbox
          default-expand-all
          node-key="id"
          :props="{ class: customNodeClass, label: 'title', value: 'id' }"
        />
      </el-form-item>
      <div class="el-descriptions__title mb-16">数据权限</div>
      <div
        v-for="item in dataPermissionMenu"
        :key="item.id"
      >
        <div class="ml-18 mb-16">{{ item.title }}</div>
        <el-form-item
          v-for="(one, order) in item.children"
          :key="one.id"
          label-width="130px"
          :label="one.title"
          prop="menuData"
        >
          <el-radio-group v-model="form.menuData[order]">
            <el-radio
              v-for="(each,index) in one.dataScopeOption.split(',')"
              :key="index"
              :label="each*1"
              @change="handleMenuDataScopeList(each*1 ,one.id)"
            >{{ each*1 === 1 ? '本单位' : each*1 === 2 ? '本单位及下属单位' : each*1 === 3 ? '本区域' : '全市' }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button
        type="primary"
        @click="submit(formRef)"
      >
        提交
      </el-button>
      <el-button
        type="info"
        @click="emits('close')"
      >
        关闭
      </el-button>
    </template>
  </el-drawer>
</template>
<style lang="less" scoped>
:deep(.el-tree) {
  .el-tree-node__content {
    height: 40px;
  }
  .bgc1 {
    & > .el-tree-node__content {
      background-color: rgba(27, 113, 227, 0.12);
    }
  }
  .bgc2 {
    & > .el-tree-node__content {
      background-color: rgba(27, 113, 227, 0.08);
    }
  }
  .bgc3 {
    & > .el-tree-node__content {
      background-color: rgba(27, 113, 227, 0.04);
    }
  }
  .bgc4 {
    & > .el-tree-node__content {
      background-color: #fff;
    }
  }
}
</style>
