<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">
      <div class="authForm">
        <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="auth_id">
              <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>
          <template v-if="tableForm.show_type != 3" :span="12">
            <el-form-item label="状态" size="default" prop="auth_status">
              <el-radio-group v-model="ruleForm.auth_status" size="default">
                <el-radio-button :label="true">开启</el-radio-button>
                <el-radio-button :label="false">关闭</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-form>
      </div>
      <div v-if="ruleForm.auth_type == 1" class="diacont">
        <el-form :model="tableForm" label-width="85px" ref="systemconfiguration">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="菜单类型" size="default" prop="menuType">
                <el-radio-group v-model="tableForm.show_type" size="default">
                  <el-radio-button :label="1">目录</el-radio-button>
                  <el-radio-button :label="2">菜单</el-radio-button>
                  <el-radio-button :label="3">按钮</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图标" size="default">
                <el-select style="width: 100%" v-model="tableForm.show_icon" class="input-shadow" filterable default-first-option clearable placeholder="">
                  <el-option v-for="item in tableOptionser" :key="item.v" :label="item.k" :value="item.v">
                    <el-icon :size="20">
                      <component :is="item.k"></component>
                    </el-icon>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单编码" size="default" prop="code">
                <el-input v-model="tableForm.code" placeholder="请输入菜单编码" />
              </el-form-item>
            </el-col>
            <el-col v-if="tableForm.show_type == 2" :span="12">
              <el-form-item label="查询模板ID" size="default" prop="queryTemplateID">
                <el-input v-model="tableForm.queryTemplateID" placeholder="请输入queryTemplateID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" size="default" prop="show_index">
                <el-input v-model="tableForm.show_index" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col v-if="tableForm.show_type != 3" :span="12">
              <el-form-item label="是否外链" size="default" prop="is_link">
                <el-radio-group v-model="tableForm.is_link" size="default">
                  <el-radio-button :label="1">是</el-radio-button>
                  <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="路由地址" size="default" prop="route_info">
                <el-input v-model="tableForm.route_info" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col v-if="tableForm.show_type == 3" :span="12">
              <el-form-item label="路由参数" size="default" prop="queryparams">
                <el-input v-model="tableForm.queryparams" placeholder="多个参数用,分割" />
              </el-form-item>
            </el-col>
            <el-col v-if="tableForm.show_type != 3" :span="12">
              <el-form-item label="是否显示" size="default" prop="is_show">
                <el-radio-group v-model="tableForm.is_show" size="default">
                  <el-radio-button :label="1">是</el-radio-button>
                  <el-radio-button :label="0">否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col v-if="tableForm.show_type == 2" :span="12">
              <el-form-item label="组件路径" size="default" prop="file_link">
                <el-input v-model="tableForm.file_link" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, watch } from "vue";
import { CloseBold } from "@element-plus/icons-vue";
import Dialog from "@/components/dialog/index.vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { GeneralDataReception } from "@/api/dataIntegration";
import * as _ from "lodash";
import tree from "../hooks/useTree";
import icons from "../hooks/useIcons";
const formRules = useElement().formRules;
//当前选中数据
const currData = ref<any>({});
//当前要删除的数据
const delObj = ref<any>({});
//下级权限数据
const childrenData = ref<any>([]);
//默认展开
const currentKey = ref([-1]);
//权限树
const data = ref<any>([]);
//删除弹框
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<any>({
  auth_name: "",
  auth_type: "",
  auth_comment: "",
  app_name: "",
  auth_ident: "",
  app_id: "",
  auth_status: true,
  auth_id: "",
});
const tableOptionser = icons; //弹窗下拉
const tableForm = ref<any>({
  show_type: "",
  show_icon: "",
  show_index: "",
  is_link: 0,
  route_info: "",
  file_link: "/templatePage/page/index.vue",
  is_show: 1,
  queryTemplateID: "",
  code: "",
  queryparams: "",
});
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 () => {
  const res = await tree.getTree();
  data.value = res.value;
};

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

watch(
  () => ruleForm,
  (newValue) => {
    const { auth_ident } = newValue.value;
    tableForm.value.code = auth_ident;
    tableForm.value.route_info = "/" + auth_ident;
  },
  { deep: true }
);

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

//启用禁用
const renderChange = (data) => {
  if (data.children) {
    delete data.children;
  }
  data.event = 2;
  changeAuth(data);
};

// 重置表单
const resetFormData = (data) => {
  ruleForm.value.app_id = data.app_id ?? "";
  ruleForm.value.app_name = data.app_name ?? "";
  ruleForm.value.auth_comment = data.auth_comment ?? "";
  ruleForm.value.auth_id = data.auth_id ?? "";
  ruleForm.value.auth_ident = data.auth_ident ?? "";
  ruleForm.value.auth_name = data.auth_name ?? "";
  ruleForm.value.auth_status = data.auth_status ?? "";
  ruleForm.value.auth_type = data.auth_type ?? "";
  ruleForm.value.up_auth_id = data.up_auth_id ?? "";
  tableForm.value.show_type = data.show_type ?? "";
  tableForm.value.show_icon = data.show_icon ?? "";
  tableForm.value.show_index = data.show_index ?? "";
  tableForm.value.code = data.code ?? "";
  tableForm.value.is_link = data.is_link ?? "";
  tableForm.value.is_show = data.is_show ?? "";
  tableForm.value.route_info = data.route_info ?? "";
  tableForm.value.file_link = data.file_link ?? "";
  tableForm.value.queryTemplateID = data.queryTemplateID ?? "";
};

//修改
const renderEdit = (data) => {
  optionsApp.value = [];
  optionsParent.value = [];
  editDialogVisible.value = true;
  editDialogTitle.value = "编辑下级权限";
  editType.value = "edit";
  data.is_link = data.is_link ? 1 : 0;
  data.is_show = data.is_show ? 1 : 0;
  resetFormData(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 isEmptyObj = (obj: object) => Object.keys(obj).length === 0;

//新增
const addAuth = () => {
  if (isEmptyObj(currData.value)) {
    ElMessage.error("请选择权限后再操作");
    return false;
  }
  resetFormData({});
  ruleForm.value.auth_type = currData.value.auth_type;
  ruleForm.value.auth_id = currData.value.auth_id;
  ruleForm.value.auth_status = true;
  tableForm.value.is_link = 0;
  tableForm.value.is_show = 1;
  tableForm.value.file_link = "/templatePage/page/index.vue";
  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();
    childrenData.value = [];
  } 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 = 1;
        ruleForm.value.event = 1;
        if (ruleForm.value.auth_id) {
          ruleForm.value.up_auth_id = ruleForm.value.auth_id;
          delete ruleForm.value.auth_id;
        }
        const obj = Object.assign(ruleForm.value, tableForm.value);
        changeAuth(obj, "form");
      } else {
        ruleForm.value.event = 2;
        const obj = Object.assign(ruleForm.value, tableForm.value);
        changeAuth(obj, "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>