<template>
  <div class="page_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="flex_row">
      <div class="flex_left bgc_white">
        <div class="tree_header">政务组织</div>
        <div class="tree_content">
          <div class="search">
            <el-input v-model="search" placeholder="请输入组织名称搜索" :prefix-icon="Search" @input="searchChange" />
          </div>
          <div class="tree">
            <tree ref="orgTree" @action="treeAction" @select="treeSelect"></tree>
          </div>
        </div>
      </div>
      <div class="flex_right">
        <div class="info_container bgc_white">
          <div class="title">
            <span class="icon_box">
              <span class="step_icon">
                <bg-icon icon="#bg-ic-file"></bg-icon>
              </span>
              <span> 基本信息 </span>
            </span>
          </div>
          <bg-info class="info_box" :data="baseInfo"></bg-info>
        </div>
        <div class="main_container bgc_white">
          <bg-filter-group @search="changeSearch" v-model="filter.key_word" placeholder="请输入关键字">
            <template v-slot:left_action>
              <div class="title">
                <span class="icon_box">
                  <span class="step_icon">
                    <bg-icon icon="#bg-ic-file"></bg-icon>
                  </span>
                  <span> 用户列表 </span>
                </span>
              </div>
            </template>
            <template v-slot:filter_group>
              <div class="left-filter filter_list">
                <div class="filter_item">
                  <span class="filter_title">启用状态</span>
                  <el-select v-model="filter.state" placeholder="请选择" style="width: 300px">
                    <el-option
                      v-for="(item, index) in stateOptions"
                      :key="'pushOptions' + index"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div class="right-action apaas_button">
                <el-button type="primary" @click="filterAction"> 查询 </el-button>
                <el-button type="default" @click="filterClear"> 重置 </el-button>
              </div>
            </template>
          </bg-filter-group>
          <div class="table_container apaas_scroll">
            <bg-table ref="dataTable" :headers="headers" :rows="tableRows" :isIndex="true" :stripe="true">
              <template v-slot:action="{ row }">
                <bg-table-btn @click="goDetail(row)" class="can_click_text"> 详情 </bg-table-btn>
              </template>
            </bg-table>
            <div class="pagination_box">
              <bg-pagination
                :page="filter.page"
                :size="filter.limit"
                :total="tableTotal"
                @change-page="changePage"
                @change-size="changeSize">
              </bg-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogDirectory"
      :title="action === 'create' ? '新增目录' : '编辑目录'"
      width="758px"
      :before-close="handleCloseDirectory"
      destroy-on-close>
      <div class="dialog_form">
        <directoryForm
          ref="directoryFormRef"
          :form-type="directoryFormType"
          @action="getDirectoryFromData"></directoryForm>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDirectory">取消</el-button>
          <el-button type="primary" @click="saveDirectory">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogOrg"
      :title="action === 'create' ? '新增组织' : '编辑组织'"
      width="758px"
      :before-close="handleCloseOrg"
      destroy-on-close>
      <div class="dialog_form">
        <orgForm ref="orgFormRef" :form-type="orgFormType" @action="getOrgFormData"></orgForm>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseOrg">取消</el-button>
          <el-button type="primary" @click="saveOrg">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogDelNode" title="删除" width="520px" :before-close="handleCloseDelNode">
      <div class="dialog_form">确认删除吗？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDelNode">取消</el-button>
          <el-button type="primary" @click="confirmDelNode">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { onBeforeMount, nextTick, reactive, ref } from "@vue/runtime-core";
import { useRouter } from "vue-router";
import tree from "./tree.vue";
import directoryForm from "./directory-form.vue";
import orgForm from "./org-form.vue";
import { downloadFileFormatNew } from "@/services/helper";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";

const dataTable = ref(null);

