<template>
  <el-dialog
    class="org-model"
    v-model="state"
    width="610"
    :destroy-on-close="true"
    :align-center="true"
    @closed="onClosed"
  >
    <div class="title">
      <div class="text">{{ popName }}角色</div>
      <Icon @click="goClose" class="close" icon="ep:close" />
    </div>

    <div :class="['content', { disabled: type === 'check' }]">
      <el-form ref="formRef" :model="params" :rules :show-message="false">
        <div class="block-container road-setting">
          <el-form-item prop="deptId" label="归属机构">
            <el-tree-select
              v-model="params.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择归属机构"
            />
          </el-form-item>

          <el-form-item prop="name" label="角色名称：">
            <el-input v-model="params.name" placeholder="请输入..." />
          </el-form-item>

          <el-form-item prop="code" label="英文名称：">
            <el-input v-model="params.code" placeholder="请输入..." />
          </el-form-item>

          <el-form-item prop="status" label="是否可用：">
            <el-radio-group v-model="params.status">
              <el-radio :value="0"> 是 </el-radio>
              <el-radio :value="1"> 否 </el-radio>
            </el-radio-group>
            <span class="c-#ffffff ml-3"> *“是”代表此数据可用，“否”代表此数据不可用</span>
          </el-form-item>

          <el-form-item label="角色授权：">
            <div class="w70 p-l-4 c-#ffffff"> 功能清单</div>
            <div class="c-#ffffff"> 是否可见</div>
          </el-form-item>

          <el-form-item
            label=" "
            class="radio_form_items"
            v-for="(v, i) in getIntDictOptions(DICT_TYPE.MENUS).reverse() || []"
            :key="i"
            :prop="'menuOptions.' + i + '.id'"
          >
            <div class="w70 p-l-4"> {{ v.label }}</div>
            <el-switch
              class="x-switch"
              v-model="params.menuCheckedStates[v.value]"
              inline-prompt
              active-text="可见"
              inactive-text="隐藏"
              :disabled="v.value == 1"
              @change="updateMenuIds(v.value, $event)"
            />
          </el-form-item>
          <el-form-item prop="remark" label="备注：">
            <el-input type="textarea" rows="3" v-model="params.remark" placeholder="请输入..." />
          </el-form-item>
        </div>
      </el-form>
    </div>

    <template #footer>
      <div class="footer">
        <el-button v-if="type === 'check'" type="primary" @click="goClose">关闭</el-button>
        <template v-else>
          <el-button @click="goClose">取消</el-button>
          <el-button @click="onSubmit" type="primary">确定</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { TUNNEL_TYPES } from '@/config/dict'
import { withDefaults, defineProps } from 'vue'
import { defaultProps, handleTree } from '@/utils/tree'
import {
  getOrgainzations,
  deleteOne,
  getSimpleDeptList,
  roleCreate,
  getDetails,
  updateRole
} from '@/api/system/role'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const emits = defineEmits(['update'])
const state = ref(false)
const type = ref<any>(null)
const deptList = ref<any>([])
const params = reactive({
  name: '',
  code: '',
  sort: 1,
  remark: '',
  dataScopeDeptIds: null,
  deptId: '',
  status: 0,
  menuIds: [], // 用于存储实际选中的菜单ID
  menuCheckedStates: {} // 用于存储每个菜单项的选中状态
})

const formRef = ref(null)

const rules = reactive<any>({
  deptId: [{ required: true }],
  name: [{ required: true }],
  code: [{ required: true }]
})

const popName = computed(() => {
  return {
    check: '查看',
    edit: '编辑',
    new: '新增'
  }[type.value]
})
const diaOpen = async (xtype, e?) => {
  if (e) {
    const res = await getDetails({ id: e.id })
    Object.keys(res).forEach((key) => {
      params[key] = res[key]
    })
    updateRadio()
  }
  type.value = xtype
  state.value = true
}
// 更新 menuIds 数组的方法
const updateMenuIds = (menuValue, isChecked) => {
  if (menuValue == 7) {
    params.menuCheckedStates[2] = isChecked
    params.menuCheckedStates[3] = isChecked
    params.menuCheckedStates[4] = isChecked
    params.menuCheckedStates[5] = isChecked
    params.menuCheckedStates[6] = isChecked
  }
  if ([2, 3, 4, 5, 6].includes(menuValue)) {
    if (
      [2, 3, 4, 5, 6].some((index) => params.menuCheckedStates[index])
    ) {
      params.menuCheckedStates[7] = true
    } else {
      params.menuCheckedStates[7] = false
    }
  }
  if (isChecked) {
    if (!params.menuIds.includes(menuValue)) {
      params.menuIds.push(menuValue)
    }
  } else {
    const index = params.menuIds.indexOf(menuValue)
    if (index > -1) {
      params.menuIds.splice(index, 1)
    }
  }
}
const goClose = () => {
  state.value = false
}

