<script setup>
import { ref } from "vue";
import request from "~/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Delete,
  EditPen,
  Histogram,
  View,
  Plus,
  UserFilled
} from "@element-plus/icons-vue";
import { orgAdd, orgList, orgDelete, orgDetail, orgEdit, userList, userAdd, userRemove, userMasterAdd, userMasterRemove, settingList, menuAdd, menuLeft } from "./api";
import menuData from "./config.js"
// import { includes } from "lodash";

const activeName = ref("-ROUTES-QXSZ");
const loading = ref(false);
const dept_id = ref("");
const cpm_id = ref("90000");


const zzjgTree_Data = ref([]);
const zzjgcyTable_Data = ref([]);
const qxszTree_Data = ref([]);

const defaultProps = {
  children: "children",
  label: "label",
};

// 组织
async function queryOrg() {
  loading.value = true;
  let data = await orgList();
  // let arr = data.page_data.filter(item => item.uo_pid == 0);
  // initAnaData(arr, data.page_data);
  // zzjgTree_Data.value = arr;
  zzjgTree_Data.value = data.one_info;
  loading.value = false;
}
queryOrg();

function initAnaData(arr, arg) {
  for (let i = 0; i < arr.length; i++) {
    arr[i].children = [];
    for (let j = 0; j < arg.length; j++) {
      if (arr[i].uo_id == arg[j].uo_pid) {
        arr[i].children.push(arg[j]);
      }
    }
    initAnaData(arr[i].children, arg);
  }
}

const handleNodeClick = ({ id }) => {
  dept_id.value = id;
  queryUser();
  queryPermission();
}

const total = ref(0);
const limit = ref(10);

const currentPage = ref(1);
function handleCurrentChange() {
  queryUser();
}

// 用户
async function queryUser() {
  let obj = {
    admin: 1,
    all: 1,
    dept_id: dept_id.value,
    page: currentPage.value,
    limit: limit.value,
  }
  let data = await userList(obj);
  total.value = parseInt(data.total_rows);
  zzjgcyTable_Data.value = data.page_data;
}
queryUser();

const userData = ref([]);
const memberTotal = ref(0);
const memberLimit = ref(100);
const memberCurrentPage = ref(1);
initAllUser();
async function initAllUser() {
  let obj = {
    is_not_stu: "1",
    admin: 1,
    page: memberCurrentPage.value,
    limit: memberLimit.value,
  }
  let data = await userList(obj);
  memberTotal.value = parseInt(data.total_rows);
  data.page_data.map((item) => {
    if (item.user_phone != "") {
      item.user_realname_phone = item.user_realname + "（" + item.user_phone + "）";
    } else {
      item.user_realname_phone = item.user_realname;
    }
  })
  userData.value = data.page_data;
}

const handleMemberChange = (val) => {
  memberCurrentPage.value = val;
  initAllUser();
}

queryPermission();
async function queryPermission() {
  let obj = {
    cpm_id: cpm_id.value,
    dept_id: dept_id.value
  }
  let data = await settingList(obj);
  let cmu_ids = data.cmu_ids;
  // let data1 = await menuLeft(obj);
  // console.log(data1)
  // const menu_left = data.menu_left || menuData;
  const menu_left = menuData;
  initAnaPermission(menu_left, cmu_ids);
  qxszTree_Data.value = menu_left.map((child) => _handleItem(child));
}
function initAnaPermission(arg, cmu_ids) {
  if (arg instanceof Array) {
    for (let i = 0; i < arg.length; i++) {
      initAnaPermission(arg[i], cmu_ids);
    }
  } else {
    arg.permission = {};
    arg.checkList.map((item) => {
      arg.permission[item.key] = false;
      if (cmu_ids != null) {
        for (let key in cmu_ids) {
          if (key == arg.cmu_id) {
            let arr = cmu_ids[key].split(",");
            arr.map((value) => {
              if (item.key == value) {
                arg.permission[item.key] = true;
              }
            })
          }
        }
      }
    })
    if (arg.children && arg.children.length != 0) {
      for (let i = 0; i < arg.children.length; i++) {
        initAnaPermission(arg.children[i], cmu_ids);
      }
    }
  }
}

// 权限
function _handleItem(item) {
  const returnObj = {
    id: item.id,
    label: item.label,
    cmu_id: item.cmu_id,
    checkList: item.checkList,
    permission: item.permission
  };
  if (Array.isArray(item.children)) {
    returnObj.children = item.children.map((child) => _handleItem(child));
  }
  return returnObj;
}

const dialogVisible = ref(false);
const dialogWidth = ref("");
const dialogTitle = ref("");
const dialogType = ref("");
const editId = ref("");
const handleAdd = (data) => {
  dialogVisible.value = true;
  dialogWidth.value = "400px";
  dialogTitle.value = "新建";
  dialogType.value = 1;
  if (data) {
    ruleForm.value.uo_pid = data.id;
    // ruleForm.value.uo_level = String(Number(data.uo_level) + 1);
  }
};

