<template>
  <div>
    <div class="card content-box">
      <div class="name">{{ supertype }}</div>
      <el-divider />
      <div class="user_box">
        <div>
          <el-form ref="formRef" :model="numberValidateForm" label-width="auto" class="demo-ruleForm">
            <div class="user_div">
              <el-form-item
                prop="departmentId"
                :rules="[
                  {
                    required: true,
                    type: 'array',
                    validator: (rule, value, callback) => {
                      if (value.length === 0) {
                        callback(new Error('请分配菜单权限!'));
                      } else {
                        if (value.length === 0 || value[0] === '') {
                          callback(new Error('请分配菜单权限!'));
                        } else {
                          callback();
                        }
                      }
                    },
                    trigger: 'change'
                  }
                ]"
              >
                <div class="user_right">
                  <TreeFilter
                    multiple
                    title="菜单权限"
                    label="title"
                    :data="TreeDatalist"
                    :default-value="numberValidateForm.departmentId"
                    @change="changeTreeFilter"
                  />
                </div>
              </el-form-item>

              <div class="user_left">
                <div class="elform">
                  <el-form-item label="角色名称：" prop="roleName" :rules="[{ required: true, message: '请输入角色名称' }]">
                    <el-input
                      v-model.number="numberValidateForm.roleName"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="角色名称"
                      autocomplete="off"
                    />
                  </el-form-item>
                  <el-form-item label="权限字符：" prop="roleKey" :rules="[{ required: true, message: '请输入权限字符' }]">
                    <el-input
                      v-model.number="numberValidateForm.roleKey"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="权限字符"
                      autocomplete="off"
                    />
                  </el-form-item>
                </div>
                <div class="elform">
                  <el-form-item label="显示顺序：" prop="roleSort" :rules="[{ required: true, message: '请输入显示顺序' }]">
                    <el-input
                      v-model.number="numberValidateForm.roleSort"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="显示顺序"
                      autocomplete="off"
                    />
                  </el-form-item>
                  <div style="width: 400px">
                    <el-form-item label="状态：" prop="status">
                      <el-switch v-model="numberValidateForm.status" />
                    </el-form-item>
                  </div>
                </div>

                <div class="elform">
                  <el-form-item label="备注：">
                    <el-input
                      v-model="numberValidateForm.remark"
                      style="width: 800px"
                      :rows="4"
                      type="textarea"
                      placeholder="备注："
                    />
                  </el-form-item>
                </div>
                <!-- <div class="elform">
                  <el-form-item label="备注：">
                    <div class="elform_tree">
                      <el-tree
                        style="max-width: 600px"
                        :props="numberValidateForm.menuIds"
                        :load="loadNode"
                        lazy
                        show-checkbox
                        @check-change="handleCheckChange"
                      />
                    </div>
                  </el-form-item>
                </div> -->
              </div>
            </div>

            <el-divider />
            <el-form-item class="bottom">
              <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
              <el-button @click="resetForm(formRef)">关闭</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>
<!--  -->
<script setup lang="ts">
import {
  platformroleadd,
  platformroleedit,
  platformshuRoleedit,
  roleMenuTreeData,
  roleMenuTreeDataadd
} from "@/api/home/Multisite";
import { other } from "@/api/interface";
// import { useHandleData } from "@/hooks/useHandleData";
import TreeFilter from "@/components/TreeFilter/index.vue";

