<template>
  <div class="tenant">
    <byTable
      :hideTable="true"
      :hidePagination="true"
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :action-list="[
        {
          text: '添加机构',
          action: () => openModal(),
        },
      ]"
      @get-list="getList">
    </byTable>
    <div style="padding: 0 20px 20px 20px; background-color: white">
      <el-table
        v-loading="loading"
        :data="sourceList.data"
        row-key="deptId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all>
        <el-table-column prop="deptName" label="机构名称" min-width="260" />
        <el-table-column prop="type" label="机构类型" width="100">
          <template #default="{ row }">
            <span>{{ dictValueLabel(row.type, typeList) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderNum" label="排序" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="{ row }">
            <span>{{ row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="{ row }">
            <el-button link type="primary" @click="getDtl(row)">修改</el-button>
            <el-button link type="primary" @click="openModal(row.deptId)">添加子项</el-button>
            <el-button v-if="row.parentId != 0" link type="primary" @click="listDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="modalType == 'add' ? '添加机构' : '编辑机构'" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #parentId>
          <div style="width: 100%">
            <el-tree-select
              v-model="formData.data.parentId"
              :data="sourceList.data"
              check-strictly
              :render-after-expand="false"
              node-key="deptId"
              :props="defaultProps" />
          </div>
        </template>
        <template #orderNum>
          <div style="width: 100%">
            <el-input-number
              v-model="formData.data.orderNum"
              placeholder="请输入排序"
              style="width: 100%"
              :precision="0"
              :controls="false"
              :min="0"
              :max="99999" />
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const defaultProps = {
  children: "children",
  label: "deptName",
};
const userList = ref([]);
const typeList = ref([
  {
    label: "公司",
    value: 0,
  },
  {
    label: "业务中心",
    value: 1,
  },
  {
    label: "部门",
    value: 2,
  },
  {
    label: "组",
    value: 3,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 9999,
    keyword: "",
    tenantId: useUserStore().user.tenantId,
  },
});
const loading = ref(false);
const config = computed(() => {
  return [];
});
const getDict = () => {
  proxy.get("/tenantUser/list", { pageNum: 1, pageSize: 10000, tenantId: useUserStore().user.tenantId }).then((res) => {
    userList.value = res.rows.map((item) => {
      return {
        label: item.nickName,
        value: item.userId,
      };
    });
  });
};
const getList = async (req) => {
  if (req) {
    req.deptName = req.keyword;
  }
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.get("/tenantDept/list", sourceList.value.pagination).then((res) => {
    sourceList.value.data = proxy.handleTree(res.data, "deptId");
    console.log(sourceList.value.data);
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    {
      type: "slot",
      prop: "parentId",
      slotName: "parentId",
      label: "上级机构",
    },
    {
      type: "input",
      prop: "deptName",
      label: "机构名称",
    },
    {
      type: "select",
      prop: "type",
      label: "机构类型",
      data: typeList.value,
    },
    {
      type: "select",
      prop: "leaderId",
      label: "负责人",
      data: userList.value,
      itemWidth: 50,
    },
    {
      type: "select",
      prop: "directorId",
      label: "总监",
      data: userList.value,
      itemWidth: 50,
    },
    {
      type: "slot",
      prop: "orderNum",
      slotName: "orderNum",
      label: "部门排序",
    },
  ];
});
const rules = ref({
  parentId: [{ required: true, message: "请选择上级机构", trigger: "change" }],
  deptName: [{ required: true, message: "请输入机构名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择机构类型", trigger: "change" }],
  orderNum: [{ required: true, message: "请输入部门排序", trigger: "blur" }],
});
const openModal = (val) => {
  modalType.value = "add";
  formData.data = {
    parentId: val || "",
    tenantId: useUserStore().user.tenantId,
  };
  loadingDialog.value = false;
  dialogVisible.value = true;
};
const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    const method = modalType.value == "add" ? "POST" : "PUT";
    if (!formData.data.parentId) formData.data.parentId = 0;
    proxy.post("/tenantDept", formData.data, method).then(() => {
      ElMessage({
        message: modalType.value == "add" ? "添加成功" : "编辑成功",
        type: "success",
      });
      dialogVisible.value = false;
      getList();
    });
  });
};
const listDelete = (row) => {
  ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    proxy.post("/tenantDept/" + row.deptId, {}, "delete").then((res) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getList();
    });
  });
};
const getDtl = (row) => {
  formData.data = { ...row };
  modalType.value = "edit";
  dialogVisible.value = true;
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
