
<script lang="ts">
export default {
  name: 'dept'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import {
  getTreelist,
  addTreelist,
  updataTreelist,
  delTreelist,
  gettableData,
  deptIsVaild,
  reviseDepartment,
} from "@/api/dept";

import { useAppStore } from '@/store/modules/app';
//树形控件类型定义
interface Tree {
  [x: string]: any;
  label: string;
  children?: Tree[];
}
//搜索内容
const querystr = ref("");
// 左侧树
const treedata: any = ref([]);

const defaultProps = { label: "orgname" };
const handleNodeClick = (data: Tree) => {
  checkedtreeid.value = data.id;
  getData();
};
const infoForm = ref();
const causeForm = ref();
const treeRef = ref();
// 表格数组类型定义
const tableData = ref([]);
const checkedtreeid = ref("");
const loading = ref(false);
const treeloading = ref(false);
//新建部门数组
const info = ref({
  id: "",
  parentid: "",
  orgtype: "2",
  orgcode: "",
  orgname: "",
  manager: "",
  description: "",
  custom1: "",
});
//新建组织数组
const causeInfo = ref({
  id: "",
  parentid: "",
  orgtype: "2",
  orgcode: "",
  orgname: "",
  manager: "",
  description: "",
  custom1: "",
});
const title = ref("");
const dialogVisible = ref(false);
const dialogCause = ref(false);
//删除组织
const choosetreeid = ref("");
//获取组织树形信息
function getTree() {
  const params = {
    parentid: "0",
  };
  treeloading.value = true
  getTreelist(params).then((res: any) => {
    treedata.value = res;
    treeloading.value = false
    if (checkedtreeid.value == "") {
      checkedtreeid.value = res[0].id;
    }
    nextTick(() => {
      treeRef.value?.setCurrentKey(checkedtreeid.value);
    });
    getData();
  })
  .catch((error:any)=>{
    treeloading.value = false
  })
}
//获取表格类型
function getData() {
  const params = {
    id: checkedtreeid.value,
  };
  loading.value = true
  gettableData(params).then((res) => {
    tableData.value = res.data;
    loading.value = false
  });
}
const multipleSelection = ref([]);
//定义组织填写规则
const rules = reactive<FormRules>({
  orgname: [{ required: true, message: "请填写组织名称", trigger: "blur" }],
  manager: [{ required: true, message: "请填写组织负责人名称", trigger: "blur" }],
});
//定义部门填写规则
const moderules = reactive<FormRules>({
  orgname: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
  manager: [{ required: true, message: "请输入负责人", trigger: "blur" }],
});
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
//部门是否有效
function switchChange(row: any) {
  const elMessage = ref('')
  if (row.isvaild == '0') {
    elMessage.value = "确定设置该部门为无效吗？"
  } else if (row.isvaild == '1') {
    elMessage.value = "确定设置该部门为有效吗？"
  }
  ElMessageBox.confirm(elMessage.value, "提示信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let params = {
        isvaild: row.isvaild,
        id: row.id,
      };

      deptIsVaild(params).then((res) => {
        getData();
        ElMessage({
          type: "success",
          message: "改变成功",
        });
      });

    })
    .catch(() => {
      getData();
    });
}
//新建组织
function causeAdd() {
  title.value = "新增组织";
  dialogCause.value = true;
  const causeInfogase = ref({
    id: "",
    parentid: "",
    orgtype: "2",
    orgcode: "",
    orgname: "",
    manager: "",
    description: "",
    custom1: "",
  });
  causeInfo.value = causeInfogase.value;
}
//新键组织-保存
function editisrepetition(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {
      if (causeInfo.value.id) {
        updataTreelist(causeInfo.value).then((res) => {
          getTree();
          ElMessage({
            message: "修改成功",
            type: "success",
          });
        });
      } else {
        addTreelist(causeInfo.value).then((res) => {
          getTree();
          ElMessage({
            message: "新建成功",
            type: "success",
          });
        });
      }
      dialogCause.value = false;
    }
  });
}
//新建部门-保存/修改
function confirmClick(formEl: any) {
  formEl.validate((valid: any) => {
    if (valid) {
      if (info.value.id) {
        reviseDepartment(info.value).then((item) => {
          getData();
        });
      } else {
        addTreelist(info.value).then((item) => {
          getData();
        });
      }
      dialogVisible.value = false;
    }
  })
}
//关闭弹窗
function handleClose() {
  if (infoForm.value != null) infoForm.value.resetFields();
  if (causeForm.value != null) causeForm.value.resetFields();
  dialogVisible.value = false;
  dialogCause.value = false;
}

