<template>
  <el-form
    :label-position="'right'"
    label-width="120px"
    :model="orgAccountForm"
    :rules="orgAccountFormRules"
    ref="orgformAccountRef"
    style="max-width: 66%">
    <el-form-item label="所属组织" prop="organization_id">
      <el-tree-select
        v-model="orgAccountForm.organization_id"
        :data="orgData"
        :props="treeProps"
        :render-after-expand="false"
        :disabled="true"
        style="width: 100%" />
      <!-- <el-input v-model="orgAccountForm.organization_id" /> -->
    </el-form-item>
    <el-form-item label="角色" prop="select_role" v-if="!formType">
      <el-select
        v-model="orgAccountForm.select_role"
        multiple
        placeholder="请选择角色"
        :disabled="true"
        style="width: 100%">
        <el-option v-for="item in roleList" :key="item.role_id" :label="item.role_name" :value="item.role_id" />
      </el-select>
    </el-form-item>
    <el-form-item label="头像" prop="logo">
      <bg-upload-image
        v-model="orgAccountForm.logo"
        :showTips="true"
        :limit="1"
        :fileSize="500"
        :fileSizeUnit="'KB'"
        listType="picture-card"
        :accept="['.jpg', '.jpeg', '.png']"
        customTips="请选择图片上传：大小120 * 120像素支持jpg、png等格式，图片需小于500KB"></bg-upload-image>
    </el-form-item>
    <el-form-item label="账号" prop="system_account">
      <el-input v-model="orgAccountForm.system_account" />
    </el-form-item>
    <el-form-item label="手机号" prop="contact_phone">
      <el-input v-model="orgAccountForm.contact_phone" />
    </el-form-item>
    <el-form-item label="密码" prop="password" v-if="!formType">
      <el-input type="password" v-model="orgAccountForm.password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password" v-if="!formType">
      <el-input type="password" v-model="orgAccountForm.confirm_password" />
    </el-form-item>

    <el-form-item label="是否启用" prop="state">
      <bg-switch :labels="['否', '是']" :values="[0, 1]" v-model="orgAccountForm.state"></bg-switch>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeMount } from "vue";
import { useRoute } from "vue-router";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
const route = useRoute();
const props = defineProps({
  formType: {
    type: Boolean,
    default: false, //false 新增 true 编辑
  },
  id: {
    type: String,
    default: "",
  },
});
const orgAccountForm = reactive({
  organization_id: "",
  select_role: "",
  logo: [],
  system_account: "",
  contact_phone: "",
  password: "",
  confirm_password: "",
  state: 1,
});

const validatePass = (rule, value, callback) => {
  if (value !== orgAccountForm.password) {
    callback(new Error("密码输入不一致"));
  } else {
    callback();
  }
};

const validateSystemAccount = (rule, value, callback) => {
  let reg = /^[a-zA-Z0-9]+$/;
  if (!reg.test(value)) {
    callback(new Error("只能输入字母和数字"));
  } else {
    let params = null;
    if (props.id) {
      params = { id: parseInt(props.id), system_account: value };
    } else {
      params = { system_account: value };
    }

    axios.post(`/apaas/system/v5/user/check/account`, params).then((res) => {
      if (res.data.code == 200) {
        callback();
      } else {
        callback(new Error(res.data.data));
      }
    });
  }
};

const checkPhone = (rule, value, callback) => {
  var phone_ruler = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
  setTimeout(() => {
    if (!phone_ruler.test(value) && value.length !== 0) {
      callback(new Error("请输入正确的手机号码"));
    } else {
      callback();
    }
  });
};

const checkPhoneRepet = (rule, value, callback) => {
  let params = null;
  if (props.id) {
    params = { id: parseInt(props.id), contact_phone: value };
  } else {
    params = { id: 0, contact_phone: value };
  }

  axios.post(`/apaas/system/v5/org/check`, params).then((res) => {
    if (res.data.code == 200) {
      callback();
    } else {
      callback(new Error(res.data.data));
    }
  });
};

const orgAccountFormRules = reactive({
  organization_id: [{ required: true, message: "请选择组织", trigger: "blur" }],
  select_role: [{ required: true, message: "请选择角色", trigger: "blur" }],
  system_account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 4, message: "帐号长度不得低于4个字符", trigger: "blur" },
    { max: 20, message: "帐号最大长度为20个字符", trigger: "blur" },
    { validator: validateSystemAccount, trigger: "blur" },
  ],
  contact_phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: checkPhone, trigger: "blur" },
    { validator: checkPhoneRepet, trigger: "blur" },
  ],

  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, message: "密码长度不得低于8位", trigger: "blur" },
  ],
  confirm_password: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
});

const orgformAccountRef = ref(null);
const emit = defineEmits(["action"]);
const roleList = ref([]);

const submitForm = async () => {
  if (!orgformAccountRef) return;
  await orgformAccountRef.value.validate((valid, fields) => {
    if (valid) {
      emit("action", orgAccountForm);
    } else {
      emit("action", null);
    }
  });
};

const clearForm = () => {
  if (!orgformAccountRef) return;
  orgformAccountRef.value.resetFields();
  orgAccountForm.select_role = [roleList.value[0].role_id];
};

const setForm = (data) => {
  Object.assign(orgAccountForm, data);
};

const orgData = ref([]);
const treeProps = {
  label: "name",
  children: "Child",
  value: "organization_id",
};
const getOrgTree = () => {
  axios.get(`/apaas/system/v5/org/tree`).then((res) => {
    if (res.data.code == 200) {
      orgData.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const getRoleList = () => {
  axios.get(`/apaas/system/v5/org/select/role?is_admin=2`).then((res) => {
    if (res.data.code == 200) {
      roleList.value = res.data.data;
      orgAccountForm.select_role = [roleList.value[0].role_id];
    } else {
    }
  });
};

onBeforeMount(() => {
  getOrgTree();
  getRoleList();
  orgAccountForm.organization_id = route.query.orgId;
});

onMounted(() => {});

defineExpose({ submitForm, clearForm, setForm });
</script>