const baseInfo = reactive([
  {
    name: "组织名称",
    value: "",
    nameWidth: 130,
  },
  {
    name: "组织代码",
    value: "",
    nameWidth: 130,
  },
  {
    name: "组织描述",
    value: "",
    nameWidth: 130,
  },
  {
    name: "用户数量",
    value: "",
    nameWidth: 130,
  },

  {
    name: "创建时间",
    value: "",
    nameWidth: 130,
  },
]);
const headers = reactive([
  {
    label: "账号",
    prop: "system_account",
    minWidth: 150,
  },
  {
    label: "手机号",
    prop: "contact_phone",
    minWidth: 150,
  },
  {
    label: "角色",
    prop: "system_role",
    minWidth: 150,
  },
  {
    label: "创建时间",
    prop: "created_time",
    minWidth: 200,
  },
  {
    label: "操作",
    prop: "action",
    width: 220,
    fixed: "right",
  },
]);
const stateOptions = ref([
  {
    name: "全部",
    value: "",
  },
  {
    name: "启用",
    value: "1",
  },
  {
    name: "禁用",
    value: "0",
  },
]);
const tableRows = ref([]);
const tableTotal = ref(0);
const orgTree = ref(null);
const selectTreeData = ref(null);
const actionTreeData = ref(null);
const selectTreeDataType = ref(2);
const selectOrgNode = ref(null);
const dialogDelNode = ref(false);
const router = useRouter();
const filter = reactive({
  state: "",
  key_word: "",
  page: 1,
  limit: 10,
});

const search = ref("");

const changeSize = (size) => {
  filter.limit = size;
  changePage(1);
};

const changePage = (page) => {
  filter.page = page;
  getTableRows();
};

const changeSearch = (val) => {
  filter.key_word = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  filter.state = "";
  filter.key_word = "";
  filter.limit = 10;
  filter.page = 1;
  changePage(1);
}; // 重置筛选项

const dialogDirectory = ref(false);
const directoryFormType = ref("create");
const orgFormType = ref("create");
const handleCloseDirectory = () => {
  dialogDirectory.value = false;
};

const directoryFormRef = ref(null);
const saveDirectory = () => {
  directoryFormRef.value.submitForm();
};

//新增/编剧目录
const getDirectoryFromData = (data) => {
  if (directoryFormType.value === "create") {
    const params = {
      p_organization_id: data.level ? "" : data.p_organization_id,
      name: data.name,
      data_type: 0,
    };
    axios.post(`/v1/api/org/add`, params).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        orgTree.value.getOrgTree(res.data.data.id);
      } else {
        ElMessage.error(res.data.data);
      }
      handleCloseDirectory();
    });
  } else if (directoryFormType.value === "edit") {
    const params = {
      name: data.name,
      data_type: 0,
    };
    axios.put(`/v1/api/org/${actionTreeData.value.id}`, params).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        orgTree.value.getOrgTree(actionTreeData.value.id);
      } else {
        ElMessage.error(res.data.data);
      }
      handleCloseDirectory();
    });
  }
};

const dialogOrg = ref(false);
const handleCloseOrg = () => {
  dialogOrg.value = false;
};

const orgFormRef = ref(null);
const saveOrg = () => {
  orgFormRef.value.submitForm();
};

//新增/编辑组织
const getOrgFormData = (data) => {
  if (orgFormType.value === "create") {
    const params = {
      p_organization_id: data.level ? "" : data.p_organization_id,
      name: data.name,
      organization_code: data.organization_code,
      description: data.description,
      data_type: 1,
    };
    axios.post(`/v1/api/org/add`, params).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        orgTree.value.getOrgTree(res.data.data.id);
      } else {
        ElMessage.error(res.data.data);
      }
      handleCloseOrg();
    });
  } else if (orgFormType.value === "edit") {
    const params = {
      // p_organization_id: data.level ? "" : data.p_organization_id,
      name: data.name,
      organization_code: data.organization_code,
      description: data.description,
      data_type: 1,
    };
    axios.put(`/v1/api/org/${actionTreeData.value.id}`, params).then((res) => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.msg);
        orgTree.value.getOrgTree(actionTreeData.value.id);
      } else {
        ElMessage.error(res.data.data);
      }
      handleCloseOrg();
    });
  }
};

const handleCloseDelNode = () => {
  dialogDelNode.value = false;
};

//删除目录/组织
const confirmDelNode = () => {
  axios.delete(`/v1/api/org/${actionTreeData.value.id}`).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      orgTree.value.getOrgTree(actionTreeData.value.id === selectTreeData.value.id ? null : selectTreeData.value.id);
    } else {
      ElMessage.error(res.data.data);
    }
    handleCloseDelNode();
  });
};

const moveOrg = (params) => {
  axios.put(`/v1/api/org/sort`, params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      orgTree.value.getOrgTree(selectTreeData.value.id);
    } else {
      ElMessage.error(res.data.data);
    }
  });
};

