<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="filterTree" placeholder="请输入组织名称搜索" :prefix-icon="Search" />
          </div>
          <div class="tree">
            <el-tree
              ref="treeRef"
              :data="orgData"
              :props="defaultProps"
              @node-click="handleNodeClick"
              node-key="organization_id"
              :highlight-current="true"
              :filter-node-method="filterNode"
              :default-expand-all="true">
              <template #default="{ node, data }">
                <div class="custom_tree_node">
                  <span class="label-text" :title="node.label">{{ node.label }} </span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </div>
      <div class="flex_right bgc_white">
        <div class="main_container">
          <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入关键字">
            <template v-slot:left_action>
              <div class="apaas_button">
                <el-button type="primary" @click="addAccount">
                  <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
                  新增
                </el-button>
                <el-button @click="deleteBatch"> 批量删除 </el-button>
                <el-button @click="resetPsd"> 重置密码 </el-button>
                <span class="header_info"
                  >已选择<span style="color: #202531; font-weight: bold">{{ selected.length }}</span
                  >项</span
                >
                <span class="header_info can_click_text" @click="clearSelected">清空</span>
              </div>
            </template>
          </bg-filter-group>
          <div class="table_container apaas_scroll">
            <bg-table
              ref="dataTable"
              :headers="headers"
              :rows="tableRows"
              :isIndex="true"
              :stripe="true"
              :select="true"
              @selectAc="selectRows">
              <template v-slot:state="{ row }">
                <bg-switch
                  @click="stateChange(row)"
                  :labels="['否', '是']"
                  :values="[0, 1]"
                  v-model="row.state"></bg-switch>
              </template>
              <template v-slot:action="{ row }">
                <bg-table-btn @click="editAccount(row.id)"> 编辑 </bg-table-btn>
                <bg-table-btn @click="editPsdAccount(row)"> 修改密码 </bg-table-btn>
                <bg-table-btn @click="deleteAccount(row)"> 删除 </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="deleteFlag" title="删除" width="520px" :before-close="handleCloseDelete">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        您正在对 <span class="danger_info">{{ selectedName.join("、") }}</span
        >做删除操作。
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDelete">取消</el-button>
          <el-button type="primary" @click="deleteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="deleteRowFlag" title="删除" width="520px" :before-close="handleCloseRowDelete">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        您正在对 <span class="danger_info">{{ selectedRow.system_account }}</span
        >做删除操作。
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseRowDelete">取消</el-button>
          <el-button type="primary" @click="deleteRowConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="resetFlag" title="重置密码" width="520px" :before-close="handleCloseReset">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        您正在对 <span class="danger_info">{{ selectedName.join("、") }}</span
        >做重置密码操作。
      </div>
      <div>重置密码为123456，是否继续？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseReset">取消</el-button>
          <el-button type="primary" @click="resetConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="editFlag" title="修改密码" width="520px" :before-close="handleCloseEdit">
      <div class="warning_info">
        <bg-icon
          style="font-size: 12px; color: #a9b1c7; margin-right: 8px; vertical-align: baseline"
          icon="#bg-ic-circle-tips"></bg-icon>
        您正在对 <span class="danger_info">{{ selectedRow.system_account }}</span
        >做修改密码操作，修改后旧密码将无法登录。
      </div>
      <div>
        <el-form
          :label-position="'right'"
          label-width="120px"
          :model="passwordForm"
          :rules="passwordFormRules"
          ref="passwordRef"
          style="max-width: 80%">
          <el-form-item label="新密码" prop="password">
            <el-input
              v-model="passwordForm.password"
              :type="password_eye ? 'text' : 'password'"
              placeholder="请输入密码">
              <template #suffix>
                <bg-icon @click="password_eye = !password_eye" class="icon_eye" icon="#bg-ic-eye"></bg-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirm_password">
            <el-input
              v-model="passwordForm.confirm_password"
              :type="confirm_eye ? 'text' : 'password'"
              placeholder="请确认新密码">
              <template #suffix>
                <bg-icon @click="confirm_eye = !confirm_eye" class="icon_eye" icon="#bg-ic-eye"></bg-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEdit">取消</el-button>
          <el-button type="primary" @click="editConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { watch, nextTick, reactive, ref, computed, onBeforeMount } from "vue";
