<template>
  <div>
    <el-dialog
      :title="`${props.rowData?.id ? '编辑' : '新增'}角色`"
      v-model="dialogVisible"
    >
      <div>
        <el-form ref="formRef" :model="form" size="large" label-width="120px">
          <el-form-item
            label="角色名称"
            :rules="[
              {
                required: true,
                message: '请输入角色名称',
                trigger: 'blur'
              }
            ]"
            prop="name"
          >
            <el-input
              clearable
              v-model="form.name"
              placeholder="请输入角色名称"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="角色权限" style="font-weight: bold" required>
            <el-tabs
              v-model="permissionName"
              class="demo-tabs"
              @tab-click="handleClick"
            >
              <el-tab-pane label="功能权限" name="feature">
                <div style="width: 100%">
                  <el-checkbox v-model="checkAll" @change="checkAllChange"
                    >全选</el-checkbox
                  >
                  <div v-for="(item, index) in permissions" :key="index">
                    <el-divider class="m-1"></el-divider>
                    <div>{{ item.label }}</div>
                    <div>
                      <el-checkbox
                        v-model="child.checked"
                        v-for="(child, childIndex) in item.children"
                        :key="childIndex"
                        @change="onChangeCheck"
                        >{{ child.label }}</el-checkbox
                      >
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="数据权限" name="data">
                <CardLargeScreenAuth
                  :id="props.rowData?.id"
                  ref="cardLargeScreenAuthRef"
                ></CardLargeScreenAuth>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit(formRef)"
              >确定</el-button
            >
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { request } from "@/utils";
import { ref, computed, defineProps, defineEmits, watch, nextTick } from "vue";

import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import CardLargeScreenAuth from "./CardLargeScreenAuth.vue";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["update:show"]);
const form = ref({
  name: "",
  permissions: []
});
const formRef = ref();
const cardLargeScreenAuthRef = ref(null);
const checkAll = ref(false);
const permissions = ref([]);
const permissionName = ref("feature");
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});
watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      if (props.rowData?.id) {
        form.value.name = props?.rowData.name;
        form.value.permissions = props?.rowData.permissions;
      }
      init();
    } else {
      onReset();
    }
  }
);
const getPermissions = () => {
  request.get("/mechanism/role/permission/list").then(resp => {
    permissions.value = formatPermissions(resp.data.list);
  });
};

const formatPermissions = (list, checked, key = "value") => {
  return list.map(v => {
    if (v.children.length) {
      v.children.forEach(vv => {
        if (form.value.permissions.includes(vv.value)) {
          vv.checked = true;
        } else {
          vv.checked = false;
        }
        // vv.disabled =
        //   getSame(form.value.permissions, vv.requiredValues).length !=
        //   vv.requiredValues.length;
      });
    }
    return v;
  });
};
const permissionsValues = () => {
  let values = [];
  permissions.value.map(v => {
    v.children.forEach(vv => {
      if (vv.checked) {
        values.push(vv.value, ...vv.requiredValues);
      }
    });
  });
  return values;
};
const onChangeCheck = values => {
  if (!values) {
    checkAll.value = false;
  }
  form.value.permissions = permissionsValues();
  formatPermissions(permissions.value);
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (permissionName.value == "feature") {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (!valid) return;
      if (!form.value.permissions.length) {
        return ElMessage.error("请至少选择一个权限");
      }
      let params = form.value;
      props?.rowData?.id && (params.id = props?.rowData?.id);
      request.post("/mechanism/role/updateOrCreate", params).then(resp => {
        ElMessage.success(resp.message);
        onCancel();
      });
    });
  } else {
    cardLargeScreenAuthRef.value.onSave().then(resp => {
      onCancel();
    });
  }
};

const onReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  form.value = {
    name: "",
    permissions: []
  };
};

const onCancel = () => {
  dialogVisible.value = false;
};
const checkAllChange = val => {
  checkAll.value = val;
  permissions.value.map(v => {
    v.children.forEach(vv => {
      vv.checked = val;
    });
  });
  form.value.permissions = permissionsValues();
  formatPermissions(permissions.value);
};

const getSame = (arr1, arr2) => {
  return [...new Set(arr1)].filter(item => arr2.includes(item));
};

const init = () => {
  permissionName.value = "feature";
  getPermissions();
  checkAll.value = false;
  nextTick(() => {
    cardLargeScreenAuthRef?.value?.init();
  });
};
</script>
