<template>
  <div id="RoleManage">
    <FormBlock :title="$t('module.userManage.affiliation')" direction="column" style="width:300px;float:left">
      <el-tree :data="orgTree" :load="loadData" lazy ref="orgTree" :props="orgTreeProps" @node-click="onTreeChange"></el-tree>
    </FormBlock>
    <div class="run-mod-box">
      <PageTable ref="roleTable" action="QueryRole" :columnsFn="columns">
        <Form ref="roleFormSearch" slot="search-bar" :model="formSearch" :label-width="100">
          <Row>
            <Col span="8">
              <Form-item prop="roleName" :label="$t('module.role.roleName')">
                <Input type="text" maxlength="30" v-model="formSearch.roleName" :placeholder="$t('module.role.warning.enterRoleName')"></Input>
              </Form-item>
            </Col>
            <Col span="8">
              <Form-item prop="enabled" :label="$t('common.status')">
                <Select v-model="formSearch.enabled" clearable>
                  <Option value=1>{{$t("common.enable")}}</Option>
                  <Option value=0>{{$t("common.disable")}}</Option>
                </Select>
              </Form-item>
            </Col>
          </Row>
        </Form>
        <div slot="handle-bar">
          <Button v-bind:disabled="isButtonDisabled" @click.native="reset" type="text">{{$t("common.reset")}}</Button>
          <Button v-bind:disabled="isButtonDisabled" @click.native="search" type="ghost">{{$t("common.search")}}</Button>
        </div>
        <div slot="table-bar">
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="plus-round" @click="add">{{$t("common.create")}}</Button>
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="trash-a" @click="deleted()">{{$t("common.delete")}}</Button>
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="unlocked" @click="toggleLock(1)">{{$t("common.enable")}}</Button>
          <Button type="ghost" v-bind:disabled="isButtonDisabled" icon="locked" @click="toggleLock(0)">{{$t("common.disable")}}</Button>
        </div>
      </PageTable>
    </div>
    <!-- 权限编辑窗口 -->
    <Modal v-model="permissionModal" width="650">
      <p slot="header">
        <span>{{ rolePermissonModalTitle }}</span>
      </p>
      <div class="run-modal-style">
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
          <div style="height: 280px;overflow-y: auto;overflow-x: hidden">
            <el-tree :data="baseData" :show-checkbox="true" ref="roleMenusTree" :props="treeProps" node-key="menuId" default-expand-all></el-tree>
          </div>
          </Col>
        </Row>
      </div>
      <Spin size="large" fix v-if="isQueryMenusAndBtns"></Spin>
      <div slot="footer" class="run-modal-ftbButton">
        <Button type="primary" :loading="saveLoading" @click="onOk()">{{$t("common.confirm")}}</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Three from "../../../tools/getThree.js";
