<template>
  <div class="auth scroll-y">
    <div class="flex auth-content">
      <div class="box role-info auth-list">
        <div class="manageTitle">角色信息</div>
        <div class="role-info-content t30">
          <el-form ref="ruleFormRef" :model="ruleForm" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="role_name">
              <el-input disabled v-model="ruleForm.role_name" size="default" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="role_comment">
              <el-input disabled v-model="ruleForm.role_comment" size="default" type="textarea" :rows="3" placeholder="请输入角色描述" />
            </el-form-item>
            <el-form-item label="是否启用" prop="role_status">
              <el-radio-group disabled v-model="ruleForm.role_status">
                <el-radio label="1">启用</el-radio>
                <el-radio label="2"> 禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="box auth-list">
        <div class="manageTitle">权限树</div>
        <div class="t30">
          <el-tree ref="treeRef" highlight-current @check="currentChange" :default-expanded-keys="checkKeys" :data="data" show-checkbox :props="defaultProps" node-key="auth_id" @node-click="handleNodeClick">
            <template #default="{data}">
              <span class="custom-tree-node">
                {{ data.auth_name }}
              </span>
              <span v-if="
              data.edit_col_condition ||
              data.delete_row_condition ||
              data.edit_row_condition ||
              data.new_col_condition ||
              data.query_col_conditon ||
              data.query_row_condition" class="custom-tree-icon"></span>
            </template>
          </el-tree>
        </div>
      </div>
      <div class="box auth-list">
        <div class="flex">
          <div class="manageTitle">权限规则</div>
          <el-radio-group v-model="auth">
            <el-radio label="1">显示权限</el-radio>
            <el-radio label="2">显示及编辑权限</el-radio>
          </el-radio-group>
        </div>
        <div class="t30">
          <el-form :model="form" class="demo-ruleForm">
            <el-form-item label="许可查询行">
              <el-input size="default" v-model="form.query_row_condition" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="许可查询列">
              <el-input size="default" v-model="form.query_col_conditon" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="许可删除行">
              <el-input size="default" v-model="form.delete_row_condition" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="许可新增列">
              <el-input size="default" v-model="form.new_col_condition" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="许可编辑行">
              <el-input size="default" v-model="form.edit_row_condition" placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="许可编辑列">
              <el-input size="default" v-model="form.edit_col_condition" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, watch } from "vue";
import { Query, GeneralDataReception } from "@/api/dataIntegration";
import { translateDataToTreeAll } from "@/utils/validate";
import { ElMessage, ElTree } from "element-plus";
import tree from "../hooks/useTree";
import * as _ from "lodash";
const route = useRoute();
const role_id = route.query.role_id;
const ruleForm = ref({
  role_name: "",
  role_comment: "",
  role_status: "",
});
const auth = ref("1");
const form = ref({
  query_row_condition: "",
  query_col_conditon: "",
  delete_row_condition: "",
  new_col_condition: "",
  edit_row_condition: "",
  edit_col_condition: "",
});
const maxReq = ref(20);
const proAll = ref<any>([]);
const proNum = ref(0);
const checkObj = ref<any>(null);
const data = ref<any>([]);
const newData = ref<any>([]);
const checkData = ref<any>([]);
const checkKeys = ref<any>([-1]);
const boxData = ref<any>([]);
const treeRef = ref<InstanceType<typeof ElTree>>();
onBeforeMount(() => {
  roleDetails();
  getTree();
});

watch(
  () => form,
  (newValue) => {
    newData.value.forEach((item) => {
      if (item.children) {
        delete item.children;
      }
      if (item.auth_id == checkObj.value.auth_id) {
        item = Object.assign(item, newValue.value);
      }
    });
    checkKeys.value = [checkObj.value.auth_id];
    toTree();
  },
  { deep: true }
);

//角色详情
const roleDetails = async () => {
  try {
    const { code, message, returnData } = await Query({
      id: DATACONTENT_ID.roleDetailsId,
      dataContent: [role_id],
    });
    if (code == 0) {
      ruleForm.value = returnData.listValues[0];
    } else {
      ElMessage.error(message);
    }
  } catch (error) {}
};

const toTree = () => {
  data.value = [];
  const chks = treeRef.value!.getCheckedNodes(false, true);
  const arr = translateDataToTreeAll(newData.value, "up_auth_id", "auth_id");
  const items = {
    auth_id: -1,
    auth_name: "所有权限",
    auth_status: 0,
    up_auth_id: -2,
    auth_type: 0,
    children: arr,
    disabled: true,
  };
  data.value = [items];
  if (chks && chks.length) {
    checkBox(chks, newData.value);
  }
};

//权限树
const getTree = async () => {
  try {
    const { returnData, code } = await Query({
      id: DATACONTENT_ID.authTreeNewId,
      dataContent: [sessionStorage.getItem("User_Id")],
    });
    if (code == 0 && returnData.listValues) {
      newData.value = _.cloneDeep(returnData.listValues);
      toTree();
      roleAuths();
    } else {
    }
  } catch (error) {}
  // const res = await tree.getTree();
  // newData.value = await tree.newData.value;
  // data.value = res.value;
};

const checkBox = (arr, all) => {
  const checks: any = [];
  const nots = _.cloneDeep(arr);
  const caps = _.cloneDeep(all);
  arr.forEach((item) => {
    checks.push(item.auth_id);
  });
  const res = [...caps, ...nots].filter(
    (item) =>
      !(
        caps.some((p) => item.auth_id == p.auth_id) &&
        nots.some((c) => item.auth_id == c.auth_id)
      )
  );
  treeRef.value!.setCheckedKeys(checks);
  setTimeout(() => {
    res.forEach((item) => {
      treeRef.value!.setChecked(item.auth_id, false, false);
    });
  }, 0);
};

