<script setup lang="ts">
import { ref, unref, watchEffect, onMounted } from "vue";
import { useAsync } from "/@/hooks";
import { MOCK_PROCESS_DATA } from "../config/mock";
import { httpAllList } from "/@/api/interest/processPermission";

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

const { data: rule_process_list, run: listRun } = useAsync({
  initalData: [],
  isList: true
});

const { data: list, run: allListRun } = useAsync({
  initalData: MOCK_PROCESS_DATA
});

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

//刷新流程
watchEffect(() => {
  const { currentRole } = props;
  // listRun()

  console.log(list.value);
});

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;
}

// onMounted(() => allListRun(httpAllList()));
</script>

<template>
  <ElScrollbar>
    <template v-for="(p, index) in list" :key="p.id">
      <div w-full>
        <p>{{ p.process_name }}</p>

        <ElDivider border-style="dashed" m-0 />

        <div flex gap-10 v-if="p.child">
          <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>
