<template>
  <div class="bf-postmanagementadd">
    <div class="postmanagementadd_header">
      <div class="postmanagementadd_top">
        <div class="tltleLeft">{{ pageTitle }}</div>
        <div
          class="btn"
          style="margin-top: 20px"
        >
          <el-button
            type="primary"
            @click="handleClickSave('editForm')"
          >保存</el-button>
        </div>
      </div>
      <div class="addApp-form-content dialog-public-background">
        <el-form
          ref="editForm"
          :inline="true"
          :rules="rules"
          class="form"
          :model="editForm"
        >
          <el-form-item
            prop="name"
            label="账号组名称"
          >
            <el-input
              v-model="editForm.name"
              maxlength="32"
              placeholder="账号组名称"
            />
          </el-form-item>
          <el-form-item
            label="描述"
            style="margin-left: 40px"
          >
            <el-input
              v-model="editForm.desc"
              style="width: 640px"
              placeholder="请输入描述"
              maxlength="200"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="content">
      <el-row :gutter="24">
        <el-col :span="8">
          <div class="part">
            <AccountGroupTree
              title="上级账号组"
              nodekey="GroupId"
              :type="true"
              :defaultProps="defaultProps"
              :checkedKeys="accountGroupTreeCheckedList"
              @getTreeData="getAccountGroupChecked"
            />
          </div>
        </el-col>
        <!-- 开启角色 -->
        <template v-if="openRole">
          <el-col :span="8">
            <div class="part">
              <RoleList
                title="角色列表"
                :roleType="roleType"
                :GroupIds="accountGroupTreeCheckedTemp"
                :checkBoxList="roleListCheckedList"
                :number="8"
                :active="true"
                @checkChange="getRoleListChecked"
                @checkClick="selectRole"
              />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="part">
              <PermissionList
                title="权限列表"
                class="hucPower"
                :RoleList="checkedRoles"
                :check="true"
                @Competen="Competen"
              />
            </div>
          </el-col>
        </template>
        <!-- 无角色 -->
        <template v-else>
          <el-col :span="8">
            <div class="part">
              <PermissionTree
                title="权限树"
                :checkedKeys="permissionTreeChckedKeys"
                :queryType="queryType"
                :queryIds="accountGroupTreeCheckedTemp"
                @getTreeData="getPermissionTreeChecked"
              />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="part">
              <RulesOfCompetency
                title="权限规则"
                margin-b="20px"
                @getData="getRulesOfCompetency"
              />
            </div>
          </el-col>
        </template>
      </el-row>
    </div>
    <!-- <Dialog :flag="dialogVisible">
      <div class="closeDialog">
        <div class="title">删除账号</div>
        <div class="content">是否确定要删除该账号？</div>
        <div class="foot right t30">
          <el-button
            size="medium"
            class="r24"
          >取消</el-button>
          <el-button
            size="medium"
            type="danger"
          >删除</el-button>
        </div>
      </div>
    </Dialog> -->
  </div>
</template>
<script>
import AccountGroupTree from '@/components/usergrouptree/index.vue'
import PermissionTree from '@/components/permissiontree/index.vue'
import RulesOfCompetency from '@/components/rulesofcompetency/index.vue'
import RoleList from '@/components/rolelist/index.vue'
import PermissionList from '@/components/permissionlist/index.vue'
// import Dialog from '@/layout/components/Dialog/index.vue'

import { RoleAuths } from '@/api/apiAuthority'
import { GetGroupDetails, EditGroup, SaveGroup } from '@/api/AccountGroup.js'
// import treeData from '../minixs/treeData'
import { mapGetters } from 'vuex'

