<template>
  <div class="permission scroll-y">
    <div class="permission-head rowSS">
      <div class="manageTitle">权限项管理</div>
      <div class="status0"><span class="icon"></span>交互权限</div>
      <div class="status1"><span class="icon"></span>API接口</div>
      <div class="status2"><span class="icon"></span>数据读写</div>
    </div>
    <div class="permission-content rowSS">
      <div class="permission-content-tree box">
        <div class="manageTitle">权限树</div>
        <div class="contentTree">
          <el-tree :data="data" :props="defaultProps" node-key="auth_id" highlight-current :default-expanded-keys="currentKey" :expand-on-click-node="false" @node-click="handleNodeClick" />
        </div>
      </div>
      <div class="permission-content-card box">
        <div class="grid-contentBottom">
          <div class="capTitle rowBS">
            <div class="manageTitle">下级权限</div>
            <div class="btn-create">
              <el-button size="default" plain class="btn-white" @click="addAuth">新增</el-button>
            </div>
          </div>
          <div class="content">
            <template v-if="childrenData.length">
              <el-row :gutter="24">
                <el-col v-for="data in childrenData" :key="data.auth_id" :span="6">
                  <div class="account-left-content-teams">
                    <div class="team">
                      <div class="bg" :class="data.auth_type == 1 ? 'status0' : data.auth_type == 2 ? 'status1' : 'status2'"></div>
                      <div class="list" :class="data.QueryTarget == 1 ? 'activeStatus' : ''">
                        <div class="rowBS info">
                          <div :title="data.auth_name" class="name">
                            {{ data.auth_name }}
                          </div>
                          <div v-if="data.auth_type > 0" class="icon">
                            <el-tooltip effect="dark" :content="`修改${data.auth_name}`" placement="bottom">
                              <span class="cap cap-edit" @click="renderEdit(data)"></span>
                            </el-tooltip>
                          </div>
                        </div>
                        <div v-if="data.auth_type > 0" class="rowBS details">
                          <div class="details-msg">
                            状态：<span :class="data.auth_status ? 'success' : 'error'">{{ data.auth_status ? "启用" : "禁用" }}</span>
                          </div>
                          <div class="details-info">
                            <el-switch v-model="data.auth_status" active-color="#AC014D" @change="renderChange(data)"> </el-switch>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <div v-if="data.auth_type !== 0" class="info-close" @click.stop="onNodeClick(data)">
                        <CloseBold class="icon" :class="data.auth_type === 1 ? 'close1' : data.auth_type > 2 ? 'close2' : ''" />
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </template>
            <template v-else>
              <el-empty description="暂无数据" />
            </template>
          </div>
        </div>
      </div>
    </div>
    <!--删除弹框-->
    <Dialog :flag="flag" msgTitle="删除权限" type="del" :delName="title" @delRest="delRest" @delRemove="remove" />
    <!--新增/编辑-->
    <Dialog :flag="editDialogVisible" :msg-title="editDialogTitle" @submitForm="submitForm(ruleFormRef)" @reset-form="resetForm(ruleFormRef)" width="628px" :show-flag="true">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px" class="demo-ruleForm">
        <el-form-item label="权限名称" prop="auth_name">
          <el-input v-model="ruleForm.auth_name" size="default" placeholder="请输入权限名称" />
        </el-form-item>
        <div class="flex">
          <el-form-item label="权限类型" prop="auth_type">
            <el-select v-model="ruleForm.auth_type" size="default" placeholder="请选择">
              <el-option v-for="(item, index) in optionsType" :key="index" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="父级权限" prop="authParent">
            <el-select v-model="ruleForm.auth_id" size="default" placeholder="请选择">
              <el-option v-for="(item, index) in optionsParent" :key="index" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item class="flex1" label="所属应用" prop="app_name">
          <el-select v-model="ruleForm.app_name" style="display: block" size="default" placeholder="请选择">
            <el-option v-for="(item, index) in optionsApp" :key="index" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标识符" prop="auth_ident">
          <el-input v-model="ruleForm.auth_ident" size="default" type="textarea" :rows="3" placeholder="请输入权限标识符" />
        </el-form-item>
        <el-form-item label="数据项描述" prop="auth_comment">
          <el-input v-model="ruleForm.auth_comment" size="default" type="textarea" :rows="3" placeholder="请输入数据项描述" />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount } from "vue";