import { useRoute, useRouter } from "vue-router";
import CryptoJS from "crypto-js";
import axios from "@/request/http.js";
import { ElMessage } from "element-plus";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";

const dataTable = ref(null);
const headers = ref([
  {
    label: "姓名",
    prop: "name",
    minWidth: 160,
  },
  {
    label: "手机号",
    prop: "phone",
    minWidth: 160,
  },
  {
    label: "账号",
    prop: "system_account",
  },
  {
    label: "所属组织",
    prop: "org_name",
    minWidth: 180,
  },
  {
    label: "创建时间",
    prop: "created_time",
    width: 160,
  },
  {
    label: "是否启用",
    prop: "state",
  },
  {
    label: "操作",
    prop: "action",
    width: 220,
    fixed: "right",
  },
]);
const tableRows = ref([]);
const filter = reactive({
  search: "",
  page: 1,
  limit: 10,
});
const tableTotal = ref(0);
const deleteFlag = ref(false);
const deleteRowFlag = ref(false);
const resetFlag = ref(false);
const selectedRow = ref({});
const selected = ref([]);
const selectedName = ref([]);
const editFlag = ref(false);
const password_eye = ref(false);
const confirm_eye = ref(false);
const passwordRef = ref(null);
const passwordForm = reactive({
  password: "",
  confirm_password: "",
});
const selectNode = ref(null);
const selectNodeObj = ref(null);
const filterTree = ref("");
const treeRef = ref(null);
const validatePass = (rule, value, callback) => {
  if (value !== passwordForm.password) {
    callback(new Error("密码输入不一致"));
  } else {
    callback();
  }
};

const passwordFormRules = reactive({
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, message: "密码长度不得低于8位", trigger: "blur" },
  ],
  confirm_password: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
});

const router = useRouter();
const route = useRoute();
const getTableRows = () => {
  let params = { ...filter, organization_id: selectNode.value };
  axios
    .get(`/v1/api/org/detail`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        tableRows.value = res.data.data?.org_users?.data || [];
        tableTotal.value = res.data.data?.org_users?.total || 0;
      } else {
        ElMessage.error(res.data.data);
      }
    });
};

const addAccount = () => {
  router.push({
    path: "/authority/user/add",
  });
};

const handleNodeClick = (data) => {
  if (data.data_type > 0) {
    selectNode.value = data.organization_id;
    changePage(1);
  } else {
    nextTick(() => {
      treeRef.value.setCurrentKey(null);
    });
  }
};

const orgData = ref([]);
const customNodeClass = (data, node) => {
  if (data.data_type == 0) {
    return "noFocus";
  } else {
    return "";
  }
};
const defaultProps = {
  label: "name",
  children: "Child",
  value: "organization_id",
  class: customNodeClass,
};
const getOrgTree = () => {
  axios.get(`/v1/api/org/tree`).then((res) => {
    if (res.data.code == 200) {
      orgData.value = res.data.data || [];
      // orgData.value.shift();
      const orgList = searchOrg(orgData.value);
      if (route.query.organization_id) {
        searchItem(orgData.value, route.query.organization_id);
      } else {
        selectNode.value = orgList.length > 0 ? orgList[0].organization_id : "";
      }
      nextTick(() => {
        if (route.query.organization_id) {
          treeRef.value.setCurrentNode(selectNodeObj.value);
        } else {
          if (orgList.length > 0) {
            treeRef.value.setCurrentNode(orgList[0]);
          }
        }
      });
      getTableRows();
    } else {
      ElMessage.error(res.data.data);
    }
  });
};
const searchItem = (data, organization_id) => {
  data.forEach((e) => {
    if (e.organization_id == organization_id) {
      selectNodeObj.value = e;
      selectNode.value = e.organization_id;
    } else {
      if (e.Child) {
        searchItem(e.Child, organization_id);
      }
    }
  });
};
const searchOrg = (data) => {
  const arr = [];
  data.forEach((item) => {
    if (item.data_type > 0) {
      arr.push(item);
      return;
    } else {
      if (item.Child) {
        searchOrg(item.Child);
      } else {
        return;
      }
    }
  });
  return arr;
};

