<template>
  <el-card>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="form"
      label-width="110px"
      label-position="left"
    >
      <el-form-item prop="roleName" label="职位名称">
        <el-input style="width: 280px" v-model="ruleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item prop="deptId" label="部门">
        <el-select
          style="width: 280px"
          v-model="ruleForm.deptId"
          placeholder="请选择部门"
        >
          <el-option
            v-for="item in departmentSelect"
            :key="item"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="mt30 p30">
    <h4 class="mb30">权限设置</h4>
    <el-tree
      ref="treeRef"
      :data="basePermissionData"
      show-checkbox
      default-expand-all
      node-key="code"
      highlight-current
      :props="defaultProps"
      :default-checked-keys="checkedNodes"
      style="display: flex; justify-content: space-between"
    />
    <div class="df aic jcfe mt50">
      <el-button type="primary" @click="addRole">{{
        roleId ? "修改员工" : "添加职位"
      }}</el-button>
    </div>
  </el-card>
</template>

<script setup>
import api from "../../apis/fetch";
import store from "../../store";
import router from "../../router";
import { ref, onMounted, reactive, computed } from "vue";
import { ElNotification, ElMessageBox } from "element-plus";
import { mapGetters } from "vuex";
import { useRoute } from "vue-router";

const route = useRoute();

let loginAccountId = ref(0);
let form = ref(null);
let ruleForm = ref({
  roleName: "",
  deptId: "",
});
const rules = reactive({
  roleName: [
    {
      required: true,
      message: "请填角色名称",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "请选择部门",
      trigger: "blur",
    },
  ],
});
let roleId = ref("");
let treeRef = ref(null);
const defaultProps = {
  children: "children",
  label: "label",
};

let basePermissionData = computed(() => store.state.basePermissionData);
let baseParentNodes = computed(() => store.state.baseParentNodes);
let checkedNodes = ref([]);

async function getRoleDetail(roleId) {
  let res = await api.getRoleDetail({
    loginAccountId: loginAccountId.value,
    roleId,
  });
  if (res.data.status == 0) {
    let {
      code,
      departmentId,
      roleName,
      permission,
      cargoLimit,
      cargoOwnerLimit,
    } = res.data.result;
    ruleForm.value = {
      roleName,
      deptId: departmentId,
    };
    let c = cargoLimit.split(",");
    let cargoLimitArr = [];
    for (let i of c) {
      cargoLimitArr.push(`CARGO_${i}`);
    }
    let p = cargoOwnerLimit.split(",");
    let cargoOwnerArr = [];
    for (let i of p) {
      cargoOwnerArr.push(`CARGOOWNER_${i}`);
    }
    let arr = permission.split(",");
    baseParentNodes.value.forEach((item) => {
      for (let i of arr) {
        if (i == item) {
          let index = arr.indexOf(i);
          arr.splice(index, 1);
        }
      }
    });
    checkedNodes.value = [...arr, ...cargoLimitArr, ...cargoOwnerArr];
  }
}

async function addRole() {
  let fullChecked = treeRef.value.getCheckedNodes();
  let halfCHecked = treeRef.value.getHalfCheckedNodes();
  let permissionCodes = [];
  for (let i of fullChecked) {
    permissionCodes.push(i.code);
  }
  for (let i of halfCHecked) {
    permissionCodes.push(i.code);
  }

  let postData = {
    loginAccountId: loginAccountId.value,
    ...ruleForm.value,
    permissionCodes: permissionCodes.join(","),
  };
  if (roleId.value) {
    postData.roleId = roleId.value;
  }
  let res = await api[roleId.value ? "updateRole" : "addRole"](postData);
  if (res.data.status == 0) {
    ElNotification({
      title: "成功",
      duration: 1500,
      message: res.data.msg,
      type: "success",
    });
    store.dispatch("GetBasePermissionData", localStorage.loginAccountId);
    store.dispatch("GetUserPermission", localStorage.loginAccountId);
    router.replace("/authManage/roleList");
  } else {
    console.log(res);
    ElNotification({
      title: "失败",
      duration: 1500,
      message: res.data.msg,
      type: "error",
    });
  }
}

let departmentSelect = ref([]);
async function getDepartmentSelect() {
  let res = await api.getDepartmentSelect({
    loginAccountId: loginAccountId.value,
  });
  departmentSelect.value = res.data.result;
}

onMounted(() => {
  loginAccountId.value = localStorage.loginAccountId;
  getDepartmentSelect();
  store.dispatch("GetBasePermissionData", localStorage.loginAccountId);

  let id = route.query.roleId;
  if (id) {
    getRoleDetail(id);
    roleId.value = id;
    store.commit("changefirstTitle", "修改员工");
  }
});
</script>

<style scoped>
.seach-btn {
  display: inline-block;
  width: 60px;
  height: 38px;
  background: #0094fe;
  border-radius: 2px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
  line-height: 38px;
  margin-left: 10px;
  cursor: pointer;
}
</style>