<template>
  <div class="dept">
    <div class="tree">
      <treeList
        :data="treeListData"
        v-model="sourceList.pagination.tenantId"
        node-key="id"
        @change="treeChange"
      >
      </treeList>
    </div>
    <div class="content">
      <byTable
        :hideTable="true"
        :hidePagination="true"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: '添加机构',
            action: () => openModal('add'),
            disabled: !sourceList.pagination.tenantId,
          },
        ]"
        @get-list="getList"
      >
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
      <el-table
        v-loading="loading"
        :data="sourceList.data"
        row-key="deptId"
        style="padding: 0 20px; box-sizing: border-box"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column
          prop="deptName"
          label="机构名称"
          width="260"
        ></el-table-column>
        <el-table-column
          prop="orderNum"
          label="排序"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="type"
          label="机构类型"
          width="100"
          :formatter="(row) => showType(row.type)"
        >
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="200"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="getDtl(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']"
              >新增</el-button
            >
            <el-button
              v-if="scope.row.parentId != 0"
              link
              type="primary"
              @click="listDelete(scope.row)"
              v-hasPermi="['system:dept:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="modalType == 'add' ? '新增' : '编辑'"
      v-model="dialogVisible"
      width="500"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #account>
          <el-input
            style="width: 150px; margin-right: 10px"
            v-model="formData.data.userName"
            placeholder="请输入用户名"
          ></el-input>
          <el-input
            style="width: 150px; margin-right: 10px"
            v-model="formData.data.password"
            placeholder="密码"
          ></el-input>
          <span style="color: #409eff; cursor: pointer" @click="newPassword"
            >随机生成</span
          >
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="修改密码"
      v-model="roomDialogVisible"
      width="500"
      :before-close="handleClose"
      v-loading="loading"
    >
      <template #footer>
        <el-button @click="roomDialogVisible = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitTree('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import treeList from "@/components/treeList/index";
import { computed, defineComponent, ref } from "vue";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  parentId: [{ required: true, message: "请选择上级机构", trigger: "blur" }],
  orderNum: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "机构名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "机构类型不能为空", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = computed(() => {
  return [];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "机构名称",
        prop: "deptName",
      },
    },
    {
      attrs: {
        label: "机构类型",
        prop: "type",
        align: "left",
      },

      render(type) {
        return type == "0"
          ? "公司"
          : type == "1"
          ? "业务中心"
          : type == "2"
          ? "部门"
          : "组";
      },
    },
    {
      attrs: {
        label: "排序",
        prop: "nickName",
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {},
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    orderNum:1,
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "treeSelect",
      prop: "parentId",
      label: "上级机构",
      data: [],
    },
    {
      type: "input",
      prop: "deptName",
      label: "机构名称",
      required: true,
      itemWidth: 50,
      //disabled:true,
      itemType: "text",
    },

    {
      type: "select",
      prop: "type",
      label: "机构类型",
      required: true,

      data: [
        {
          label: "公司",
          id: 0,
        },
        {
          label: "业务中心",
          id: 1,
        },
        {
          label: "部门",
          id: 2,
        },
        {
          label: "组",
          id: 3,
        },
      ],
    },
    {
      type: "select",
      label: "负责人",
      prop: "leaderId",
      itemWidth: 50,
      data:[],
    },
    {
      type: "select",
      label: "总监",
      prop: "directorId",
      itemWidth: 50,
      data:[],
    },
    {
      type: "input",
      prop: "orderNum",
      label: "排序",
      required: true,
      itemWidth: 50,
      //disabled:true,
      itemType: "number",
    },
  ];
});
const newPassword = () => {
  formData.data.password = generatePassword();
};
const generatePassword = () => {
  var length = 12,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    password = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    password += charset.charAt(Math.floor(Math.random() * n));
  }
  return password;
};

const getTreeList = () => {
  proxy.post("/tenantInfo/list").then((message) => {
    message.map((item) => {
      item.label = item.enterpriseName;
      item.id = item.tenantId;
      item.children = [];
    });

    treeListData.value = message;
    console.log(treeListData.value);
  });
};
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((message) => {
    recursive(message.data);
    sourceList.value.data = proxy.handleTree(message.data, "deptId");
    console.log(sourceList.value);
    formConfig.value[0].data = proxy.handleTree(message.data, "deptId");
    console.log(formConfig.value[0].data)
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

const treeChange = (e) => {
  sourceList.value.pagination.tenantId = e.id;
  getList({ tenantId: e.id });
};

const handleAdd = (row) => {
  dialogVisible.value = true;
  modalType.value = "add";
  console.log(row);
  formData.data = {
    parentId: row.deptId,
    tenantId: row.tenantId,
  };
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    orderNum:1,
  };
  getUserList()
};
const TreetenantId = ref("");
const selection = ref({
  data: [],
});

const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};

const tree = ref(null);
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const method = modalType.value == "add" ? "POST" : "PUT";
    console.log(method);
    if (!formData.data.parentId) formData.data.parentId = 0;
    proxy
      .post(
        "/tenantDept",
        {
          ...formData.data,
          tenantId: formData.data.tenantId
            ? formData.data.tenantId
            : sourceList.value.pagination.tenantId,
        },
        method
      )
      .then((res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      });
  });
};

const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.deptId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};

const listDelete = (row) => {
  // 弹窗提示是否删除
  ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 删除
    proxy.post("/tenantDept/" + row.deptId, {}, "delete").then((res) => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getList();
    });
  });
};
const showType = (type) => {
  return type == "0"
    ? "公司"
    : type == "1"
    ? "业务中心"
    : type == "2"
    ? "部门"
    : "组";
};
const getDtl = (row) => {
  formData.data = { ...row };
  modalType.value = "edit";
  console.log(modalType.value);
  dialogVisible.value = true;
};

const getUserList = () => {
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: sourceList.value.pagination.tenantId,
    })
    .then((message) => {
      message.rows.map((item) => {
        item.label = item.nickName;
        item.id = item.userId;
      });
      formConfig.value[3].data = message.rows;
      formConfig.value[4].data = message.rows;
      console.log(config)
    });
};



getTreeList();
getList();
</script>
  
<style lang="scss" scoped>
.dept {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  .tree {
    width: 300px;
  }
  .content {
    width: calc(100% - 320px);
  }
}
</style>