<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: any, value: any, callback: any) => {
                      if (value.length == 0) {
                        callback(new Error('请分配电站!'));
                      } else {
                        if (value.length == 1 && value[0] == '') {
                          callback(new Error('请分配电站!'));
                        } else {
                          callback();
                        }
                      }
                    },
                    trigger: 'change'
                  }
                ]"
              >
                <div class="user_right">
                  <TreeFilter
                    multiple
                    title="电站权限"
                    label="powerName"
                    :data="TreeDatalist"
                    id="powerId"
                    :default-value="numberValidateForm.departmentId"
                    @change="changeTreeFilter"
                  />
                </div>
              </el-form-item>
              <div class="user_left">
                <div class="elform">
                  <el-form-item label="用户名称：" prop="userName" :rules="[{ required: true, message: '请输入用户名称' }]">
                    <el-input
                      v-model.number="numberValidateForm.userName"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="请输入用户名称"
                      autocomplete="off"
                    />
                  </el-form-item>
                  <el-form-item label="归属部门：" prop="deptId">
                    <!-- <el-input
                      v-model.number="numberValidateForm.age"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="归属部门"
                      autocomplete="off"
                    /> -->
                    <!-- <el-select v-model="numberValidateForm.deptId" placeholder="请选择部门" size="large" style="width: 300px">
                      <el-option v-for="item in treeData" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select> -->
                    <el-cascader
                      style="width: 300px"
                      v-model="numberValidateForm.deptId"
                      :options="treeData[0].children"
                      :show-all-levels="false"
                      :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'children' }"
                      @change="handleChange"
                    />
                  </el-form-item>
                </div>

                <div class="elform">
                  <el-form-item
                    label="手机号码："
                    prop="phonenumber"
                    :rules="[
                      { required: true, message: '请输入手机号码', trigger: 'blur' },
                      { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
                    ]"
                  >
                    <el-input
                      v-model.number="numberValidateForm.phonenumber"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="手机号码"
                    />
                  </el-form-item>
                  <el-form-item label="岗位：" prop="postIds">
                    <el-select
                      v-model="numberValidateForm.postIds"
                      placeholder="请选择部门"
                      size="large"
                      style="width: 300px"
                      multiple
                    >
                      <el-option v-for="item in platformData.post" :key="item.id" :label="item.postName" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </div>
                <div class="elform">
                  <el-form-item label="登录账号：" prop="loginName" :rules="[{ required: true, message: '请输入登录账号' }]">
                    <el-input
                      v-model="numberValidateForm.loginName"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="登录账号"
                    />
                  </el-form-item>
                  <el-form-item label="登录密码：" prop="password" :rules="[{ required: true, message: '请输入登录密码' }]">
                    <el-input
                      v-model="numberValidateForm.password"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="登录密码"
                      show-password
                      autocomplete="new-password"
                    />
                  </el-form-item>
                </div>

                <div class="elform">
                  <el-form-item
                    label="邮箱："
                    prop="email"
                    :rules="[
                      { required: true, message: '请输入邮箱', trigger: 'blur' },
                      {
                        pattern: /^([A-Za-z0-9_\-.])+@([A-Za-z0-9_\-.])+\.([A-Za-z]{2,4})$/,
                        message: '邮箱格式不正确',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input
                      v-model="numberValidateForm.email"
                      style="width: 300px"
                      size="large"
                      type="text"
                      placeholder="邮箱"
                    />
                  </el-form-item>

                  <el-form-item label="推送类型：" prop="postIds">
                    <el-select
                      v-model="numberValidateForm.emailType"
                      placeholder="选择推送模式"
                      style="width: 300px"
                      size="large"
                    >
                      <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </div>
                <div class="elform">
                  <el-form-item label="推送时间：">
                    <el-time-select
                      v-model="numberValidateForm.emailTypetime"
                      style="width: 300px"
                      start="00:00"
                      step="00:30"
                      end="24:00"
                      placeholder="推送时间"
                    />
                  </el-form-item>

                  <el-form-item label="角色：">
                    <el-radio-group style="width: 300px" v-model="numberValidateForm.roleIds[0]">
                      <el-radio v-for="item in platformData.role" :key="item.id" :value="item.id">{{ item.roleName }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="elform">
                  <el-form-item label="用户性别：">
                    <el-radio-group v-model="numberValidateForm.sex">
                      <el-radio value="0">男</el-radio>
                      <el-radio value="1">女</el-radio>
                    </el-radio-group>
                  </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: 1000px"
                      :rows="6"
                      type="textarea"
                      placeholder="请输入备注"
                    />
                  </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 {
  gettreeData,
  platformlist,
  platformadd,
  yonghuedit,
  getresetPwd,
  platformedit,
  selectTenantPower
  // selectPowerstation
} from "@/api/home/Multisite.js";
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { FormInstance } from "element-plus";
import { other } from "@/api/interface";

const router = useRouter();
const route = useRoute();
const formRef = ref<FormInstance>();
const supertype = ref(route.query.type);
interface FormData {
  userName: string;
  deptId: string;
  phonenumber: string;
  email: string;
  loginName: string;
  password: string;
  sex: string;
  status: boolean;
  postIds: string[]; // 修改为 string[]
  roleIds: string[]; // 假设 roleIds 也是 string[]
  remark: string;
  departmentId: string[];
  emailTypetime: string;
  emailType: string;
}

const numberValidateForm = reactive<FormData>({
  userName: "",
  deptId: "",
  phonenumber: "",
  email: "",
  loginName: "",
  password: "",
  sex: "",
  status: true,
  postIds: [],
  roleIds: [],
  remark: "",
  departmentId: [],
  emailTypetime: "",
  emailType: ""
});
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(formEl);
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      if (route.query.type == "用户新增") {
        const obj = {
          userName: numberValidateForm.userName,
          deptId: numberValidateForm.deptId,
          phonenumber: numberValidateForm.phonenumber,
          email: numberValidateForm.email,
          loginName: numberValidateForm.loginName,
          password: numberValidateForm.password,
          sex: numberValidateForm.sex,
          status: numberValidateForm.status ? 0 : 1,
          postIds: numberValidateForm.postIds.toString(),
          roleIds: numberValidateForm.roleIds.toString(),
          remark: numberValidateForm.remark,
          powerId: numberValidateForm.departmentId.toString(),
          sendTime: numberValidateForm.emailTypetime,
          emailType: numberValidateForm.emailType
        };

        const { data } = await platformadd(obj);
        // let objobj = {
        //   powerId: numberValidateForm.departmentId.toString()
        // };
        // const { data: res } = await savetenantpower(route.query.id, objobj);
        // console.log(res);

        console.log(data);
      } else {
        const obj = {
          userName: numberValidateForm.userName,
          deptId: numberValidateForm.deptId,
          phonenumber: numberValidateForm.phonenumber,
          email: numberValidateForm.email,
          loginName: numberValidateForm.loginName,
          // password: "",
          sex: numberValidateForm.sex,
          status: numberValidateForm.status ? 0 : 1,
          postIds: numberValidateForm.postIds.toString(),
          roleIds: numberValidateForm.roleIds.toString(),
          remark: numberValidateForm.remark,
          id: route.query.id,
          powerId: numberValidateForm.departmentId.toString(),
          sendTime: numberValidateForm.emailTypetime,
          emailType: numberValidateForm.emailType
        };

        const { data } = await platformedit(obj);
        console.log(data);
      }

      router.back();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
//
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/user/index");
};
const treeData = ref();
const department = async () => {
  const { data } = await gettreeData();
  // treeData.value = data;
  treeData.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;
};

const platformData = ref();
const getplatformlist = async () => {
  const { data } = await platformlist({});
  platformData.value = data;
  console.log(data);
};
const yonghueditdata = ref();

const options = ref();

const getghuedit = async () => {
  const { data } = await yonghuedit(route.query.id);
  yonghueditdata.value = data;
  numberValidateForm.userName = yonghueditdata.value.user.userName;

  numberValidateForm.deptId = yonghueditdata.value.user.deptId;
  numberValidateForm.phonenumber = yonghueditdata.value.user.phonenumber;
  numberValidateForm.email = yonghueditdata.value.user.email;
  numberValidateForm.loginName = yonghueditdata.value.user.loginName;
  numberValidateForm.password = yonghueditdata.value.user.password;
  numberValidateForm.sex = yonghueditdata.value.user.sex;
  numberValidateForm.status = yonghueditdata.value.user.status == 0 ? true : false;
  numberValidateForm.remark = yonghueditdata.value.user.remark;
  yonghueditdata.value.powerId.forEach((item: { powerId: string }) => {
    numberValidateForm.departmentId.push(item.powerId);
  });

  yonghueditdata.value.posts.forEach((role: { flag: any; id: string }) => {
    if (role.flag) {
      numberValidateForm.postIds.push(role.id);
    }
  });

  yonghueditdata.value.roles.forEach((role: { flag: any; id: string }) => {
    if (role.flag) {
      numberValidateForm.roleIds.push(role.id);
    }
  });
  if (yonghueditdata.value.user.roles[0].roleKey == 1) {
    options.value = [
      {
        value: "0",
        label: "暂不发送邮件"
      },
      {
        value: "1",
        label: "发送邮件"
      }
    ];
  } else {
    options.value = [
      {
        value: "0",
        label: "暂不发送邮件"
      },
      {
        value: "1",
        label: "详细邮件"
      },
      {
        value: "2",
        label: "简易邮件"
      }
    ];
  }
  numberValidateForm.emailTypetime = yonghueditdata.value.user.sendTime;
  numberValidateForm.emailType = yonghueditdata.value.user.emailType;
  getTreeDatalist();
};
const resetPwddata = ref();
const onresetPwd = async () => {
  const { data } = await getresetPwd(route.query.id);
  resetPwddata.value = data;
};
// 电站权限列表
const TreeDatalist = ref();
const getTreeDatalist = async () => {
  const { data } = await selectTenantPower({});
  console.log(data);

  TreeDatalist.value = data;
};
// 回显电站权限
// const TreeDatalists = ref();

// const ongetTreeDatalist = async () => {
//   const { data } = await selectPowerstation(route.query.id);
//   TreeDatalists.value = data;
//   TreeDatalists.value.forEach((item: { powerId: string }) => {
//     numberValidateForm.departmentId.push(item.powerId);
//   });
// };
const changeTreeFilter = (val: string[]) => {
  numberValidateForm.departmentId = val;
};

const handleChange = async (val: any) => {
  console.log(val);
  numberValidateForm.deptId = val[numberValidateForm.deptId.length - 1].toString();
};

onMounted(() => {
  if (route.query.type == "用户编辑") {
    // ongetTreeDatalist();
    getghuedit();
    onresetPwd();
  } else {
    getTreeDatalist();
  }
  department();
  getplatformlist();
});
</script>
<style scoped lang="scss">
@import "./addition.scss";
</style>
<!-- 
0.3225  918    296
0.7371  459   338
-->