//权限详情
const roleAuths = async () => {
  try {
    const { code, message, returnData } = await Query({
      id: DATACONTENT_ID.roleAuthId,
      dataContent: [role_id],
    });
    if (code == 0 && returnData.listValues) {
      boxData.value.push(returnData.listValues);
      checkBox(returnData.listValues, newData.value);
    } else {
      ElMessage.error(message);
    }
  } catch (error) {}
};

const handleNodeClick = (data) => {
  checkObj.value = data;
  checkData.value.push(_.cloneDeep(data));
  const datas = _.unionBy(checkData.value, "auth_id");
  checkData.value = datas;
  const checkNode = checkData.value.filter(
    (item) => item.auth_id == data.auth_id
  );
  if (checkNode.length) {
    const formObj = checkNode[0];
    form.value = formObj;
  } else {
    clearFormData();
  }
};

const clearFormData = () => {
  form.value.query_row_condition = "";
  form.value.query_col_conditon = "";
  form.value.delete_row_condition = "";
  form.value.new_col_condition = "";
  form.value.edit_row_condition = "";
  form.value.edit_col_condition = "";
};

const currentChange = () => {
  const datas = treeRef.value!.getCheckedNodes(false, true);
  datas.forEach((item, index) => {
    if (item.auth_id == -1) {
      datas.splice(index, 1);
    }
  });
  boxData.value.push(datas);
  const data1 = boxData.value[boxData.value.length - 1]; //最后一条数据
  const data2 = boxData.value[boxData.value.length - 2]; //倒数第二条数据
  if (data1.length > data2.length) {
    checksBoxTs(data1, data2, "add");
  } else {
    checksBoxTs(data2, data1, "del");
  }
};

const checksBoxTs = async (datas, arr, type) => {
  const res = [...datas, ...arr].filter(
    (item) =>
      !(
        datas.some((p) => item.auth_id == p.auth_id) &&
        arr.some((c) => item.auth_id == c.auth_id)
      )
  );
  const [msg1, msg2] = [<any>[], <any>[]];
  if (res && res.length) {
    for (let i = 0; i < res.length; i++) {
      delete res[i].children;
      let obj = <any>{
        auth_id: res[i].auth_id || res[i].AuthId,
        role_id: role_id,
      };
      let authObj = res[i].AuthList
        ? Object.assign(_.cloneDeep(obj), res[i].AuthList)
        : Object.assign(_.cloneDeep(obj), res[i]);
      if (type == "add") {
        obj.event = 1;
        authObj.event = 1;
        msg1.push(obj);
        msg2.push(authObj);
      } else {
        obj.event = 3;
        authObj.event = 3;
        msg1.push(obj);
        msg2.push(authObj);
      }
    }
    GeneralDataReception({
      serviceId: SERVICE_ID.roleMsgTreeId,
      dataContent: JSON.stringify(msg1),
    }).then((result) => {
      if (result.code == 0) {
        if (type == "add") {
          ElMessage.success("操作权限成功");
        } else {
          ElMessage.success("操作权限成功");
        }
      } else {
        if (type == "add") {
          ElMessage.error("操作权限失败");
        } else {
          ElMessage.error("操作权限失败");
        }
      }
    });
    if (msg2.length > maxReq.value) {
      foxFunc(msg2);
    } else {
      GeneralDataReception({
        serviceId: SERVICE_ID.roleMsgAuthId,
        dataContent: JSON.stringify(msg2),
      }).then((result) => {
        if (result.code == 0) {
          if (type == "add") {
            ElMessage.success("操作规则成功");
          } else {
            ElMessage.success("操作规则成功");
          }
        } else {
          if (type == "add") {
            ElMessage.error("操作规则失败");
          } else {
            ElMessage.error("操作规则失败");
          }
        }
      });
    }
  } else {
    // this.$message.error('未选中数据')
  }
};

const foxFunc = async (arr?: Array<any>) => {
  if (proAll.value.length == 0) {
    proAll.value = _.cloneDeep(arr);
  }
  const limit = _.chunk(proAll.value, maxReq.value);
  const reqUts = [];
  limit.forEach((item, index) => {
    const req = GeneralDataReception({
      serviceId: SERVICE_ID.roleMsgAuthId,
      dataContent: JSON.stringify(limit[index]),
    });
    reqUts.push(req);
  });
  const result = Promise.all(reqUts);
  const resultLen = await result;
  if (limit.length == resultLen.length) {
    proAll.value = [];
    proNum.value = 0;
    ElMessage.success("操作规则成功");
  } else {
    proNum.value += 1;
    if (proNum.value == 4) {
      ElMessage.success("网络错误，请稍后重试");
    } else {
      foxFunc();
    }
  }
};

const defaultProps = {
  children: "children",
  label: "auth_name",
};
</script>

<style lang="scss" scoped>
.auth {
  &-content {
    height: 100%;
  }
  &-list {
    flex: 1;
    margin-right: 24px;
    &:last-child {
      margin-right: 0;
    }
    :deep .el-tree {
      .custom-tree-icon {
        position: absolute;
        right: 0;
        width: 14px;
        height: 14px;
        background: url("@/assets/index/ic_date.png") no-repeat;
        background-size: 100% 100%;
      }
    }
  }
}
</style>