const memberAdd = () => {
  if (dept_id.value == "") {
    ElMessage.error("请先选择机构！");
    return;
  }
  dialogVisible.value = true;
  dialogWidth.value = "1000px";
  dialogTitle.value = "添加成员";
  dialogType.value = 2;
  memberValue.value = [];
}

const filterMethod = (query, item) => {
  return item.user_realname_phone.toLowerCase().includes(query.toLowerCase())
}

const handleClose = () => {
  dialogVisible.value = false;
  dialogWidth.value = "";
  dialogTitle.value = "";
  dialogType.value = "";
  ruleForm.value.uo_name = "";
  ruleForm.value.uo_sort = 1;
  editId.value = "";
};

const ruleForm = ref({
  uo_name: "",
  uo_sort: 1,
  uo_pid: "0",
  uo_attrib: "2",
  // uo_level: "0",
});
const rules = ref({
  uo_name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  uo_sort: [{ required: true, message: "请输入序号", trigger: "blur" }],
});

const memberValue = ref([]);
const commitData = async () => {
  if (dialogType.value == 1) {
    ruleForm.value.uo_sort = Number(ruleForm.value.uo_sort);
    let obj = {
      user_org: ruleForm.value,
    };
    loading.value = true;
    if (editId.value == "") {
      await orgAdd(obj);
    } else {
      await orgEdit({ uo_id: editId.value, user_org: obj.user_org });
    }
    loading.value = false;
    ElMessage.success("保存成功！");
    queryOrg();
  } else if (dialogType.value == 2) {
    let obj = {
      uo_id: dept_id.value,
      uo_user_ids: memberValue.value,
      issubmit: '1'
    }
    loading.value = true;
    await userAdd(obj);
    loading.value = false;
    ElMessage.success("保存成功！");
    queryUser();
  }
  handleClose();
};

const handleEdit = async (data) => {
  editId.value = data.id;
  dialogVisible.value = true;
  dialogWidth.value = "400px";
  dialogTitle.value = "编辑";
  dialogType.value = 1;
  let obj = await orgDetail({ uo_id: editId.value });
  ruleForm.value.uo_name = obj.one_info.uo_name;
  ruleForm.value.uo_sort = obj.one_info.uo_sort;
};

const handleRemove = (uo_id) => {
  ElMessageBox.confirm("是否确定删除当前数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    buttonSize: "default",
  })
    .then(async () => {
      loading.value = true;
      let data = await orgDelete({ uo_id });
      loading.value = false;
      if (data) {
        ElMessage.success("删除成功！");
        queryOrg();
      }
    })
    .catch(() => { });
};

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const memberSet = async (type, row) => {
  if (multipleSelection.value.length == 0 && type != 4) {
    ElMessage.error("请先选择数据");
    return
  }
  let arr = [];
  multipleSelection.value.map((item) => {
    arr.push(item.user_id);
  })
  let obj = {
    uo_id: Number(dept_id.value),
    issubmit: "1"
  }
  if (type == 1) {
    obj.uo_master_user_ids = arr;
    await userMasterRemove(obj);
    ElMessage.success("取消管理员成功！");
    queryUser();
  } else if (type == 2) {
    obj.uo_master_user_ids = arr;
    await userMasterAdd(obj);
    ElMessage.success("设为管理员成功！");
    queryUser();
  } else if (type == 3) {
    obj.uo_user_ids = arr;
    let data = await userRemove(obj);
    if (data) {
      ElMessage.success("删除成功！");
      queryUser();
    }
  } else if (type == 4) {
    obj.uo_user_ids = [row.user_id];
    let data = await userRemove(obj);
    if (data) {
      ElMessage.success("删除成功！");
      queryUser();
    }
  }
}

const handlePermissionChange = async (data) => {
  if (dept_id.value == "") {
    ElMessage.error("请先选择机构！");
    return;
  }
  let arr = [];
  for (let key in data.permission) {
    if (data.permission[key]) {
      arr.push(key);
    }
  }
  let obj = {
    user_org_menu: {
      cpm_id: cpm_id.value,
      cmu_id: data.cmu_id,
      dept_id: dept_id.value,
      cmu_permission: arr.join(",")
    }
  }
  await menuAdd(obj);
  queryPermission();
}
</script>