const onClosed = () => {
  // 数据清除
  params.name = ''
  params.code = ''
  params.remark = ''
  params.deptId = ''
  params.menuIds = []
  params.status = 0
  updateRadio()
}

// 更新radio
const updateRadio = () => {
  const options = getIntDictOptions(DICT_TYPE.MENUS) || []

  // console.log(options, params.menuIds, '88888')

  options.forEach((option) => {
    params.menuCheckedStates[option.value] = params.menuIds.includes(option.value)
  })
  if (
    params.menuIds.includes(7) &&
    [2, 3, 4, 5, 6].every((item) => params.menuIds.includes(item))
  ) {
    params.menuCheckedStates[2] = true
    params.menuCheckedStates[3] = true
    params.menuCheckedStates[4] = true
    params.menuCheckedStates[5] = true
    params.menuCheckedStates[6] = true
  }
params.menuCheckedStates[1] = true
  // params.menuCheckedStates[7] = params.menuIds.some((item) => [2, 3, 4, 5, 6].includes(item))
}

function isSubset(superArray, subArray) {
  return subArray.every((item) => superArray.includes(item))
}
// 提交
const onSubmit = async () => {
  const base = await new Promise((resolve) => {
    formRef.value?.validate((e) => {
      resolve(e)
    })
  })
  if (!base) {
    return ElMessage.error('请完成数据填写！')
  }

  params.menuIds = []
  for (const key in params.menuCheckedStates) {
    if (params.menuCheckedStates.hasOwnProperty(key) && params.menuCheckedStates[key] == true) {
      params.menuIds.push(parseInt(key, 10))
    }
  }

  if (type.value === 'new') {
    params.id = ''
    await roleCreate(params)
  } else {
    await updateRole(params)
  }

  ElMessage.success(type.value === 'edit' ? '修改成功！' : '创建成功！')
  state.value = false
  emits('update')
}

//获取组织列表
const getDeptlist = async () => {
  const res = await getSimpleDeptList(params)
  deptList.value = handleTree(res)
}
// 初始化菜单项的选中状态
onMounted(() => {
  updateRadio()
})
defineExpose({
  diaOpen,
  getDeptlist
})
</script>

<style lang="scss" scoped>
$base_url: '@/assets/images/home/';

.title {
  height: 48px;
  display: flex;
  align-content: center;
  align-items: center;
  color: white;
  padding: 0 20px;
  font-size: 18px;
  font-weight: 600;
  justify-content: space-between;
  .close {
    cursor: pointer;
  }
}

.content {
  padding: 0 16px;
  // height: 600px;

  .block-container {
    padding-right: 24px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-top: 20px;
  }

  &.disabled {
    :deep(.base-block) {
      pointer-events: none;
    }
    :deep(.road-setting) {
      pointer-events: none;
    }
    :deep(.el-input) {
      background: rgba($color: #ffffff, $alpha: 0.2);
    }
  }
  .radio_form_items {
    color: #ffffff;
    :deep(.el-form-item__content) {
      height: 44px;
      background: rgba(69, 116, 182, 0.2);
      border-radius: 2px;
    }
    .x-switch {
      :deep(.el-switch__core) {
        height: 26px;
        width: 52px;
        border-radius: 26px;
      }
    }
  }
}

.footer {
  // background: rgba(69, 116, 182, 0.36);
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 20px 24px;
  color: white;
}
</style>

<style lang="scss">
.org-model {
  padding: 0;
  box-sizing: border-box;
  // border: 1px solid rgba(255, 255, 255, 0.5);
  background: #0d3561;
  border-radius: 4px;

  .el-dialog__header {
    display: none;
  }
  .el-dialog__footer {
    padding-top: 0;
  }
  .def-btn {
    background: #1270ff;
    border: 1px solid rgba(155, 193, 255, 0.74);
    height: 28px;
    padding: 8px 10px;
    color: white;
    &:hover {
      border: 1px solid rgba(255, 255, 255, 0.8);
    }
  }
}
</style>
