<template>
  <div>
    <div class="titleBox">
      <div class="title">部门管理</div>
      <div class="btnBox">
        <el-button type="primary" @click="addItemMenu">
          <el-icon><CirclePlus /></el-icon>
          <span>新增</span>
        </el-button>
      </div>
    </div>
    <div class="searchBox" ref="searchBox">
      <el-form :model="listQuery" :inline="true">
        <el-form-item label="部门名称">
          <el-input
            placeholder="请输入部门名称"
            v-model="listQuery.deptname"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleFilter">查询</el-button>
          <el-button @click="reset()"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tabBox">
      <el-table
        :data="tableData"
        border
        row-key="orgCode"
        :tree-props="{ children: 'childDeptList', hasChildren: 'hasChildren' }"
        style="width: 100%"
        :height="tableHeight"
        :key="keyCount"
        lazy
        :load="depLoad"
      >
        <el-table-column
          sortable
          prop="orgName"
          label="部门名称"
          show-overflow-tooltip
          width="320"
        >
          <template #default="{ row }">
            {{ row.orgName ? row.orgName : row.orgJc }}
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="orgType"
          label="部门类型"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_BMLX" :value="row.orgType" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="orgLevel"
          label="部门等级"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <dict-tag :options="D_BZ_BMDJ" :value="row.orgLevel" :tag="false" />
          </template>
        </el-table-column>
        <el-table-column
          sortable
          prop="linkTel"
          label="部门电话"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>

        <el-table-column
          sortable
          prop="linkManTel"
          label="部门联系人电话"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          sortable
          prop="linkMan"
          label="部门联系人"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <!-- <el-table-column prop="qxbs" label="权限标识" align="center" width="140px"></el-table-column> -->
        <el-table-column label="操作" align="center" fixed="right" width="320">
          <template #default="{ row }">
            <el-button @click="update(row)" size="small">编辑</el-button>
            <el-button @click="addItemMenu(row)" size="small"
              >添加下级</el-button
            >
            <el-button @click="assignRoles(row)" size="small"
              >绑定角色</el-button
            >
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              title="确定要删除?"
              @confirm="delDictItem(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <RolesDialog
      v-model="roleDialogVisible"
      :deptId="currentDeptId"
      @updateRole="handleFilter"
    ></RolesDialog>
    <div v-if="dialogFormVisible" class="dialog">
      <div class="head_box">
        <span class="title">{{ isEdit ? "修改" : "新增" }}</span>
        <div>
          <!-- 修改 -->
          <el-button
            v-if="isEdit"
            type="primary"
            size="small"
            @click="onSave"
            :loading="buttonLoading"
            >保存</el-button
          >
          <!-- 新增 -->
          <el-button
            v-else
            type="primary"
            size="small"
            @click="onAdd"
            :loading="buttonLoading"
            >保存</el-button
          >
          <el-button size="small" @click="closeDialog">关闭</el-button>
        </div>
      </div>
      <el-form
        class="mosty-from-wrap"
        ref="editRef"
        :inline="true"
        label-position="top"
        :model="dialogForm"
      >
        <el-form-item
          label="部门名称"
          :rules="[{ required: true, message: '请填写部门名称' }]"
          prop="orgName"
          label-width="140px"
        >
          <el-input
            placeholder="请填写部门名称"
            v-model="dialogForm.orgName"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门全称"
          show-word-limit
          maxlength="30"
          prop="orgQc"
          required
          label-width="140px"
        >
          <el-input
            placeholder="请填写部门全称"
            v-model="dialogForm.orgQc"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门简称"
          :rules="[{ required: true, message: '请填写部门简称' }]"
          prop="orgJc"
          required
          label-width="140px"
        >
          <el-input
            placeholder="请填写部门简称"
            v-model="dialogForm.orgJc"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门类型"
          :rules="[{ required: true, message: '请选择部门类型' }]"
          prop="orgType"
          required
          label-width="140px"
        >
          <!-- <el-input
            show-word-limit
            maxlength="30"
            v-model="dialogForm.orgType"
          ></el-input> -->
          <el-select
            style="width: 100%"
            v-model="dialogForm.orgType"
            class="m-4"
            placeholder="请选择部门类型"
          >
            <el-option
              v-for="item in D_BZ_BMLX"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门代码"
          :rules="[{ required: true, message: '请填写部门代码' }]"
          prop="orgCode"
          required
          label-width="140px"
        >
          <el-input
            placeholder="请填写部门代码"
            show-word-limit
            maxlength="30"
            v-model="dialogForm.orgCode"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门等级"
          :rules="[{ required: true, message: '请选择部门等级' }]"
          prop="orgLevel"
          required
          label-width="140px"
        >
          <el-select
            style="width: 100%"
            v-model="dialogForm.orgLevel"
            class="m-4"
            placeholder="请选择部门等级"
          >
            <el-option
              v-for="dict in D_BZ_BMDJ"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门顺序号" label-width="140px">
          <el-input-number
            style="width: 100%"
            v-model="dialogForm.orgNo"
            class="mx-4"
            placeholder="请填写部门顺序号"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="部门电话" prop="linkTel" label-width="140px">
          <el-input
            v-model="dialogForm.linkTel"
            placeholder="请填写部门电话"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门业务类型"
          :rules="[{ required: true, message: '请选择部门业务类型' }]"
          prop="orgBizType"
          required
          label-width="140px"
        >
          <!-- <el-input
            show-word-limit
            maxlength="30"
            v-model="dialogForm.orgBizType"
          ></el-input> -->
          <el-select
            style="width: 100%"
            v-model="dialogForm.orgBizType"
            class="m-4"
            placeholder="请选择部门业务类型"
          >
            <el-option
              v-for="item in D_BZ_BMYWLX"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门联系人电话" label-width="140px">
          <el-input
            placeholder="请填写部门联系人电话"
            v-model="dialogForm.linkManTel"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门联系人" label-width="140px">
          <el-input
            show-word-limit
            placeholder="请填写部门联系人"
            maxlength="30"
            v-model="dialogForm.linkMan"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门邮箱" label-width="140px">
          <el-input
            v-model="dialogForm.email"
            placeholder="请填写部门邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门名称拼音" label-width="140px">
          <el-input
            show-word-limit
            maxlength="30"
            placeholder="请填写部门名称拼音"
            v-model="dialogForm.bmpyszm"
          ></el-input>
        </el-form-item>

        <el-form-item label="部门主页" label-width="140px">
          <el-input
            show-word-limit
            placeholder="请填写部门主页"
            maxlength="50"
            v-model="dialogForm.webUrl"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门所属行政区划" label-width="140px">
          <el-input
            show-word-limit
            placeholder="请填写部门所属行政区划"
            maxlength="50"
            v-model="dialogForm.xzqh"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="状态" label-width="140px">
          <el-select v-model="dialogForm.zdywlb" placeholder="请选择业务类别">
            <el-option label="正常" value="0"></el-option>
            <el-option label="注销" value="1"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item style="width: 100%" label="部门地址" label-width="140px">
          <el-input
            show-word-limit
            placeholder="请填写部门地址"
            maxlength="200"
            v-model="dialogForm.address"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item style="width: 100%" label="备注" label-width="140px">
          <el-input
            v-model="dialogForm.bz"
            show-word-limit
            maxlength="200"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import RolesDialog from "./components/roles.vue";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, getCurrentInstance, onUnmounted } from "vue";
