<template>
  <div class="data-info">
    <el-card>
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataRef"
        label-width="140px"
      >
        <el-form-item label="角色名称:" prop="name">
          <el-input v-model="dataForm.name"></el-input>
        </el-form-item>
        <el-form-item label="是否为管理员:" prop="is_admin">
          <el-select
            v-model="dataForm.is_admin"
            placeholder="请选择是否为管理员"
            size="large"
            style="width: 100%"
            @change="selChange"
          >
            <el-option
              v-for="item in adminOptions"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="权限配置:">
              <div
                style="
                  width: 100%;
                  height: 300px;
                  overflow: hidden;
                  overflow-y: auto;
                  padding: 10px;
                "
              >
                <el-checkbox
                  v-model="allChecked.nodeTree"
                  @change="(val) => handleCheckAllChange('nodeTree', val)"
                  >全选</el-checkbox
                >
                <el-tree
                  ref="nodeTree"
                  style="max-width: 600px"
                  :props="treeProps"
                  :data="treeData"
                  default-expand-all
                  node-key="value"
                  show-checkbox
                  @check="handleNodeCheck"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="模板分类授权:">
              <div
                style="
                  width: 100%;
                  height: 150px;
                  overflow: hidden;
                  overflow-y: auto;
                  padding: 10px;
                "
              >
                <el-tree
                  ref="templateCate"
                  style="max-width: 600px"
                  :props="defaultProps"
                  :data="templateCate"
                  default-expand-all
                  node-key="id"
                  :default-checked-keys="defaultCheckedKeys.templateCate"
                  show-checkbox
                  @check="handleTemplateCheck"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文档分类授权:">
              <div
                style="
                  width: 100%;
                  height: 150px;
                  overflow: hidden;
                  overflow-y: auto;
                  padding: 10px;
                "
              >
                <el-tree
                  ref="docCate"
                  style="max-width: 600px"
                  :props="defaultProps"
                  :data="documentCate"
                  default-expand-all
                  :default-checked-keys="defaultCheckedKeys.documentCate"
                  node-key="id"
                  show-checkbox
                  @check="handleDocCheck"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原始数据分类授权:">
              <div
                style="
                  width: 100%;
                  height: 150px;
                  overflow: hidden;
                  overflow-y: auto;
                  padding: 10px;
                "
              >
                <el-tree
                  ref="sourceDataTree"
                  style="max-width: 600px"
                  :props="defaultProps"
                  :data="sourceDataCate"
                  default-expand-all
                  node-key="id"
                  show-checkbox
                  :default-checked-keys="defaultCheckedKeys.sourceDataCate"
                  @check="handleSourceDataCheck"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色状态:">
          <el-select
            v-model="dataForm.status"
            placeholder="请选择状态"
            size="large"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.status"
              :label="item.name"
              :value="item.status"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="介绍:">
          <el-input type="textarea" v-model="dataForm.intro"></el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <div style="text-align: right; margin-top: 20px">
      <el-button type="warning" @click="btnSave">确认保存</el-button>
    </div>
  </div>
</template>

<script>
import {
  createAdminRole,
  updateAdminRole,
  getAdminRoleInfo,
  selectPermissions,
} from "@/api/AdminRole";