import { FormInstance } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const supertype = ref(route.query.type);
interface FormState {
  roleName: string;
  roleKey: string;
  roleSort: string;
  status: boolean;
  remark: string;
  departmentId: string[];
}
const numberValidateForm: FormState = reactive({
  roleName: "",
  roleKey: "",
  roleSort: "",
  status: true,
  remark: "",
  departmentId: []
  // menuIds: {
  //   label: "name",
  //   children: "zones"
  // }
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // formEl.validate(async valid => {
  //   if (valid) {
  //     if (route.query.type == "角色新增") {
  //       let obj = {
  //         roleName: numberValidateForm.roleName,
  //         roleKey: numberValidateForm.roleKey,
  //         roleSort: numberValidateForm.roleSort,
  //         status: numberValidateForm.status ? 0 : 1,
  //         remark: numberValidateForm.remark,
  //         menuIds: numberValidateForm.departmentId.toString()
  //       };
  //       const { data } = await platformroleadd(obj);
  //       console.log(data);
  //     } else {
  //       let obj = {
  //         roleName: numberValidateForm.roleName,
  //         roleKey: numberValidateForm.roleKey,
  //         roleSort: numberValidateForm.roleSort,
  //         status: numberValidateForm.status ? 0 : 1,
  //         remark: numberValidateForm.remark,
  //         menuIds: numberValidateForm.departmentId.toString(),
  //         id: route.query.id
  //       };
  //       const { data } = await platformroleedit(obj);
  //       console.log(data);
  //     }
  //     router.back();
  //   } else {
  //     return false;
  //   }
  // });
  formEl.validate(async valid => {
    if (valid) {
      // Common object structure
      const obj = {
        roleName: numberValidateForm.roleName,
        roleKey: numberValidateForm.roleKey,
        roleSort: numberValidateForm.roleSort,
        status: numberValidateForm.status ? 0 : 1,
        remark: numberValidateForm.remark,
        menuIds: numberValidateForm.departmentId.toString(),
        ...(route.query.type === "角色编辑" && { id: route.query.id }) // Conditionally add ID for editing
      };

      try {
        let responseData;

        if (route.query.type === "角色新增") {
          responseData = await platformroleadd(obj);
        } else {
          responseData = await platformroleedit(obj);
        }

        console.log(responseData.data);
        router.back(); // Navigate back after success
      } catch (error) {
        console.error("Submission error:", error);
      }
    } else {
      console.log("Validation failed!");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/role/index");
};
const yonghueditdata = ref();
const getghuedit = async () => {
  const { data } = await platformshuRoleedit(route.query.id);
  yonghueditdata.value = data;
  numberValidateForm.roleName = yonghueditdata.value.role.roleName;
  numberValidateForm.roleKey = yonghueditdata.value.role.roleKey;
  numberValidateForm.roleSort = yonghueditdata.value.role.roleSort;
  numberValidateForm.status = yonghueditdata.value.role.status == 0 ? true : false;
  numberValidateForm.remark = yonghueditdata.value.role.remark;
};
// 懒加载
const TreeDatalist = ref();
const onBeforeMount = async () => {
  const { data } = await roleMenuTreeData(route.query.id);
  data.forEach(item => {
    if (item.checked) {
      numberValidateForm.departmentId.push(item.id);
    }
  });
  TreeDatalist.value = buildTree(data);
};
const onBeforeMountadd = async () => {
  const { data } = await roleMenuTreeDataadd();

  TreeDatalist.value = buildTree(data);
};
const buildTree = (data: other.tableData1[]) => {
  const tree: other.tableData1[] = [];
  const map: { [key: string]: other.tableData1 } = {};

  // 创建一个map以便快速找到item
  data.forEach((item: other.tableData1) => {
    map[item.id] = { ...item, children: [] };
  });

  data.forEach((item: { pId: string; id: string | number }) => {
    if (item.pId === "0") {
      // 根节点，假设根节点的 pId 是空字符串或者其他标识
      tree.push(map[item.id]);
    } else {
      // 子节点
      if (map[item.pId]) {
        map[item.pId].children.push(map[item.id]);
      }
    }
  });

  return tree;
};
onMounted(() => {
  if (route.query.type == "角色编辑") {
    getghuedit();
    onBeforeMount();
  } else {
    onBeforeMountadd();
  }
});

const changeTreeFilter = (val: string[]) => {
  numberValidateForm.departmentId = val;
};
</script>
<style scoped lang="scss">
@import "./addition.scss";
</style>