import { CloseBold } from "@element-plus/icons-vue";
import Dialog from "@/components/dialog/index.vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { translateDataToTreeAll } from "@/utils/validate";
import { GeneralDataReception, Query } from "@/api/dataIntegration";
import * as _ from "lodash";
//当前选中数据
const currData = ref({});
//当前要删除的数据
const delObj = ref({});
//下级权限数据
const childrenData = ref([]);
//默认展开
const currentKey = ref([-1]);
//权限树
const data = ref([]);
//删除弹框
const flag = ref(false);
//新增编辑弹框
const editDialogVisible = ref(false);
//新增编辑类型
const editType = ref("add");
//删除弹框标题
const title = ref("");
//删除id
const auId = ref("");
//新增编辑弹框-标题
const editDialogTitle = ref("新增下级权限");
//新增编辑弹框-表单
const ruleForm = ref({
  auth_name: "",
  auth_type: "",
  auth_comment: "",
  app_name: "",
  auth_ident: "",
  app_id: "",
  auth_status: true,
});
const optionsType = ref([
  {
    label: "前端权限",
    value: 1,
  },
  {
    label: "API权限",
    value: 2,
  },
  {
    label: "数据权限",
    value: 3,
  },
]);
const optionsParent: any = ref([]);
const optionsApp: any = ref([]);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  auth_name: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
});
const defaultProps = {
  children: "children",
  label: "auth_name",
};

//获取权限树数据
const getAuthTree = async () => {
  try {
    const { returnData, code } = await Query({
      id: DATACONTENT_ID.authTreeNewId,
      dataContent: [sessionStorage.getItem("User_Id")],
    });
    if (code == 0 && returnData.listValues) {
      const obj = {
        auth_id: -1,
        auth_name: "所有权限",
        auth_status: true,
        up_auth_id: -1,
        auth_type: 0,
        disabled: true,
        children: translateDataToTreeAll(
          returnData.listValues,
          "up_auth_id",
          "auth_id"
        ),
      };
      data.value = [obj];
    } else {
      const obj = {
        auth_id: -1,
        auth_name: "所有权限",
        auth_status: true,
        up_auth_id: -1,
        auth_type: 0,
        disabled: true,
        children: [],
      };
    }
    data.value = [obj];
  } catch (error) {}
};

onBeforeMount(() => {
  getAuthTree();
});

//权限树点击
const handleNodeClick = (data) => {
  if (data.children) {
    const newData = _.cloneDeep(data);
    currData.value = newData;
    childrenData.value = newData.children;
  } else {
    childrenData.value = [];
  }
};

//启用禁用
const renderChange = (data) => {
  console.log(data);
};

//修改
const renderEdit = (data) => {
  optionsApp.value = [];
  optionsParent.value = [];
  editDialogVisible.value = true;
  editDialogTitle.value = "编辑下级权限";
  editType.value = "edit";
  ruleForm.value = _.cloneDeep(data);
  optionsApp.value.push({
    label: data.app_name,
    value: data.app_id,
  });
  optionsParent.value.push({
    label: currData.value.auth_name,
    value: data.auth_id,
  });
};
const delRest = () => {
  flag.value = false;
};
//删除弹框
const onNodeClick = (data) => {
  flag.value = true;
  title.value = data.auth_name;
  auId.value = data.auth_id;
  delObj.value = data;
};

//删除
const remove = () => {
  delObj.value.event = 3;
  changeAuth(delObj.value, "del");
  /* const datas = childrenData.value;
  datas.filter((item, index) => {
    if (item.auth_id == auId.value) {
      datas.splice(index, 1);
    }
  });
  flag.value = false;
  ElMessage.success("删除成功");*/
};

//判断对象是否为空
const isEmptyObj = (obj: object) => Object.keys(obj).length === 0;

//新增
const addAuth = () => {
  if (isEmptyObj(currData.value)) {
    ElMessage.error("请选择权限后再操作");
    return false;
  }
  optionsApp.value = [];
  optionsParent.value = [];
  editDialogVisible.value = true;
  editDialogTitle.value = "新增下级权限";
  editType.value = "add";
  optionsApp.value.push({
    label: currData.value.app_name,
    value: currData.value.app_id,
  });
  optionsParent.value.push({
    label: currData.value.auth_name,
    value: currData.value.auth_id,
  });
};