//修改组织
function edittree(data: any) {
  title.value = "修改组织";
  causeInfo.value = JSON.parse(JSON.stringify(data));
  dialogCause.value = true;
}
function remove(data: any) {
  choosetreeid.value = "";
  choosetreeid.value = data.id;
  ElMessageBox.confirm("确定删除该组织及该组织下的所有部门吗？", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: data.id,
    };
    delTreelist(params).then((res) => {
      getTree();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });

  });
}

//点击搜索
function searchOrganizations() {
  if (querystr.value == "") {
    getData();
  } else {
    querystr.value = querystr.value.replace(/\s+/g, "");
    let params = {
      orgName: querystr.value,
      id: checkedtreeid.value,
    };
    gettableData(params).then((res) => {
      tableData.value = res.data;
    });
  }
}
//新建部门
function addClick() {
  const infoagin = ref({
    id: "",
    parentid: checkedtreeid.value,
    orgtype: "2",
    orgcode: "",
    orgname: "",
    manager: "",
    description: "",
    custom1: "",
  });
  info.value = infoagin.value;
  title.value = "新增部门";
  dialogVisible.value = true;
}
//修改部门
function editdepartment(row: any) {
  title.value = "修改部门";
  const elrow = JSON.parse(JSON.stringify(row));
  const infon = ref({
    parentid: elrow.parentid,
    orgcode: elrow.orgcode,
    manager: elrow.manager,
    orgname: elrow.orgname,
    orgtype: elrow.orgtype,
    custom1: elrow.custom1,
    description: elrow.description,
    id: elrow.id,
    isvaild: elrow.isvaild,
  });

  info.value = infon.value;
  dialogVisible.value = true;
}
//删除部门
function deldepartment(row: any) {
  ElMessageBox.confirm("确定删除此部门吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      id: row.id,
    };
    delTreelist(params).then(() => {
      getTree();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
// 多选删除部门
function delClick() {
  ElMessageBox.confirm("确定删除已选择的部门吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      id: id.join(','),
    };
    delTreelist(params).then(() => {
      getTree();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    });
  });
}
function dateFormat(row: any) {
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}
onMounted(() => {
  getTree();
});
const vMove = {
  mounted(el: any) {
    el.onmousedown = function (e: any) {
      var init = e.clientX;
      var parent: any = document.getElementById("silderLeft");
      const initWidth: any = parent.offsetWidth;
      document.onmousemove = function (e) {
        var end = e.clientX;
        var newWidth = end - init + initWidth;
        parent.style.width = newWidth + "px";
      };
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      };
    };
  }
}
</script>