import {
  addSysDept,
  deleteSysDept,
  updateSysDept,
  selectDeptPage
} from "@/api/user-manage";
import { useRouter, useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const { D_BZ_BMYWLX, D_BZ_BMDJ, D_BZ_BMLX } = proxy.$dict(
  "D_BZ_BMYWLX",
  "D_BZ_BMDJ",
  "D_BZ_BMLX"
);
const keyCount = ref(0); //tabel组件刷新值
const searchBox = ref(null); // 搜索盒子
const tableHeight = ref(); // 表格高度
const route = useRoute();
//查询参数
const total = ref(0);
const currentRow = ref({});
const listQuery = ref({
  deptname: "",
  deptcode: ""
});
const topParentId = ref("");
const id = ref("");
const zdlx = ref();
const buttonLoading = ref(false);
const isEdit = ref(true);
const dialogForm = ref({
  orgNo: 1
});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
//动态加载部门数据
function depLoad(row, treeNode, resolve) {
  listQuery.value.parentid = row.id;
  selectDeptPage(listQuery.value).then((res) => {
    resolve(res);
  });
}
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  const res = await selectDeptPage(params);
  tableData.value = res;
  total.value = Number(res.total);
};
const reset = () => {
  tableData.value = [];
  listQuery.value = {
    deptname: "",
    deptcode: ""
  };
  getListData();
};
const handleFilter = () => {
  getListData();
};
getListData();

// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  getListData();
};

/**修改字典 */
const update = (row) => {
  isEdit.value = true;
  dialogForm.value = { ...row };
  // dialogForm.value.linkManTel = parseInt(dialogForm.value.linkManTel);
  // dialogForm.value.linkTel = parseInt(dialogForm.value.linkTel);
  dialogFormVisible.value = true;
};

function isNull(data) {
  if (!data) return true;
  if (JSON.stringify(data) === "{}") return true;
  if (JSON.stringify(data) === "[]") return true;
  return false;
}
const addItemMenu = (row) => {
  id.value = isNull(row) ? topParentId.value : row.id;
  isEdit.value = false;
  dialogForm.value = {
    orgNo: 1
  };
  dialogFormVisible.value = true;
};
const onSave = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      updateSysDept({
        ...dialogForm.value
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("修改成功");
          reset();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};
const editRef = ref(null);
const onAdd = () => {
  editRef.value.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      addSysDept({
        ...dialogForm.value,
        parentId: id.value
      })
        .then((res) => {
          dialogFormVisible.value = false;
          ElMessage.success("新增成功");
          reset();
        })
        .finally(() => {
          buttonLoading.value = false;
        });
    } else {
      ElMessage.error("请填写完必填项!");
      return false;
    }
  });
};

const delDictItem = (row) => {
  deleteSysDept({
    id: Number(row.id)
  }).then((res) => {
    ElMessage.success("删除成功");
    reset();
  });
};

const closeDialog = () => {
  dialogForm.value = {};
  dialogFormVisible.value = false;
};

const toGoPage = (row) => {
  router.push("/user/role?zdbh=" + row.zdbh);
};

//分配角色
const currentDeptId = ref("");
const roleDialogVisible = ref(false);
const assignRoles = (row) => {
  roleDialogVisible.value = true;
  currentDeptId.value = row.id;
};

//分配用户
const router = useRouter();
const allocationUser = (row) => {
  router.push(`/user/deptAllocationUser/${row.id}`);
};
// 表格高度计算
const tabHeightFn = () => {
  tableHeight.value = window.innerHeight - searchBox.value.offsetHeight - 210;
};
onMounted(() => {
  tabHeightFn();
  window.onresize = function () {
    tabHeightFn();
  };
  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "@/assets/css/element-plus.scss";
.user-manage-container {
  .table-header-wrap {
    margin-bottom: 22px;
  }

  ::v-deep .avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }

  ::v-deep .el-tag {
    margin-right: 6px;
  }

  .pagination {
    margin-top: 20px;
  }

  .twoLine {
    display: flex;
    align-items: flex-start;
    flex-flow: wrap;

    .el-form-item {
      width: 380px;
    }
  }
}
</style>
