<script setup lang="ts">
import { ref, unref, watchEffect } from "vue";
import { MOCK_PROCESS_DATA } from "../config/mock";

defineProps<{
  currentRole: Record<string, string>;
}>();

const emit = defineEmits(["saveBtnClick"]);

//所有的流程权限
const list = ref<any>([...MOCK_PROCESS_DATA]);

//角色拥有的流程权限
const rule_process_list = ref([]);

//刷新流程
watchEffect(() => {
  rule_process_list.value = ["89", "90"];
});

function handleSave() {
  emit("saveBtnClick", unref(rule_process_list));
}

function handleCheckAllChange(status, index) {
  const process = list.value[index].child;
  if (status)
    return process.forEach(p => {
      !rule_process_list.value.includes(p.id) &&
        rule_process_list.value.push(p.id);
    });

  process.forEach(p => {
    const idx = rule_process_list.value.findIndex(c => {
      return c === p.id;
    });
    if (idx >= 0) rule_process_list.value.splice(idx, 1);
  });
}

function isIndeterminate(index: number) {
  const process = list.value[index].child;
  const len = process.length;
  const has = process.filter(p => rule_process_list.value.includes(p.id));
  return has.length > 0 && has.length !== len;
}

function isCheckAll(index: number) {
  const process = list.value[index].child;
  const len = process.length;
  const has = process.filter(p => rule_process_list.value.includes(p.id));
  return has.length === len;
}
</script>

<template>
  <ElScrollbar>
    <template v-for="(p, index) in list" :key="p.id">
      <div w-full v-if="p.child">
        <p>{{ p.process_name }}</p>
        <ElDivider border-style="dashed" m-0 />

        <div flex gap-10>
          <ElCheckbox
            label="全选"
            :model-value="isCheckAll(index)"
            :indeterminate="isIndeterminate(index)"
            @change="handleCheckAllChange($event, index)"
          />

          <ElCheckboxGroup v-model="rule_process_list">
            <ElCheckbox
              v-for="(action, index) in p.child"
              :key="index"
              :label="action.id"
              >{{ action.status_name }}</ElCheckbox
            >
          </ElCheckboxGroup>
        </div>
        <ElDivider />
      </div>
    </template>

    <div fixed right-5 bottom-5>
      <ElButton @click="handleSave" type="primary" size="small">保存</ElButton>
    </div>
  </ElScrollbar>
</template>