<template>
  <div class="faulttemplate-box">
    <aside id="silderLeft">
      <div v-hasPerm="['add:org']" class="p-[15px]"><el-button class="w-full mb-[15px]" style="color: #0099ff; border: 1px solid #0099ff;"
          @click="causeAdd"> <img src="@/assets/MenuIcon/u241.png" style="margin-right: 10px;"> 新增组织</el-button></div>
      <el-tree :class="useAppStore().size === 'default' ? 'silderLeft-large' : 'silderLeft-default'" v-loading="treeloading"
        ref="treeRef" node-key="id" :data="treedata" :highlight-current="true" :props="defaultProps"
        @node-click="handleNodeClick" style="height: calc(100vh - 215px); overflow: auto">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <span style="font-size: 16px;">
              <el-icon  class="treeediticon" title="修改" @click="() => edittree(data)">
                <EditPen />
              </el-icon>
              <el-icon  class="treedelicon" title="删除" @click="() => remove(data)">
                <Delete />
              </el-icon>
            </span>
          </span>
        </template>
      </el-tree>
      <div class="moveBtn" v-move>
        <div class="moveBtn-line" v-move></div>
      </div>
    </aside>
    <main class="silderRight">
      <el-row style="margin-bottom: 10px">
        <el-col :span="24" class="top-nav">
          <div>
            <el-input v-model="querystr" placeholder="请输入部门名称" clearable style="width: 200px;"
              @keyup.enter="searchOrganizations" />
            <el-button type="primary" style="margin-left: 10px;" @click="searchOrganizations">搜索</el-button>
          </div>
          <div class="left-nav">
            <el-button v-hasPerm="['add:org']" type="primary" @click="addClick"><img style="margin-right:5px;" src="@/assets/MenuIcon/jscz_xz.png" alt=""> 新增</el-button>
            <el-button v-hasPerm="['del:org']" :disabled="multipleSelection.length <= 0" :type="multipleSelection.length > 0 ? 'primary' : ''"
              @click="delClick"><el-icon>
                <Delete />
              </el-icon> 删除</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border
        @selection-change="handleSelectionChange" default-expand-all :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}" >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="orgcode" label="部门编号" width="100"></el-table-column>
        <el-table-column prop="orgname" label="部门名称" width="140"></el-table-column>
        <el-table-column prop="manager" label="负责人" width="120"></el-table-column>
        <el-table-column prop="custom1" label="联系信息" width="160"></el-table-column>
        <el-table-column prop="description" label="部门描述" min-width="100"></el-table-column>
        <el-table-column prop="isvaild" label="是否有效" align="center" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isvaild" active-value="1" inactive-value="0" @change="switchChange(scope.row)"
              style="margin-right: 4px"></el-switch>
            <span v-if="scope.row.isvaild == 1" style="color: #0099ff">有效</span>
            <span v-else style="color: #d7d7d7">无效</span>
          </template>
        </el-table-column>
        <el-table-column prop="lastmodifier" label="最近修改者" width="174"></el-table-column>
        <el-table-column prop="lastmodifydate" label="最近修改日期" width="196">
          <template #default="scope">
            {{ dateFormat(scope.row.lastmodifydate) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <span style="display: flex;display: -webkit-flex;justify-content: space-around; -webkit-justify-content: space-around; ">
              <img v-hasPerm="['update:org']" src="@/assets/MenuIcon/lbcz_xg.png" title="修改" style="cursor: pointer;"
              @click="editdepartment(scope.row)" >
            <img  v-hasPerm="['del:org']" src="@/assets/MenuIcon/lbcz_sc.png" title="删除" style="cursor: pointer;"
              @click="deldepartment(scope.row)" >
            </span>
          </template>
        </el-table-column>
      </el-table>
    </main>

    <!-- 部门 弹框-->
    <el-dialog v-model="dialogVisible" :before-close="handleClose" :title="title" draggable width="620px">
      <el-form ref="infoForm" :model="info" label-width="90px" :rules="moderules">
        <el-form-item label="部门编号" prop="orgcode">
          <el-input v-model="info.orgcode" style="width: 100%" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="orgname">
          <el-input v-model="info.orgname" style="width: 100%" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager" placeholder="请输入负责人姓名">
          <el-input v-model="info.manager" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="联系信息" prop="custom1">
          <el-input type="textarea" v-model="info.custom1" :autosize="{ minRows: 2 }" style="width: 100%"
            placeholder="请输入联系信息"></el-input>
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input type="textarea" v-model="info.description" :autosize="{ minRows: 2 }" style="width: 100%"
            placeholder="请输入部门描述"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button style="padding: 10px 15px" @click="handleClose">取 消</el-button>
        <el-button type="primary" style="padding: 10px 15px" @click="confirmClick(infoForm)">确定</el-button>
      </span>
    </el-dialog>
    <!-- 组织弹框-->
    <el-dialog v-model="dialogCause" :before-close="handleClose" :title="title" draggable width="620px">
      <el-form ref="causeForm" :model="causeInfo" label-width="90px" :rules="rules">
        <el-form-item label="组织编号" prop="orgcode">
          <el-input v-model="causeInfo.orgcode" style="width: 100%" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="组织名称" prop="orgname">
          <el-input v-model="causeInfo.orgname" style="width: 100%" placeholder="请输入组织名称"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="causeInfo.manager" style="width: 100%" placeholder="请输入负责人姓名"> </el-input>
        </el-form-item>
        <el-form-item label="组织描述" prop="description">
          <el-input v-model="causeInfo.description" type="textarea" :autosize="{ minRows: 2 }" style="width: 100%"
            placeholder="请输入组织描述"></el-input>
        </el-form-item>
        <el-form-item label="联系信息" prop="custom1">
          <el-input v-model="causeInfo.custom1" type="textarea" :autosize="{ minRows: 2 }" style="width: 100%"
            placeholder="请输入组织联系信息"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button style="padding: 10px 15px" @click="handleClose">取 消</el-button>
        <el-button type="primary" style="padding: 10px 15px" @click="editisrepetition(causeForm)">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style scoped  lang="scss">
.silderLeft-default {
  :deep(.custom-tree-node, .treedelicon, .treeediticon) {
    font-size: 16px !important;
  }

  :deep(.custom-tree-large, .treedelicon, .treeediticon) {
    font-size: 14px !important;
  }
}

.faulttemplate-box {
  height: 100%;
  display: -webkit-flex;
  display: flex;
  background-color: #f2f4f9;
}

#silderLeft {
  width: 300px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 3px;
  position: relative;

  &:hover {
    .moveBtn {
      opacity: 1;
    }
  }
}

/* 拖动条 */
.moveBtn {
  height: 100%;
  width: 15px;
  padding: 0 6px;
  opacity: 0;
  position: absolute;
  right: -15px;
  top: 0;
}

.moveBtn-line {
  width: 100%;
  height: 100%;
  cursor: col-resize;
  user-select: none;
  background-color: #60bfff;
}

.dialog-footer {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}

.silderRight {
  flex: 1;
  position: relative;
  width: 100%;
  height: calc(100vh - 130px);
  overflow: auto;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 3px;
  padding: 15px;
  padding-bottom: 0px;
  margin-left: 15px;
  box-sizing: border-box;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  width: 100%;
  height: 40px;
  background-color: #409eff !important;
  color: #fff !important;
}

:deep(.el-tree-node__content) {
  width: 100%;
  height: 40px;
  line-height: 40px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #409eff19;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  display: -webkit-flex;
  align-items: center;
  -webkit-align-items: center;
  justify-content: space-between;
  -webkit-justify-content: space-between; 
  padding-right: 8px;

}

.faulttemplate-box {
  .is-current .treeediticon {
    color: #ffffff !important;
  }

  .is-current .treedelicon {
    color: #ffffff !important;
  }

  .el-tree-node__content:hover .treeediticon {
    color: #00cccc;
  }

  .el-tree-node__content:hover .treedelicon {
    color: #f56c6c;
  }
}

.treeediticon,
.treedelicon {
  color: #fff;
  margin: 0 5px;
}
:deep(.el-table__cell){
  color: #383838;
}
.top-nav {
  display: -webkit-flex;
  display: flex;
  justify-content: space-between;
  -webkit-justify-content: space-between;
}</style>
