<template>
  <div class="bf-postmanagementadd">
    <div class="postmanagementadd_header">
      <div class="postmanagementadd_top">
        <div class="tltleLeft">{{ pageTitle }}</div>
        <div v-is="doesGroupExist ? ['group_btn_edit'] : ['group_btn_save']" 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="`${accountGroupType}名称`">
            <el-input v-model.trim="editForm.name" :placeholder="`请输入${accountGroupType}名称`" />
          </el-form-item>
          <el-form-item label="描述" prop="desc" style="margin-left: 40px">
            <el-input v-model.trim="editForm.desc" style="width: 640px" placeholder="请输入描述" />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="content">
      <el-row :gutter="24">
        <el-col :span="8">
          <div class="part">
            <AccountGroupTree :title="`上级${accountGroupType}`" nodekey="GroupId" :single-node="doesGroupExist ? GroupUpId : 0" :type="true" :default-props="defaultProps" :checked-keys="accountGroupTreeCheckedList" @getTreeData="getAccountGroupChecked" />
          </div>
        </el-col>
        <!-- 开启角色 -->
        <template v-if="openRole">
          <el-col :span="8">
            <div class="part">
              <RoleList title="角色列表" :role-type="roleType" :group-ids="groupIds" :check-box-list="roleListCheckedList" :number="8" :active="true" :selected-role-id="currentSelectedRoleId" @checkChange="getRoleListChecked" @checkClick="selectRole" @role-list-change="roleListCheckedFilter" />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="part">
              <PermissionList title="权限列表" :role-list="checkedRoles" :check="true" @Competen="Competen" />
            </div>
          </el-col>
        </template>
        <!-- 无角色 -->
        <template v-else>
          <el-col :span="8">
            <div class="part">
              <PermissionTree title="权限树" :checked-keys="permissionTreeChckedKeys" :query-type="queryType" :query-ids="queryIds" @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'
import { lengthValidator } from '@/utils/validate'

export default {
  components: {
    AccountGroupTree,
    PermissionTree,
    RulesOfCompetency,
    RoleList,
    PermissionList
    // Dialog
  },
  // mixins: [treeData],
  data () {
    return {
      doesGroupExist: this.$route.meta.doesGroupExist, // 控制岗位新增/编辑
      GroupId: 0,
      GroupUpId: parseInt(this.$route.query.GroupUpId),
      // dialogVisible: false,
      openRole: 0,
      accountGroupTreeCheckedList: [], // 岗位树初始勾选项
      accountGroupTreeCheckedTemp: [], // 岗位树当前勾选项
      roleListCheckedList: [], // 角色列表初始勾选项
      roleListCheckedCopy: [],
      roleListCheckedTemp: [], // 角色列表当前勾选项
      permissionTreeChckedKeys: [], // 权限树初始勾选项
      permissionTreeChckedTemp: [], // 权限树当前勾选项
      rulesOfCompetency: null, // 当前编辑的权限规则
      queryType: '',
      roleType: '',
      groupIds: [],
      queryIds: [],
      currentSelectedRoleId: -1,
      checkedRoles: [],
      editForm: {
        name: '',
        desc: '',
        isUsed: 0
      },
      rules: {
        // 表单验证
        name: [
          { required: true, message: `请输入${this.accountGroupType}名称`, trigger: 'blur' },
          { validator: lengthValidator, max: 128, message: '长度在 1 到 128 个字符', trigger: ['change', 'blur'] }
        ],
        desc: [{ validator: lengthValidator, max: 256, message: '长度在 1 到 256 个字符', trigger: ['change', 'blur'] }]
      },
      defaultProps: {
        children: 'children',
        label: 'GroupName'
      }
    }
  },
  computed: {
    ...mapGetters(['systemSet']),
    pageTitle () {
      return this.doesGroupExist ? `编辑${this.accountGroupType}` : `新增${this.accountGroupType}`
    }
  },
  created () {
    // 获取系统配置
    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.accountGroupTreeCheckedTemp = [this.GroupUpId]
    this.doesGroupExist && (this.GroupId = parseInt(this.$route.query.GroupId))
  },
  mounted () {
    if (this.GroupUpId !== -1) {
      this.roleType = 'group'
      this.groupIds = [this.GroupUpId]
      this.queryType = 'group'
      this.queryIds = [this.GroupUpId]
    } else {
      this.groupIds = [-1]
      this.roleType = 'onlyRole'
      this.queryIds = [-1]
      this.queryType = 'all'
    }
    if (this.doesGroupExist) {
      this.getGroupDetails()
    }
    this.accountGroupTreeCheckedList = [this.GroupUpId]
  },
  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.roleListCheckedTemp.push(role),
                  this.roleListCheckedCopy.push(role),
                  this.roleListCheckedList.push(role.RoleId))
            })
          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) {
      this.permissionTreeChckedTemp = arr.map(auth => auth.AuthList)
    },
    // 获取当前勾选的岗位
    getAccountGroupChecked (arr) {
      if (arr?.length === 0) {
        this.accountGroupTreeCheckedList = [-1]
      } else if (arr?.length === 1) {
        if (arr[0].GroupId === -1) {
          this.accountGroupTreeCheckedTemp = [-1]
          this.groupIds = [-1]
          this.roleType = 'onlyRole'
          this.queryIds = [-1]
          this.queryType = 'all'
        } else {
          const GroupIds = arr.map(item => item.GroupId)
          this.accountGroupTreeCheckedTemp = GroupIds
          this.roleType = 'group'
          this.groupIds = GroupIds
          this.queryType = 'group'
          this.queryIds = GroupIds
        }
      }
    },
    // 角色选取
    getRoleListChecked (arr) {
      this.roleListCheckedTemp = arr
      this.roleListCheckedCopy = arr
    },
    roleListCheckedFilter (arr) {
      this.roleListCheckedTemp = this.roleListCheckedCopy.filter(
        role => arr.findIndex(item => item.RoleId === role.RoleId) > -1
      )
      this.roleListCheckedList = this.roleListCheckedCopy.map(role => role.RoleId)
      if (arr.findIndex(item => item.RoleId === this.currentSelectedRoleId) === -1) {
        this.checkedRoles = []
        this.currentSelectedRoleId = -1
      }
    },
    // 获取当前编辑的权限规则
    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')
          }, 1000)
        } 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>