watch(filterTree, (val) => {
  treeRef.value.filter(val);
});

const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};

const stateChange = (row) => {
  console.log("row", row);
  const params = {
    id: row.id,
    state: row.state,
  };
  axios.post(`/v1/api/user/updateState`, params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      getTableRows();
    } else {
      ElMessage.error(res.data.data);
      row.state = row.state == 0 ? 1 : 0;
    }
  });
};

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

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

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

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

const editAccount = (id) => {
  router.push({
    path: "/authority/user/edit",
    query: {
      id: id,
    },
  });
};

const deleteAccount = (data) => {
  if (data.state === 0) {
    selectedRow.value = data;
    deleteRowFlag.value = true;
  } else {
    ElMessage.error("当前状态已启用，不可删除！");
  }
};

const handleCloseDelete = () => {
  deleteFlag.value = false;
};
const handleCloseRowDelete = () => {
  deleteRowFlag.value = false;
};

const deleteConfirm = () => {
  const ids = selected.value.map((item) => item.id);
  axios.delete(`/v1/api/user/del`, { data: { ids: ids } }).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      getTableRows();
    } else {
      ElMessage.error(res.data.data);
    }
    handleCloseDelete();
  });
};

const deleteRowConfirm = () => {
  axios.delete(`/v1/api/user/del`, { data: { ids: [selectedRow.value.id] } }).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      getTableRows();
    } else {
      ElMessage.error(res.data.data);
    }
    handleCloseRowDelete();
  });
};

const deleteBatch = () => {
  if (selectedName.value.length > 0) {
    deleteFlag.value = true;
  } else {
    ElMessage.error("请先选择需要操作的数据!");
  }
};

const handleCloseReset = () => {
  resetFlag.value = false;
};

const resetPsd = () => {
  if (selectedName.value.length > 0) {
    resetFlag.value = true;
  } else {
    ElMessage.error("请先选择需要操作的数据!");
  }
};

const resetConfirm = () => {
  const ids = selected.value.map((item) => item.id);
  axios.post(`/v1/api/user/resetPwd`, { ids: ids }).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      getTableRows();
    } else {
      ElMessage.error(res.data.data);
    }
    handleCloseReset();
  });
};

const editPsdAccount = (data) => {
  selectedRow.value = data;
  editFlag.value = true;
};

const handleCloseEdit = () => {
  if (!passwordRef) return;
  passwordRef.value.resetFields();
  editFlag.value = false;
  password_eye.value = false;
  confirm_eye.value = false;
};
const editConfirm = () => {
  if (!passwordRef) return;
  passwordRef.value.validate((valid, fields) => {
    if (valid) {
      axios
        .post(`/v1/api/user/updatePwd`, {
          id: selectedRow.value.id,
          password: CryptoJS.AES.encrypt(passwordForm.password, "swuE9cmCZQwrkYRV").toString(),
        })
        .then((res) => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
          } else {
            ElMessage.error(res.data.data);
          }
          handleCloseEdit();
        });
    }
  });
};

const selectRows = (data) => {
  selected.value = data.selection;
  selectedName.value = data.selection.map((item) => item.system_account);
};

const clearSelected = () => {
  dataTable.value.clearTable();
};

onBeforeMount(() => {
  getOrgTree();
  //getTableRows()
});
</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: auto;
  height: calc(100% - 65px);
}
.tree :deep() .el-tree-node > .el-tree-node__children {
  overflow: unset;
}
.tree :deep().noFocus:focus > .el-tree-node__content {
  background-color: #fff;
}
.custom_tree_node {
  width: 100%;
  font-size: 14px;
  color: #202531;
  padding-right: 16px;
}
.label-text:hover {
  padding: 3px 0;
  background-color: var(--el-tree-node-hover-bg-color);
}
.main_container {
  height: 100%;
}
.table_container {
  height: calc(100% - 30px);
  overflow: auto;
  padding: 0 16px;
}

.pagination_box {
  position: sticky;
  position: -webkit-sticky;
  margin-top: 16px;
  bottom: 25px;
  background-color: #fff;
  z-index: 1024;
  height: 40px;
  line-height: 40px;
  padding-top: 5px;
}
.bg-pagination {
  bottom: unset;
  margin-top: 0px;
}
</style>