import RoleUserListMg from "./RoleUserListManage.vue";
import AssignDimension from "../dimension/AssignDimension.vue";
import RoleEdit from "./RoleEdit.vue";
export default {
  name: 'role-manage',
  components: {
    'AssignDimension': AssignDimension
  },
  data() {
    return {
      isQueryMenusAndBtns: false,
      rolePermissonModalTitle: this.$t('module.role.permissionMaList'),
      permissionModal: false,
      tableData: [],
      formInfo: {
        orgName: "",
        roleName: "",
        remark: "",
        roleId: "",
        menuIds: "",
        effectBegin: "",
        effectEnd: "",
        roleCode: ""
      },
      baseData: [],
      treeProps: {
        label: "title",
        children: "children"
      },
      formSearch: {
        enabled: "",
        roleName: "",
        orgPath: "",
        orgId: ""
      },
      saveLoading: false,
      originMenuBtns: [], //存储从后台查询的原始功能及资源数据
      menuIdMap: {}, //key:menuId,value:parentID
      checkedNodes: [], //待选中的节点列表
      selectedMenuIds: [], //保存所有的已选中的功能ID
      selectedBtnIds: [], //保存所有的已选中的资源ID
      // 组织树
      orgTree: [],
      orgTreeProps: {
        children: 'children',
        label: 'orgName'
      },
      rootOrg: {},
      isButtonDisabled: true
    };
  },
  computed: {},

  created: function () {
  },

  mounted: function () {
  },

  methods: {
    columns(){
      return [
        {
          type: "selection",
          width: 55,
          fixed: 'left',
          align: "center"
        },
        {
          title: this.$t("common.operating"),
          align: "center",
          fixed: 'left',
          width: 85,
          render: (h, params) => {
            return h("RowTools", {
              props: {
                data: [
                  {
                    type: "icon",
                    icon: "md-create",
                    text: this.$t("common.edit"),
                    handle: () => {
                      this.edit(params.row.roleId, params.row.version);
                    }
                  },
                  this.getDimension(params.row.roleId, params.row.version),
                  {
                    type: "icon",
                    icon: "person-stalker",
                    text: this.$t("module.role.memberManage"),
                    handle: () => {
                      new this.$sidelipPage(RoleUserListMg, {
                        props: {
                          roleId: params.row.roleId
                        }
                      });
                    }
                  }
                ]
              }
            });
          }
        },
        {
          title: this.$t("module.role.roleName"),
          key: "roleName",
          sortable: "custom",
          minWidth: 80,
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.roleName
              }
            }, params.row.roleName);
          }
        },
        {
          title: this.$t('module.userManage.affiliation'),
          sortable: "custom",
          key: "orgName",
          align: "center",
          width: 130,
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.orgName
              }
            }, params.row.orgName);
          }
        },
        {
          title: this.$t("module.role.roleCode"),
          sortable: "custom",
          key: "roleCode",
          minWidth: 80,
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.roleCode
              }
            }, params.row.roleCode);
          }
        },
        {
          title: this.$t("module.role.effectBegin"),
          sortable: "custom",
          align: "center",
          key: "effectBegin",
          render: (h, params) => {
            return h("span", {}, this.getDateString(params.row.effectBegin));
          },
          width: 120
        },
        {
          title: this.$t("module.role.effectEnd"),
          sortable: "custom",
          align: "center",
          key: "effectEnd",
          render: (h, params) => {
            return h("span", {}, this.getDateString(params.row.effectEnd));
          },
          width: 110
        },
        {
          title: this.$t("common.remark"),
          key: "remark",
          align: "center",
          width: 160,
          render: (h, params) => {
            return h('div', {
              attrs: {
                class: 'ivu-table-cell ivu-table-cell-ellipsis',
                title: params.row.remark
              }
            }, params.row.remark);
          }
        },
        {
          title: this.$t("common.status"),
          align: "center",
          key: "enabled",
          width: 100,
          render: (h, params) => {
            console.log(params.row.enabled, !!params.row.enabled);
            return h(
              "Tag",
              {
                props: {
                  type: "dot",
                  color: !!params.row.enabled ? "blue" : "red"
                }
              },
              !!params.row.enabled ? this.$t("module.userManage.enabled") : this.$t("module.userManage.frozen")
            );
          }
        }
      ]
    },
    // 加载当前组织子节点
    loadData(currentOrg, callback) {
      this.$store.dispatch("QueryOrg", { "orgId": currentOrg.data.orgId }).then(response => {
        if (response.statusCode == "0") {
          var childrenOrg = response.dataResult.depList;
          if (childrenOrg.length > 0) {
            //记录根节点
            if (currentOrg.level === 0) {
              this.rootOrg = childrenOrg[0];
            }
          }
          callback(childrenOrg);
        } else {
          this.$Message.error(response.msg);
        }
      });
    },
    search(page) {
      // 选择根组织时，级联查询下级角色
      var orgPath = this.$refs["orgTree"].getCurrentNode().orgPath;
      // if (this.rootOrg.orgPath == orgPath) {
      //   this.formSearch.orgPath = "";
      // } else {
      //   this.formSearch.orgPath = orgPath;
      // }
      //点击树节点查询该节点下面左右子节点的角色
      this.formSearch.orgPath = orgPath;
      this.$refs["roleTable"].load(this.formSearch, page);
    },
    reset() {
      this.$refs["roleFormSearch"].resetFields();
      this.search(1);
    },
    toggleLock(status) {
      let ids = this.getIds();
      if (ids == "") {
        this.$Message.warning({
          content: `${this.$t("module.role.selectWant")}  ${status == 0 ? this.$t("common.disable") : this.$t("common.enable")} ${this.$t("module.role._role")}`,
          duration: 1.5
        });
        return;
      }
      new $confirm(`${this.$t("common.confirm")}${status == 0 ? this.$t("common.disable") : this.$t("common.enable")}?`, this).then(() => {
        this.$store.dispatch("ToggleLockRole", {
          ids,
          status
        }).then(res => {
          if (!res.success) {
            this.$Message.warning({
              content: res.msg,
              duration: 3
            });
            return;
          }
          this.search();
        });
      });
    },
    editPermisson(id, version) {
      //编辑功能及资源权限
      this.permissionModal = true;
      this.formInfo.roleId = id;
      this.isQueryMenusAndBtns = true;
      this.$store
        .dispatch("QueryMenusAndBtns", {
          commonPageDTO: {
            currentPage: 1,
            pageSize: 10000
          },
          roleId: id
        })
        .then(res => {
          this.isQueryMenusAndBtns = false;
          // console.log(new Three(res).json);
          this.baseData = new Three(res.data).json;
          this.$refs["roleMenusTree"].setCheckedKeys(res.checkList);
          // this.originMenuBtns = res;
          // this.initBaseDataAndCheckedNodesArray(this.originMenuBtns, 0);//three.json;
          // this.baseData = this.originMenuBtns;
          // console.log(this.checkedNodes);
          // console.log(this.menuIdMap);
          // console.log(this.baseData);

          // this.initCheckedTree();
        });
    },
    editDimension(roleId, version) {
      new this.$pageModal(
        AssignDimension,
        {
          props: {
            objectId: roleId
          }
        }, (data) => {
          // this.roles = [].concat(data);
        });
    },
    // initBaseDataAndCheckedNodesArray(menuBtns, parentId) {
    //   this.baseData = [];
    //   this.checkedNodes = [];
    //   this.menuIdMap = {};
    //   this.recursiveGetChildrenMenu(menuBtns, parentId);
    // },
    // recursiveGetChildrenMenu(menuJsonObject, parentMenuId) {
    //   if (menuJsonObject && Array.isArray(menuJsonObject)) {
    //     for (let item of menuJsonObject) {
    //       this.recursiveGetMenuItem(item, parentMenuId);
    //     }
    //   } else {
    //     this.recursiveGetMenuItem(menuJsonObject, parentMenuId);
    //   }
    // },
    // recursiveGetMenuItem(item, parentId) {
    //   //解析单个功能节点
    //   this.menuIdMap[item.id] = parentId;
    //   if (item.checked && item.checked == 'true') {
    //     //需要被选中的节点
    //     this.checkedNodes.push(item.id);
    //   }
    //   if (item.children && item.children.length > 0) {
    //     //递归遍历子节点
    //     this.recursiveGetChildrenMenu(item.children, item.id);
    //   }
    // },
    edit(id, version) {
      new this.$sidelipPage(RoleEdit, {
        className: 'editSidelipWarp',
        props: {
          roleId: id,
          version: version
        }
      }, data => {
        this.search();
      });
    },
    deleted() {
      let deleteStr = this.getIds();
      if (!deleteStr || deleteStr == undefined || deleteStr == "") {
        this.$Message.warning(this.$t("module.role.warning.selectRole"));
      }
      if (deleteStr == "" || deleteStr == undefined) return;
      new $confirm(this.$t("module.role.warning.ensureToDelete"), this).then(() => {
        this.$store
          .dispatch("DeleteRole", {
            roleIds: deleteStr
          })
          .then(res => {
            if (!res.success) {
              this.$Message.warning({
                content: res.msg,
                duration: 3
              });
              return;
            }
            this.search();
          });
      });
    },
    add() {
      this.baseData = [];
      // 当前组织
      if(this.$refs["orgTree"].getCurrentNode()){
        var orgId = this.$refs["orgTree"].getCurrentNode().orgId;
        var orgName = this.$refs["orgTree"].getCurrentNode().orgName;
      }else{
        var orgId = this.rootOrg.orgId;
        var orgName = this.rootOrg.orgName;
      }
      // //默认有效期
      // var date = new Date();
      // var month = date.getMonth() + 1;
      // var currentDate = date.getFullYear() + "-" + month + "-" + date.getDate();
      // var endDate =
      //   date.getFullYear() + 50 + "-" + month + "-" + date.getDate();

      // this.formInfo = {
      //   orgId: orgId,
      //   orgName: orgName,
      //   roleName: "",
      //   roleCode: "",
      //   remark: "",
      //   roleId: "",
      //   menuIds: "",
      //   effectBegin: currentDate,
      //   effectEnd: endDate
      // };
      new this.$sidelipPage(
        RoleEdit,
        {
          props: {
            orgId: orgId,
            orgName: orgName,
          }
        }, (data) => {
          this.search();
      });
    },
    onOk() {
      //添加或修改角色权限信息
      let menusList = this.$refs["roleMenusTree"].getCheckedNodes();
      let menuIds = [];
      let btnIds = [];
      for (let item of menusList) {
        if (!!item.btnCode) {
          btnIds.push(item.menuId);
          menuIds.push(item.menuModuleId);
        } else {
          menuIds.push(item.menuId);
        }
      }
      menuIds = menuIds.join(",");
      btnIds = btnIds.join(",");
      if (this.formInfo.roleId) {
        this.saveLoading = true;
        this.$store
          .dispatch("SaveMenusAndBtns", {
            menuIds,
            btnIds,
            roleId: this.formInfo.roleId
          })
          .then(res => {
            this.baseData = [];
            this.permissionModal = false;
            this.saveLoading = false;
            if (!res.success) {
              this.$Message.warning({
                content: res.msg,
                duration: 3
              });
              return;
            }
            this.$Message.success({
              content: this.$t("module.role.warning.permissionUpdateSuccess"),
              duration: 3
            });
            this.search();
          });
      }
    },
    getIds() {
      let list = this.$refs["roleTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.roleId);
      }
      return ids.join(",");
    },
    getDateString(DateStr) {
      if (
        DateStr == undefined ||
        DateStr == null ||
        DateStr == "" ||
        DateStr.trim() == ""
      ) {
        return "";
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(" ")[0].split("-");
      let newDateList = [];
      let newItem = "";
      for(let key = 0; key < dateList.length; key++){
        let newNummber = parseInt(dateList[key]);
        if(newNummber < 10){
          newNummber = "0" + newNummber;
        }
          newDateList.push(newNummber); 
        
      };
      return newDateList.join("-");
    },
    onTreeChange() {
      if(1 == this.$refs["orgTree"].getCurrentNode().checked){
        this.isButtonDisabled = false;
        this.search();
      }else{
        this.isButtonDisabled = true;
        //刷新列表
        this.$refs["roleTable"].tableData = [];
        this.$refs["roleTable"].total = 0;
        this.$refs["roleTable"].param.commonPageDTO.currentPage = 1;
      }
    },
    getDimension(roleId, version){
      let dimensionOperationType = this.$store.state.dimensionOperationType;
      if(dimensionOperationType == 1){
        return {
          type: "icon",
          icon: "gear-b",
          text: this.$t("module.role.dimensionManage"),
          handle: () => {
            this.editDimension(roleId, version);
          }
        };
      }else{
        return {};
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less" scoped>
#RoleManage {
  display: flex;
  .run-mod-box {
    flex: 1;
  }
}
</style>