export default {
  components: {
    AccountGroupTree,
    PermissionTree,
    RulesOfCompetency,
    RoleList,
    PermissionList
    // Dialog
  },
  // mixins: [treeData],
  data() {
    return {
      doesGroupExist: this.$route.meta.doesGroupExist, // 控制账号组新增/编辑
      GroupId: 0,
      GroupUpId: Number(this.$route.query.GroupUpId),
      // dialogVisible: false,
      openRole: 0,
      accountGroupTreeCheckedList: [], // 账号组树初始勾选项
      accountGroupTreeCheckedTemp: [], // 账号组树当前勾选项
      roleListCheckedList: [], // 角色列表初始勾选项
      roleListCheckedTemp: [], // 角色列表当前勾选项
      permissionTreeChckedKeys: [], // 权限树初始勾选项
      permissionTreeChckedTemp: [], // 权限树当前勾选项
      rulesOfCompetency: null, // 当前编辑的权限规则
      queryType: '',
      roleType: '',
      currentSelectedRoleId: 0,
      checkedRoles: [],
      editForm: {
        name: '',
        desc: '',
        isUsed: 0
      },
      rules: {
        // 表单验证
        name: [{ required: true, message: '请输入账号组名称', trigger: 'blur' }]
      },
      defaultProps: {
        children: 'children',
        label: 'GroupName'
      }
    }
  },
  computed: {
    ...mapGetters(['systemSet']),
    pageTitle() {
      return this.doesGroupExist ? '编辑账号组' : '新增账号组'
    }
  },
  created() {
    console.log(typeof this.GroupUpId)
    let obj
    if (typeof this.systemSet === 'string') {
      obj = JSON.parse(this.systemSet)
    } else {
      obj = this.systemSet
    }
    // console.log(obj)
    const { OpenRole } = obj
    this.openRole = OpenRole
    this.queryType = this.GroupUpId === -1 ? 'all' : 'group'
    this.accountGroupTreeCheckedTemp = [this.GroupUpId]
  },
  mounted() {
    this.roleType = this.GroupUpId === -1 ? 'onlyRole' : 'roleByUpId'
    this.accountGroupTreeCheckedList = [this.GroupUpId]
    if (this.doesGroupExist) {
      this.GroupId = this.$route.query.GroupId
      this.getGroupDetails()
    }
  },
  methods: {
    // 账号组详情
    async getGroupDetails() {
      try {
        const res = await GetGroupDetails({
          GroupId: this.GroupId
        })
        if (res.code === 0) {
          const { GroupDesc, GroupName, Status, AuthList, RoleList } = res.returnData
          this.editForm.name = GroupName
          this.editForm.desc = GroupDesc
          this.editForm.isUsed = Status
          // this.$store.dispatch('auth/changeAuthList', AuthList)

          RoleList &&
            RoleList.length &&
            RoleList.forEach(role => {
              role.IsSelected && (this.roleListCheckedList.push(role.RoleId), this.roleListCheckedTemp.push(role))
            })

          AuthList &&
            AuthList.length &&
            AuthList.forEach(auth => {
              this.permissionTreeChckedKeys.push(auth.AuthId)
              this.permissionTreeChckedTemp.push(auth)
            })
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    // 保存
    handleClickSave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSaveEdit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取当前权限树勾选项
    getPermissionTreeChecked(arr) {
      // console.log(arr)
      this.permissionTreeChckedTemp = arr.map(auth => auth.AuthList)
    },
    // 获取当前勾选的账号组
    getAccountGroupChecked(arr) {
      if (arr && arr.length && arr[0] !== -1) {
        this.queryType = 'group'
        this.roleType = 'roleByUpId'
        const GroupUpId = arr[0].GroupId
        this.accountGroupTreeCheckedTemp = [GroupUpId]
      } else {
        this.queryType = 'all'
        this.roleType = 'onlyRole'
        this.accountGroupTreeCheckedTemp = [-1]
      }
    },
    // 角色选取
    getRoleListChecked(arr) {
      this.roleListCheckedTemp = arr
    },
    // 获取当前编辑的权限规则
    getRulesOfCompetency(obj) {
      this.rulesOfCompetency = obj
    },
    // 点击角色后显示对应权限列表
    async selectRole(data) {
      if (this.currentSelectedRoleId === data.RoleId) return
      try {
        const params = {
          RoleId: data.RoleId
        }
        const res = await RoleAuths(params)
        if (res.code === 0) {
          this.checkedRoles = res.returnData
          this.currentSelectedRoleId = data.RoleId
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    // 删除账号组
    // async deleteAuth() {
    //   this.dialogVisible = true;
    // },
    // async delAcc() {
    //   try {
    //     const res = await DelAccGroup({
    //       GroupId: this.GroupId,
    //     });
    //     if (res.code === 0) {
    //       this.$message.success(res.message);
    //       setTimeout(() => {
    //         this.$router.push("/AccountGroup");
    //       }, 2000);
    //     } else {
    //       this.$message.error(res.message);
    //     }
    //   } catch (error) {
    //     console.log("出错了", error);
    //   }
    // },
    // 修改权限规则
    Competen(data) {
      console.log(data)
    },
    // 账号组编辑保存
    async handleSaveEdit() {
      const params = {
        AuthList: this.permissionTreeChckedTemp,
        GroupName: this.editForm.name,
        GroupDesc: this.editForm.desc,
        GroupUpid: this.accountGroupTreeCheckedTemp[0],
        RoleList: this.roleListCheckedTemp
      }

      if (this.doesGroupExist) {
        this.saveEditGroup({
          ...params,
          GroupId: this.GroupId,
          Status: this.editForm.isUsed || 0
        })
      } else {
        this.saveAddGroup(params)
      }
    },
    async saveEditGroup(params) {
      try {
        const res = await EditGroup(params)
        if (res.code === 0) {
          this.$message.success(res.message)
          setTimeout(() => {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push('/accountGroup')
          }, 2000)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    async saveAddGroup(params) {
      try {
        const res = await SaveGroup(params)
        if (res.code === 0) {
          this.$message.success(res.message)
          setTimeout(() => {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push('/accountGroup')
          }, 1000)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.bf-postmanagementadd {
  width: 100%;
  padding: 30px 64px;
  ::v-deep > .postmanagementadd_header {
    width: 100%;
    height: 184px;
    background: #ffffff;
    box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
    border-radius: 16px;
    padding: 0 32px 0 32px;
    margin-bottom: 24px;
    > .postmanagementadd_top {
      width: 100%;
      height: 88px;
      display: flex;
      position: relative;
      justify-content: space-between;
      margin-bottom: 16px;

      .tltleLeft {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-top: 20px;
      }
      .isUsed {
        margin-top: 20px;
        position: absolute;
        left: 194px;
        top: 6px;
      }
      > .but {
        height: 40px;
      }
    }
    > .postmanagementadd_list {
      width: 100%;
      display: flex;
      > .list_up {
        display: flex;
        margin-right: 40px;
        > p {
          white-space: nowrap;
          text-overflow: ellipsis;
          font-size: 14px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #303133;
          margin-top: 0;
          margin-bottom: 0;
          display: flex;
          align-items: center;
          margin-right: 16px;
        }
        > .el-input {
          width: 184px;
          height: 32px;
          background: #f9fbff;
          border-radius: 6px;
          > .el-input__inner {
            width: 100%;
            height: 100%;
            background: #f9fbff;
            border-radius: 6px;
          }
        }
        > .el-textarea {
          width: 640px;
          height: 33px;
          border-radius: 4px;
          .el-textarea__inner {
            width: 100%;
            height: 100%;
            background: #f9fbff;
            border: 1px solid #d7dae3;
            border-radius: 4px;
            resize: none;
          }
        }
      }
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 184px);
    padding-top: 24px;
    box-sizing: border-box;
    // .el-row {
    //   height: 100%;
    //   .el-col {
    //     height: 100%;
    //   }
    // }
    .part {
      width: 100%;
      height: 856px;
      background: #ffffff;
      box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
      border-radius: 16px;
    }
    .last {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .part2 {
      width: 100%;
      height: 512px;
      background: #ffffff;
      box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
      border-radius: 16px;
    }
    .part3 {
      width: 100%;
      height: 320px;
      background: #ffffff;
      box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
      border-radius: 16px;
      margin-top: 25px;
      overflow: hidden;
    }
  }
}
</style>