<template>
  <div class="flex h-full zzjgContent" v-loading="loading">
    <div class="w-400px flex-none h-full flex flex-col">
      <div class="flex justify-between items-center flex-none mb-4">
        <div class="text-xl font-bold">组织机构</div>
        <el-button type="success" size="default" @click="handleAdd()">新建</el-button>
      </div>
      <div class="flex-auto overflow-hidden">
        <el-scrollbar>
          <el-tree :data="zzjgTree_Data" node-key="id" :props="defaultProps" default-expand-all :expand-on-click-node="false" highlight-current @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span style="flex: 1;">{{ node.label }}</span>
                <span class="operateDiv">
                  <el-icon color="#00A3FF" @click="handleAdd(data)">
                    <Plus />
                  </el-icon>
                  <el-icon color="#00A3FF" @click="handleEdit(data)" style="margin: 0 10px;">
                    <EditPen />
                  </el-icon>
                  <el-icon color="#00A3FF" @click="handleRemove(data.id)">
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>

    <div className="divider_y flex-none" />

    <div class="flex-auto">
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织机构成员" name="-ROUTES-ZZJGCY">
          <el-table :data="zzjgcyTable_Data" row-key="name" max-height="830px" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="编号" prop="user_id" width="120">
            </el-table-column>
            <el-table-column label="成员姓名" prop="user_realname" width="auto">
              <template #default="{ row }">
                <div style="display: flex;">
                  <span style="display: inline-block;width: 80px;">{{row.user_realname}}</span>
                  <span v-if="row.is_user_org_master==1" style="color: #409eff; display: flex;align-items: center;">
                    <el-icon style="margin-right: 5px;">
                      <UserFilled />
                    </el-icon>
                    管理员
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="{ row }">
                <el-link @click="memberSet(4, row)" type="primary" :underline="false">删除</el-link>
              </template>
            </el-table-column>
          </el-table>

          <div class="flex justify-end mt-10 py-4">
            <el-pagination :page-size="limit" v-model:current-page="currentPage" @current-change="handleCurrentChange" background layout="total, prev, pager, next" :total="total" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="权限设置" name="-ROUTES-QXSZ">
          <el-table :data="qxszTree_Data" row-key="id" default-expand-all max-height="830px">
            <el-table-column label="功能菜单" prop="label" width="200"> </el-table-column>
            <el-table-column label="勾选权限">
              <template #default="{ row }">
                <el-checkbox v-for="(item, index) in row.checkList" :key="index" v-model="row.permission[item.key]" :label="item.name" @change="handlePermissionChange(row)" />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="memberBtn" v-show="activeName=='-ROUTES-ZZJGCY'">
        <el-button size="default" type="success" @click="memberAdd">添加</el-button>
        <el-button size="default" type="primary" @click="memberSet(1)">取消管理员</el-button>
        <el-button size="default" type="primary" @click="memberSet(2)">设为管理员</el-button>
        <el-button size="default" type="danger" @click="memberSet(3)">删除</el-button>
      </div>
    </div>

    <el-dialog :width="dialogWidth" v-model="dialogVisible" :title="dialogTitle" custom-class="commonDialog" :show-close="false" :close-on-click-modal="false">
      <!-- <detail :current="currentId" @update="handleClose"></detail> -->
      <el-form v-if="dialogType==1" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="60px" class="demo-ruleForm">
        <el-form-item label="名称" prop="uo_name">
          <el-input v-model="ruleForm.uo_name" />
        </el-form-item>
        <el-form-item label="序号" prop="uo_sort">
          <el-input v-model="ruleForm.uo_sort" type="number" :min="1" />
        </el-form-item>
      </el-form>
      <el-transfer v-if="dialogType==2" v-model="memberValue" :props="{ key: 'user_id', label: 'user_realname_phone' }" :titles="['全部', '全部']" filterable :filter-method="filterMethod" filter-placeholder="请输入姓名..." :data="userData">
        <template #left-footer>
          <el-pagination background layout="prev, pager, next" :pager-count="5" :total="memberTotal" @current-change="handleMemberChange" :page-size="memberLimit" :currentPage="memberCurrentPage"></el-pagination>
        </template>
      </el-transfer>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="commitData">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import "~/styles/dialog.scss";
::v-deep .commonDialog {
  .el-transfer {
    display: flex;
    align-items: center;
    .el-transfer-panel {
      flex: 1;
      height: 480px;
      .el-input {
        width: 350px;
      }
      .el-transfer-panel__body {
        height: 400px;
      }
    }
  }
}
.zzjgContent {
  .pointer {
    cursor: pointer;
  }
  .el-tree::v-deep {
    padding-right: 15px;
    .el-tree-node__content {
      .el-tree-node__label {
        flex: 1;
        display: block;
        .custom-tree-node {
          display: flex;
        }
        .operateDiv {
          display: none;
        }
        &:hover {
          .operateDiv {
            display: block;
          }
        }
      }
    }
  }
  .flex-auto {
    position: relative;
    .memberBtn {
      position: absolute;
      top: 3px;
      right: 0;
    }
  }
}
</style>