//增删改
const changeAuth = async (obj, type) => {
  const { code, message } = await GeneralDataReception({
    serviceId: SERVICE_ID.authScId,
    dataContent: JSON.stringify(obj),
  });
  if (code == 0) {
    ElMessage.success(message);
    getAuthTree();
  } else {
    ElMessage.error(message);
  }
  if (type == "form") {
    // ruleForm.value = {};
    editDialogVisible.value = false;
  } else if (type == "del") {
    flag.value = false;
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (editType.value == "add") {
        ruleForm.value.app_id = ruleForm.value.app_name;
        ruleForm.value.app_name = currData.value.app_name;
        ruleForm.value.auth_status = true;
        ruleForm.value.event = 1;
        if (ruleForm.value.auth_id) {
          ruleForm.value.up_auth_id = ruleForm.value.auth_id;
          delete ruleForm.value.auth_id;
        }
        changeAuth(ruleForm.value, "form");
      } else {
        ruleForm.value.event = 2;
        changeAuth(ruleForm.value, "form");
      }
      editDialogVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  editDialogVisible.value = false;
};
</script>

<style lang="scss" scoped>
.permission {
  &-head {
    line-height: 35px;
    font-size: 14px;
    margin-bottom: 30px;
    .icon {
      width: 14px;
      height: 14px;
      background: #58c274;
      border-radius: 2px;
      display: inline-block;
      vertical-align: middle;
      margin-right: 10px;
      position: relative;
      top: -2px;
    }
    &:last-child {
      margin-right: 0;
    }

    .status2 {
      margin-left: 28px;
      .icon {
        background: #2d67e3;
      }
    }
    .status0 {
      margin-right: 28px;
      .icon {
        background: #d8b53b;
      }
    }
  }
  &-content {
    height: calc(100% - 65px);
    &-tree {
      width: 504px;
      height: 100%;
      margin-right: 24px;
      .contentTree {
        margin-top: 30px;
      }
    }
    &-card {
      height: 100%;
      flex: 1;
    }
  }
  .account-left-content-teams {
    position: relative;
    margin-top: 24px;
    .info-close {
      position: absolute;
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      background: #000000;
      border-radius: 50%;
      top: -12px;
      right: -12px;
      z-index: 5;
      cursor: pointer;
      .icon {
        color: #fff;
        font-weight: 600;
        width: 12px;
        height: 12px;
      }
    }
    .list {
      background-color: #f5f7fa;
      .info {
        line-height: normal;
        margin-bottom: 37px;
        .name {
          font-size: 16px;
          font-weight: bold;
          max-width: 120px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .cap {
          width: 16px;
          height: 16px;
          display: inline-block;
          background-repeat: no-repeat;
          background-size: 100%;
          transition: all 0.3s;
          margin-left: 16px;
          &:first-child {
            margin-right: 0;
          }
        }
        .cap-plus {
          background-image: url("@/assets/status/ic_plus.png");
          &:hover {
            background-image: url("@/assets/status/ic_plus_hovar.png");
          }
        }
        .cap-edit {
          background-image: url("@/assets/status/ic_edit_default.png");
          &:hover {
            background-image: url("@/assets/status/ic_edit_hovar.png");
          }
        }
        .cap-sub {
          background-image: url("@/assets/status/ic_permissions_add_default.png");
          &:hover {
            background-image: url("@/assets/status/ic_permissions_add_hoavr.png");
          }
        }
        .cap-job {
          background-image: url("@/assets/status/ic_jobs.png");
          &:hover {
            background-image: url("@/assets/status/ic_jobs_hovar.png");
          }
        }
        .cap-member {
          background-image: url("@/assets/status/ic_member.png");
          &:hover {
            background-image: url("@/assets/status/ic_member_hovar.png");
          }
        }
      }
    }
    .team {
      background: #fff;
      border-radius: 4px;
      box-shadow: 0px 3px 3px 0px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      .bg {
        height: 4px;
        background: #6f81bc;
      }
      .status0 {
        background: #d8b53b;
      }
      .status1 {
        background: #58c274;
      }
      .status2 {
        background: #2d67e3;
      }
    }
    .list {
      padding: 23px 24px;
      position: relative;
      min-width: 240px;
      min-height: 118px;
      .info {
        margin-bottom: 20px;
        .info-avoutr {
          display: flex;
          .avoutr {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #303133;
            img {
              max-width: 100%;
            }
          }
          .msg {
            margin-left: 20px;
            p {
              margin: 0;
              padding: 0;
              height: 20px;
              line-height: 20px;
            }
            .name {
              font-weight: bold;
              color: #303133;
              font-size: 18px;
              margin-bottom: 8px;
            }
            .group {
              font-size: 14px;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: #303133;
            }
          }
        }
        .icon {
          font-size: 16px;
          cursor: pointer;
        }
      }
      .time,
      .ip {
        height: 16px;
        line-height: 16px;
        font-size: 16px;
        .glr {
          color: #909399;
        }
      }
      .ip {
        margin-top: 23px;
        margin-bottom: 38px;
      }
      .details {
        height: 24px;
        line-height: 24px;
        font-size: 14px;
        .success {
          color: #2d67e3;
        }
        .error {
          color: #909399;
        }
      }
    }
  }
}
</style>