const action = ref("create");
const treeAction = (data) => {
  action.value = data.action;
  if (data.action === "create" || data.action === "edit") {
    if (data.type === "org") {
      orgFormType.value = data.action;
      dialogOrg.value = true;
      nextTick(() => {
        if (data.data) {
          if (data.action === "edit") {
            orgFormRef.value.setForm({
              name: data.data.value.name,
              p_organization_id: data.data.value.p_organization_id,
              level: data.data.value.p_organization_id ? false : true,
              organization_code: data.data.value.organization_code,
              description: data.data.value.description,
            });
          } else if (data.action === "create") {
            orgFormRef.value.setForm({ p_organization_id: data.data.value.organization_id });
          }
        }
      });
    } else {
      directoryFormType.value = data.action;
      dialogDirectory.value = true;
      nextTick(() => {
        if (data.data) {
          if (data.action === "edit") {
            directoryFormRef.value.setForm({ name: data.data.value.name });
          } else if (data.action === "create") {
            directoryFormRef.value.setForm({ p_organization_id: data.data.value.organization_id });
          }
        }
      });
    }
  } else if (data.action === "delete") {
    dialogDelNode.value = true;
  } else if (data.action === "mvup" || data.action === "mvdown") {
    moveOrg(data.data);
  }
};

const treeSelect = (data) => {
  if (data.type === "action") {
    actionTreeData.value = data.data.value;
  } else {
    selectTreeData.value = data.data.value;
  }

  if (data.type === "click" && (data.data.value.data_type === 1 || data.data.value.data_type === 2)) {
    selectTreeDataType.value = data.data.value.data_type;
    selectOrgNode.value = data.data.value;
    getTableRows();
  }
};

const getTableRows = () => {
  let params = {
    ...filter,
    organization_id: selectTreeData.value.organization_id,
  };
  axios
    .get(`/v1/api/org/detail`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        tableRows.value = ((res.data.data && res.data.data.org_users.data) || []).map((item) => {
          item.system_role = item.system_role ? item.system_role.join("、") : "-";
          return item;
        });
        tableTotal.value = (res.data.data && res.data.data.org_users.total) || 0;
        baseInfo[0].value = (res.data.data && res.data.data.org_info.name) || "";
        baseInfo[1].value = (res.data.data && res.data.data.org_info.organization_code) || "";
        baseInfo[2].value = (res.data.data && res.data.data.org_info.description) || "";
        baseInfo[3].value = (res.data.data && res.data.data.org_info.platform_users_number) || "";
        baseInfo[4].value = (res.data.data && res.data.data.org_info.created_time) || "";
      } else {
        ElMessage.error(res.data.data);
      }
    });
};

const searchChange = (val) => {
  orgTree.value.filterTree(val);
};

const goDetail = (params) => {
  router.push({
    path: "/authority/organization/user-detail",
    query: {
      id: params.id,
    },
  });
};
onBeforeMount(() => {});
</script>

<style scoped>
.tree_header {
  height: 40px;
  line-height: 40px;
  background-color: #f7f7f9;
  border-radius: 6px 6px 0px 0px;
  font-size: 16px;
  letter-spacing: 0px;
  color: #202531;
  padding-left: 16px;
}
.tree_content {
  overflow: hidden;
  height: calc(100% - 45px);
}
.search {
  padding: 16px;
}
.tree {
  overflow: hidden auto;
  height: calc(100% - 65px);
  /* padding: 5px; */
}
.tree :deep() .el-tree-node > .el-tree-node__children {
  overflow: unset;
}
.flex_right {
  display: flex;
  flex-direction: column;
}
.info_container {
  padding: 15px;
  margin-bottom: 10px;
}
.title {
  font-size: 18px;
  color: #202531;
  font-weight: bold;
  margin-bottom: 10px;
  max-width: 960px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail_btn {
  font-size: 14px;
  font-weight: normal;
}
.icon_box {
  display: flex;
  align-items: center;
}
.step_icon {
  display: inline-block;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  background-color: #2a4aa7;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  margin-right: 8px;
}
.info_box {
  max-width: 960px;
}
.main_container {
  flex: 1;
  overflow: hidden;
}
.filter-group .left-filter {
  flex: 1;
  display: flex;
  justify-content: start;
  flex-wrap: wrap;
}
.filter-group .right-action {
  width: 144px;
  padding-bottom: 16px;
}
.filter-group .right-action .el-button {
  width: 64px;
}

.table_container {
  height: calc(100% - 20px);
  overflow: auto;
  padding: 0 16px;
}

.bg-pagination {
  bottom: unset;
}
.dialog_form {
  padding: 24px 8px 6px;
}
</style>
