<template>
  <div>
    <div class="card content-box">
      <div class="name">{{ supertype }}</div>
      <el-divider />
      <div class="user_box">
        <div class="user_left">
          <el-form ref="formRef" :model="numberValidateForm" label-width="auto" class="demo-ruleForm">
            <div class="elform">
              <el-form-item label="上级公司/部门：" prop="parentId" :rules="[{ required: true, message: '请选择公司/部门名称' }]">
                <!-- <el-input
                  v-model.number="numberValidateForm.parentId"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入角色名称"
                  autocomplete="off"
                /> -->
                <el-cascader
                  style="width: 300px"
                  v-model="numberValidateForm.parentId"
                  :options="tableData[0].children"
                  :show-all-levels="false"
                  placeholder="创建公司不需要选择上级"
                  :props="{ checkStrictly: true, label: 'deptName', value: 'id', children: 'children' }"
                  @change="handleChange"
                />
              </el-form-item>

              <el-form-item label="公司/部门名称：" prop="deptName" :rules="[{ required: true, message: '请输入公司/部门名称' }]">
                <el-input
                  v-model="numberValidateForm.deptName"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入公司/部门名称"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="显示排序：" prop="orderNum" :rules="[{ required: true, message: '请输入显示排序' }]">
                <el-input
                  v-model.number="numberValidateForm.orderNum"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入显示排序"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="负责人：">
                <el-input
                  v-model="numberValidateForm.leader"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入负责人"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="联系电话：">
                <el-input
                  v-model.number="numberValidateForm.phone"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入联系电话"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="邮箱：">
                <el-input
                  v-model="numberValidateForm.email"
                  style="width: 300px"
                  size="large"
                  type="text"
                  placeholder="请输入邮箱"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="elform">
              <el-form-item label="用户性别：">
                <el-radio-group v-model="numberValidateForm.status">
                  <el-radio value="0">正常</el-radio>
                  <el-radio value="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </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 { platformdeptlist, platformdeptadd, platformdeptedit, platformdeptendit } from "@/api/home/Multisite";
import { other } from "@/api/interface";
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);

const numberValidateForm = reactive({
  id: route.query.id,
  parentId: "",
  deptName: "",
  orderNum: "",
  leader: "",
  phone: "",
  email: "",
  status: "0"
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  if (numberValidateForm.parentId === "") {
    numberValidateForm.parentId = tableData.value[0].id;
  }

  try {
    const valid = await formEl.validate();

    if (valid) {
      let responseData;

      if (route.query.type === "部门新增") {
        responseData = await platformdeptadd(numberValidateForm);
      } else {
        responseData = await platformdeptedit(numberValidateForm);
      }

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

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/department/index");
};
const tableData = ref();

const handleChange = async (val: any) => {
  console.log(val);
  numberValidateForm.parentId = val[numberValidateForm.parentId.length - 1].toString();
};
const getplatformuserlist = async () => {
  let obj = {};
  const { data } = await platformdeptlist(obj);
  // tableData.value = data;
  tableData.value = buildTree(data);
  console.log(tableData.value);
};
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: { parentId: string; id: string | number }) => {
    if (item.parentId === "0") {
      // 根节点，假设根节点的 parentId 是空字符串或者其他标识
      tree.push(map[item.id]);
    } else {
      // 子节点
      if (map[item.parentId]) {
        map[item.parentId].children.push(map[item.id]);
      }
    }
  });

  return tree;
};
const yonghueditdata = ref();
const getghuedit = async () => {
  const { data } = await platformdeptendit(route.query.id);
  yonghueditdata.value = data;
  console.log(yonghueditdata.value);
  numberValidateForm.parentId = yonghueditdata.value.dept.parentId;
  numberValidateForm.deptName = yonghueditdata.value.dept.deptName;
  numberValidateForm.orderNum = yonghueditdata.value.dept.orderNum;
  numberValidateForm.leader = yonghueditdata.value.dept.leader;
  numberValidateForm.phone = yonghueditdata.value.dept.phone;
  numberValidateForm.email = yonghueditdata.value.dept.email;
  numberValidateForm.status = yonghueditdata.value.dept.status;
};
onMounted(() => {
  getplatformuserlist();
  if (route.query.type == "部门编辑") {
    getghuedit();
  }
});
</script>
<style scoped lang="scss">
@import "./addition.scss";
</style>
<!--  -->