import { searchDocumentCategory } from "@/api/document";
import { searchSourceDataCategory } from "@/api/sourceData";
import { searchAdminAuth } from "@/api/AdminAuth";
import { getAllCategory } from "@/api/template";
export default {
  emits: ["onClose"],
  props: {
    dataId: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    dataId: {
      handler(v) {
        let _this = this;
        if (v == null || v <= 0) return;
        _this.getInfo(v);
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      activeName: "base",
      treeProps: {
        children: "children",
        label: "label",
      },
      defaultProps: {
        children: "children",
        label: "codename",
      },
      treeData: [],
      dataForm: {
        id: "",
        name: "",
        is_admin: "",
        intro: "",
        status: 5,
      },
      statusOptions: [
        {
          status: 5,
          name: "启用",
        },
        {
          status: 6,
          name: "禁用",
        },
      ],
      adminOptions: [
        {
          status: 1,
          name: "是",
        },
        {
          status: 2,
          name: "否",
        },
      ],
      pickedItem: [],
      templateCate: [],
      documentCate: [],
      sourceDataCate: [],
      allChecked: {
        nodeTree: false,
        templateCate: false,
        docCate: false,
        sourceDataTree: false,
      },
      defaultCheckedKeys: {
        templateCate: [],
        documentCate: [],
        sourceDataTree: [],
      },
      dataRule: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        is_admin: [
          { required: true, message: "请选择是否为管理员", trigger: "change" },
        ],
      },
    };
  },

  mounted() {
    this.initNodeList();
    this.initTemplateCate();
    this.initDocCategory();
    this.initSourceDataCate();
  },
  methods: {
    /* 管理选选择 */
    selChange(val) {
      if (val == 1) {
        this.handleCheckAllChange("nodeTree", true);
        this.handleTemplateAllChange(true);
        this.handleSourceDataAllChange(true);
        this.handleDocumentCateAllChange(true);
      } else {
        this.handleCheckAllChange("nodeTree", false);
        this.handleTemplateAllChange(false);
        this.handleSourceDataAllChange(false);
        this.handleDocumentCateAllChange(false);
      }
    },
    handleTemplateAllChange(checked) {
      const tree = this.$refs.templateCate;
      if (checked) {
        this.defaultCheckedKeys.templateCate = [1, 2, 3, 4];
        tree.setCheckedKeys(this.defaultCheckedKeys.templateCate);
      } else {
        this.defaultCheckedKeys.templateCate = [];
        tree.setCheckedKeys([]);
      }
      this.allChecked.templateCate = checked;
    },

    /* 全选原始数据分类 */
    handleSourceDataAllChange(checked) {
      const tree = this.$refs.sourceDataTree;
      if (checked) {
        this.defaultCheckedKeys.sourceDataCate = [9, 10, 11, 12];
        tree.setCheckedKeys(this.defaultCheckedKeys.sourceDataCate);
      } else {
        this.defaultCheckedKeys.sourceDataCate = [];
        tree.setCheckedKeys([]);
      }
      this.allChecked.sourceDataTree = checked;
    },

    handleDocumentCateAllChange(checked) {
      const tree = this.$refs.docCate;
      if (checked) {
        this.defaultCheckedKeys.documentCate = [5, 6, 7, 8];
        tree.setCheckedKeys(this.defaultCheckedKeys.documentCate);
      } else {
        this.defaultCheckedKeys.documentCate = [];
        tree.setCheckedKeys([]);
      }
      this.allChecked.docCate = checked;
    },

    handleSourceDataCheck() {
      const tree = this.$refs.sourceDataTree;
      console.log(tree);
      const checkedCount = tree.getCheckedNodes(true).length;
      const totalCount = this.countAllNodes(this.sourceDataCate);
      this.allChecked.sourceDataTree =
        checkedCount === totalCount && totalCount > 0;
    },
    /* 原始数据分类 */
    initSourceDataCate() {
      let _this = this;
      selectPermissions({ content_type_id: 3 }).then((res) => {
        if (res.status !== 200) return;
        _this.sourceDataCate = res.data;
      });
    },
    /* 全选文档分类 */
    handleDocAllChange(treeRef) {
      const tree = this.$refs[treeRef];
      const data = this.documentCate;
      tree.setCheckedNodes(
        this.allChecked[treeRef] ? this.flattenTree(data) : []
      );
    },

    handleDocCheck() {
      const tree = this.$refs.docCate;
      const checkedCount = tree.getCheckedNodes(true).length;
      const totalCount = this.countAllNodes(this.documentCate);
      this.allChecked.docCate = checkedCount === totalCount && totalCount > 0;
    },
    /* 文档分类 */
    initDocCategory() {
      let _this = this;
      selectPermissions({ content_type_id: 2 }).then((res) => {
        if (res.status !== 200) return;
        _this.documentCate = res.data;
      });
      /*  searchDocumentCategory({ page: 1, pageSize: 9999, status: 5 }).then(
        (res) => {
          if (res.status != 200) return;
          _this.documentCate = [
            {
              action: "view",
              type: "docCate",
              isMain: true,
              name: "查看",
              label: "查看",
            },
            {
              action: "create",
              type: "docCate",
              isMain: true,
              name: "创建",
              label: "创建",
            },
            {
              action: "edit",
              type: "docCateg",
              isMain: true,
              name: "编辑",
              label: "编辑",
            },
            {
              action: "delete",
              type: "docCateg",
              isMain: true,
              name: "删除",
              label: "删除",
            },
          ]; 
        }
      ); */
    },
    /* 全选模版分类 
    handleTemplateAllChange(treeRef) {
      const tree = this.$refs[treeRef];
      const data = this.templateCate;
      tree.setCheckedNodes(
        this.allChecked[treeRef] ? this.flattenTree(data) : []
      );
    },*/

    handleTemplateCheck() {
      const tree = this.$refs.templateCate;
      const checkedCount = tree.getCheckedNodes(true).length;
      const totalCount = this.countAllNodes(this.templateCate);
      this.allChecked.templateCate =
        checkedCount === totalCount && totalCount > 0;
    },

    flattenTree(tree) {
      return tree.reduce((acc, node) => {
        if (node.children && node.children.length > 0) {
          return [...acc, node, ...this.flattenTree(node.children)];
        }
        return [...acc, node];
      }, []);
    },

    countAllNodes(nodes) {
      return nodes.reduce((count, node) => {
        if (node.children && node.children.length > 0) {
          return count + 1 + this.countAllNodes(node.children);
        }
        return count + 1;
      }, 0);
    },
    //初始化模板分类
    initTemplateCate() {
      let _this = this;
      selectPermissions({ content_type_id: 1 }).then((res) => {
        if (res.status !== 200) return;
        _this.templateCate = res.data;
      });
    },
    /* 权限配置全选 */
    handleCheckAllChange(treeRef, checked = true) {
      const tree = this.$refs[treeRef];
      tree.setCheckedNodes(checked ? this.treeData : []);
      this.allChecked.nodeTree = checked;
    },

    handleNodeCheck() {
      const tree = this.$refs.nodeTree;
      const checkedCount = tree.getCheckedNodes().length;
      const totalCount = this.countAllNodes(this.treeData);
      this.allChecked.nodeTree = checkedCount === totalCount;
    },

    countAllNodes(nodes) {
      let count = 0;
      for (const node of nodes) {
        count++;
        if (node.children) {
          count += this.countAllNodes(node.children);
        }
      }
      return count;
    },
    /* 权限配置 */
    initNodeList() {
      let _this = this;
      searchAdminAuth({ page: 1, pageSize: 999, status: 5 }).then((res) => {
        if (res.status != 200) {
          _this.treeData = [];
          return;
        }
        /*      let dataList=this.$store.state.user.authList   {
            value: 5,
            label: "产品管理",
            children: [],
            sub: false,
          }*/
        let data = [
          {
            value: 1,
            label: "项目管理",
            children: [],
            sub: false,
          },
          {
            value: 5,
            label: "产品管理",
            children: [],
            sub: false,
          },
          {
            value: 4,
            label: "客户管理",
            children: [],
            sub: false,
          },
          {
            value: 10,
            label: "文档管理",
            children: [],
            sub: false,
          },
          {
            value: 32,
            label: "知识库管理",
            children: [],
            sub: false,
          },
          {
            value: 37,
            label: "小程序管理",
            children: [],
            sub: false,
          },
          
          {
            value: 21,
            label: "系统设置",
            children: [],
            sub: false,
          },
        ];

        let viewAuth = res.data.filter(
          (o) => o.parent_id != 99 && o.parent_id != 999
        );
        let controlAuth = res.data.filter((o) => o.parent_id == 999);

        let items = [];
        data.map((item) => {
          item.children = viewAuth
            .filter((o) => o.parent_id == item.value)
            .map((subItem) => {
              let sub = {
                value: subItem.id,
                label: subItem.name,
                sub: true,
                children: controlAuth
                  .filter((o) => o.parent_id == subItem.id)
                  .map((res) => {
                    let item = {
                      value: res.id,
                      label: res.name,
                      sub: true,
                    };
                    return item;
                  }),
              };
              return sub;
            });
          if (item.children.length > 0) {
            items.push(item);
          }
        });
        _this.treeData = items;
      });
    },

    //保存更新
    btnSave(e) {
      let _this = this;
      _this.$refs.dataRef.validate((valid) => {
        if (valid) {
          let items = _this.$refs.nodeTree.getCheckedNodes();

          let templateCate = _this.$refs.templateCate.getCheckedNodes();
          let docCate = _this.$refs.docCate.getCheckedNodes();
          let sourceDataTree = _this.$refs.sourceDataTree.getCheckedNodes();

          let operation_id;
          templateCate = templateCate.map((el) => {
            operation_id = el.id;
            return { operation_id: el.id };
          });
          docCate = docCate.map((el) => {
            el.operation_id = el.id;
            return { operation_id: el.id };
          });
          sourceDataTree = sourceDataTree.map((el) => {
            el.operation_id = el.id;
            return { operation_id: el.id };
          });

          _this.dataForm.template_cate_auth = JSON.stringify(templateCate);
          _this.dataForm.doc_cate_auth = JSON.stringify(docCate);
          _this.dataForm.source_cate_auth = JSON.stringify(sourceDataTree);
          let pickedItem = items.filter((o) => o.sub == true);
          _this.dataForm.authList = JSON.stringify(pickedItem);
          let data = { ..._this.dataForm };
          data.attrs = JSON.stringify(data.attrs);
          if (_this.dataForm.id > 0) {
            updateAdminRole(data).then((res) => {
              if (res.status != 200) return;
              _this.$alert("更新角色信息成功");
              _this.$router.push({
                path: "/system/role/index",
              });
              _this.$emit("onClose");
            });
          } else {
            createAdminRole(data).then((res) => {
              if (res.status != 200) return;
              _this.$alert("创建角色信息成功");
              _this.$router.push({
                path: "/system/role/index",
              });
              _this.$emit("onClose");
            });
          }
        }
      });
    },

    //产品详情
    getInfo(id) {
      let _this = this;
      let par = {
        id: id,
      };
      getAdminRoleInfo(par).then((res) => {
        if (!res) return;
        if (res.status != 200) return;
        _this.dataForm = res.data.info;
        if (res.data.menuList.length > 0) {
          res.data.menuList.map((el) => {
            el.label = el.name;
            el.value = el.id;
          });
          _this.$refs.nodeTree.setCheckedNodes(res.data.menuList);
        } else {
          _this.$refs.nodeTree.setCheckedNodes([]);
        }

        let tempCate = res.data.templateCategoryUsers; //JSON.parse();
        if (tempCate.length > 0) {
          _this.$refs.templateCate.setCheckedKeys(
            tempCate.map((el) => (el.type == 1 ? el.id : ""))
          );
        } else {
          _this.$refs.templateCate.setCheckedKeys([]);
        }

        let sourceCate = res.data.source_cate_auth; //JSON.parse();
        if (sourceCate.length > 0) {
          _this.$refs.sourceDataTree.setCheckedKeys(
            sourceCate.map((el) => (el.type == 1 ? el.id : ""))
          );
        } else {
          _this.$refs.sourceDataTree.setCheckedKeys([]);
        }

        // 设置文档分类树的默认选中节点
        let docCate = res.data.doc_cate_auth;
        if (docCate.length > 0) {
          _this.$refs.docCate.setCheckedKeys(
            docCate.map((el) => (el.type == 1 ? el.id : ""))
          );
        } else {
          _this.$refs.docCate.setCheckedKeys([]);
        }

        //     _this.$refs.docCate.setCheckedNodes(JSON.parse(res.data.doc_cate_auth));
        //     _this.$refs.sourceDataTree.setCheckedNodes(JSON.parse(res.data.source_cate_auth));
      });
    },

    onChangeStatus(e) {
      this.dataForm.status = e;
    },
  },
};
</script>

<style lang="scss">
@import "./dataInfo.scss";
</style>
