<!--
 * @Author: Badguy
 * @Date: 2022-02-15 11:37:42
 * @LastEditTime: 2022-02-23 19:24:51
 * @LastEditors: your name
 * @Description: 编辑账号
 * have a nice day!
-->

<template>
  <div class="account-edit">
    <div class="account-edit-header">
      <div class="title">
        <div class="title-left">{{ pageTitle }}</div>
        <!-- <div class="account-status">
          是否启用
          <el-radio
            v-model="accountForm.status"
            v-if="accountForm.status == 1 || accountForm.status == 3"
            :label="1"
            >是</el-radio
          >
          <el-radio v-model="accountForm.status" v-if="accountForm.status == 2" :label="2"
            >是</el-radio
          >
          <el-radio v-model="accountForm.status" :label="3">否</el-radio>
        </div> -->
        <div>
          <!-- <button type="submmit" class="btn-delete" @click="delate">删除</button> -->
          <button
            type="submmit"
            class="btn-save"
            @click="handleClickSave('accountForm')"
          >保存</button>
        </div>
      </div>
      <div class="title-content">
        <el-form
          ref="accountForm"
          label-width="80px"
          :inline="true"
          :model="accountForm"
          :rules="formRules"
        >
          <el-row :gutter="40">
            <el-col :span="5">
              <el-form-item
                label="账号名称"
                prop="name"
              >
                <el-input
                  v-model="accountForm.name"
                  maxlength="32"
                  placeholder="请输入名称"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                label="登录密码"
                prop="pwd"
              >
                <el-input
                  v-model="accountForm.pwd"
                  placeholder="*******"
                  size="small"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <button
                class="btn-reset-pwd"
                @click="resetPwd"
              >重置密码</button>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="描述"
                prop="desc"
              >
                <el-input
                  v-model="accountForm.desc"
                  maxlength="128"
                  placeholder="描述内容···"
                  size="small"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <div class="content">
      <!-- 用户组和角色未开启 -->
      <el-row
        v-if="!openGroup && !openRole"
        :gutter="24"
      >
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <PermissionTree
              title="权限树"
              :query-type="queryType"
              :checked-keys="permissionTreeChckedKeys"
              @getTreeData="getPermissionTreeChecked"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <RulesOfCompetency
              title="权限规则"
              margin-b="20px"
              @getData="getRulesOfCompetency"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <LoginPolicy
              :checked-list="loginPolicyCheckedList"
              @getCheckedList="getLoginPolicyChecked"
            />
          </div>
        </el-col>
      </el-row>
      <!-- 角色和用户组都开启 -->
      <el-row
        v-if="openGroup && openRole"
        :gutter="24"
      >
        <el-col :span="8">
          <div class="content-card content-card-xl">
            <AccountGroupTree
              title="所属账号组"
              nodekey="GroupId"
              :default-props="accountGroupTreeProps"
              :checked-keys="accountGroupTreeCheckedList"
              @getTreeData="getAccountGroupChecked"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-xl">
            <RoleList
              title="角色列表"
              :role-type="roleType"
              :group-ids="groupIds"
              :check-box-list="roleListCheckedList"
              :number="8"
              :active="true"
              @checkChange="getRoleListChecked"
              @checkClick="selectRole"
              @roleListChange="roleListCheckedChange"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-sm">
            <PermissionList
              title="权限列表"
              class="permission-list"
              :role-list="checkedRoles"
              :check="true"
              @Competen="Competen"
            />
          </div>
          <div class="content-card content-card-xs">
            <LoginPolicy
              :checked-list="loginPolicyCheckedList"
              @getCheckedList="getLoginPolicyChecked"
            />
          </div>
        </el-col>
      </el-row>
      <!-- 只开启用户组 -->
      <el-row
        v-if="openGroup && !openRole"
        :gutter="24"
      >
        <el-col :span="8">
          <div class="content-card content-card-xxl">
            <AccountGroupTree
              title="所属账号组"
              nodekey="GroupId"
              :default-props="accountGroupTreeProps"
              :checked-keys="accountGroupTreeCheckedList"
              @getTreeData="getAccountGroupChecked"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-xxl">
            <PermissionTree
              title="权限树"
              :query-type="queryType"
              :query-ids="queryIds"
              :checked-keys="permissionTreeChckedKeys"
              @getTreeData="getPermissionTreeChecked"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-md">
            <RulesOfCompetency
              title="权限规则"
              margin-b="20px"
              @getData="getRulesOfCompetency"
            />
          </div>
          <div class="content-card content-card-xs">
            <LoginPolicy
              :checked-list="loginPolicyCheckedList"
              @getCheckedList="getLoginPolicyChecked"
            />
          </div>
        </el-col>
      </el-row>
      <!-- 只开启角色 -->
      <el-row
        v-if="!openGroup && openRole"
        :gutter="24"
      >
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <RoleList
              title="角色列表"
              :role-type="roleType"
              :check-box-list="roleListCheckedList"
              :number="8"
              :active="true"
              @checkChange="getRoleListChecked"
              @checkClick="selectRole"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <PermissionList
              title="权限列表"
              :role-list="checkedRoles"
              :check="true"
              class="permission-list"
              @Competen="Competen"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="content-card content-card-lg">
            <LoginPolicy
              :checked-list="loginPolicyCheckedList"
              @getCheckedList="getLoginPolicyChecked"
            />
          </div>
        </el-col>
      </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"
            type="danger"
            class="r24"
          >删除</el-button>
          <el-button size="medium">取消</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 LoginPolicy from '@/components/loginpolicy/index.vue'
import RoleList from '@/components/rolelist/index.vue'
import PermissionList from '@/components/permissionlist/index.vue'
// import Dialog from '@/layout/components/Dialog'

import { RoleAuths } from '@/api/apiAuthority'
import { getAccountDetails, editAccount, addAccount } from '@/api/Account.js'
import { pwdProduce } from '@/utils/validate'
import { mapGetters } from 'vuex'

export default {
  components: {
    AccountGroupTree,
    PermissionTree,
    RulesOfCompetency,
    LoginPolicy,
    RoleList,
    PermissionList
    // Dialog
  },
  data() {
    return {
      doesAccountExist: this.$route.meta.doesAccountExist, // 控制账号新增/编辑
      userId: '',
      openRole: 0,
      openGroup: 0,
      pwdStruc: '',
      pwdLengthBegin: 0,
      pwdLengthEnd: 0,
      permissionTreeChckedKeys: [], // 权限树初始勾选项
      permissionTreeChckedTemp: [], // 权限树当前勾选项
      rulesOfCompetency: null, // 当前编辑的权限规则
      loginPolicyCheckedList: [], // 登录策略初始勾选项
      loginPolicyCheckedTemp: [], // 登录策略当前勾选项
      accountGroupTreeCheckedList: [], // 账号组树初始勾选项
      accountGroupTreeCheckedTemp: [-1], // 账号组树当前勾选项
      roleListCheckedList: [], // 角色列表初始勾选项
      roleListCheckedTemp: [], // 角色列表当前勾选项
      roleType: '',
      queryType: '',
      checkedRoles: [],
      currentSelectedRoleId: 0,
      groupIds: [],
      queryIds: [],
      // dialogVisible: false,
      formRules: {
        name: [
          { required: true, message: '请输入账号名称', trigger: 'blur' },
          { min: 1, max: 32, message: '长度在 1到 32 个字符', trigger: 'blur' }
        ],
        desc: [{ min: 1, max: 128, message: '长度最多128个字符', trigger: 'blur' }]
      },
      accountForm: {
        name: null,
        pwd: null,
        desc: null,
        status: 0
      },
      accountGroupTreeProps: {
        children: 'children',
        label: 'GroupName'
      }
    }
  },
  computed: {
    ...mapGetters(['systemSet']),
    pageTitle() {
      return this.doesAccountExist ? '编辑账号' : '新增账号'
    }
  },
  created() {
    // 获取系统配置
    let obj
    if (typeof this.systemSet === 'string') {
      obj = JSON.parse(this.systemSet)
    } else {
      obj = this.systemSet
    }
    // console.log(obj)
    const { OpenRole, OpenGroup, PwdStruc, PwdLengthBegin, PwdLengthEnd } = obj
    this.openRole = OpenRole
    this.openGroup = OpenGroup
    this.pwdStruc = PwdStruc
    this.pwdLengthBegin = PwdLengthBegin
    this.pwdLengthEnd = PwdLengthEnd
  },
  mounted() {
    if (this.doesAccountExist) {
      this.userId = this.$route.query.userId
      this.getAccountInfo()
    } else {
      this.resetPwd()
      this.roleType = 'onlyRole'
      this.queryType = 'all'
    }
  },
  methods: {
    // 获取当前账号信息
    async getAccountInfo() {
      try {
        const res = await getAccountDetails({
          UserId: this.userId
        })
        if (res.code === 0) {
          // console.log(res.returnData)
          const { UserDesc, UserName, GroupList, TacList, AuthList, RoleList, Status } = res.returnData
          this.accountForm.name = UserName
          this.accountForm.desc = UserDesc
          this.accountForm.status = Status

          AuthList &&
            AuthList.length &&
            AuthList.forEach(auth => {
              this.permissionTreeChckedKeys.push(auth.AuthId)
              this.permissionTreeChckedTemp.push(auth)
            })

          this.accountGroupTreeCheckedTemp = []
          GroupList &&
            GroupList.length &&
            GroupList.forEach(group => {
              this.accountGroupTreeCheckedList.push(group.GroupId)
              this.accountGroupTreeCheckedTemp.push(group.GroupId)
              this.groupIds.push(group.GroupId)
              this.queryIds.push(group.GroupId)
            })

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

          TacList &&
            TacList &&
            TacList.forEach(tac => {
              tac.IsSelected && this.loginPolicyCheckedList.push(tac)
              tac.IsSelected && this.loginPolicyCheckedTemp.push(tac)
            })
          this.roleType = this.openGroup ? 'roleByUpId' : 'onlyRole'
          this.queryType = this.openGroup ? 'group' : 'all'
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    // 随机生成密码
    resetPwd() {
      this.accountForm.pwd = pwdProduce(this.pwdLengthBegin, this.pwdLengthEnd, this.pwdStruc)
    },
    // 获取当前权限树勾选项
    getPermissionTreeChecked(arr) {
      this.permissionTreeChckedTemp = arr.map(auth => auth.AuthList)
    },
    // 获取当前编辑的权限规则
    getRulesOfCompetency(obj) {
      this.rulesOfCompetency = obj
    },
    // 获取当前勾选的登录策略
    getLoginPolicyChecked(arr) {
      this.loginPolicyCheckedTemp = arr
    },
    // 获取当前勾选的账号组
    getAccountGroupChecked(arr) {
      if (arr && arr.length && arr[0] !== -1) {
        const GroupIds = arr.map(item => item.GroupId)
        this.accountGroupTreeCheckedTemp = GroupIds
        this.roleType = 'roleByUpId'
        this.groupIds = GroupIds
        this.queryType = 'group'
        this.queryIds = GroupIds
      } else {
        this.accountGroupTreeCheckedTemp = [-1]
        this.roleType = 'onlyRole'
        this.queryType = 'all'
      }
    },
    // 获取当前勾选的角色列表
    getRoleListChecked(arr) {
      this.roleListCheckedTemp = arr
    },
    roleListCheckedChange(arr) {
      if (arr && arr.length) {
        this.roleListCheckedTemp = this.roleListCheckedTemp.filter(role =>
          arr.some(data => data.RoleId === role.RoleId)
        )
      } else {
        this.roleListCheckedTemp = []
      }
      this.roleListCheckedList = this.roleListCheckedTemp.map(role => role.RoleId)
    },
    // 点击角色后显示对应权限列表
    async selectRole(data) {
      if (this.currentSelectedRoleId === data.RoleId) return
      try {
        const params = {
          RoleId: data.RoleId
        }
        const result = await RoleAuths(params)
        if (result.code === 0) {
          this.checkedRoles = result.returnData
          this.currentSelectedRoleId = data.RoleId
        } else {
          this.$message.error(result.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    // 修改权限规则
    Competen(data) {
      console.log(data)
    },
    // 账号编辑保存
    handleClickSave(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSaveEdit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleSaveEdit() {
      const params = {
        AuthList: this.permissionTreeChckedTemp,
        GroupList: this.accountGroupTreeCheckedTemp.map(groupId => ({ GroupId: groupId })),
        RoleList: this.roleListCheckedTemp,
        TacList: this.loginPolicyCheckedTemp,
        UserDesc: this.accountForm.desc,
        UserName: this.accountForm.name,
        UserPwd: this.accountForm.pwd
      }
      if (this.doesAccountExist) {
        this.saveEditAccount({
          ...params,
          UserId: this.userId,
          Status: this.accountForm.status || 0
        })
      } else {
        this.saveAddAccount(params)
      }
    },
    // 编辑账号
    async saveEditAccount(params) {
      try {
        const res = await editAccount(params)
        if (res.code === 0) {
          this.$message.success(res.message)
          setTimeout(() => {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push('/account')
          }, 1000)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    },
    // 新增账号
    async saveAddAccount(params) {
      try {
        const res = await addAccount(params)
        if (res.code === 0) {
          this.$message.success(res.message)
          setTimeout(() => {
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push('/account')
          }, 1000)
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('出错了', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.account-edit {
  width: 100%;
  height: calc(100% - 178px);
  padding: 0 146px;
  .account-edit-header {
    box-sizing: border-box;
    width: 100%;
    height: 184px;
    margin: 32px 0 24px;
    padding: 32px;
    background: #ffffff;
    box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
    border-radius: 16px;
    .title {
      display: flex;
      justify-content: space-between;
      flex-direction: row;
      position: relative;
      .account-status {
        position: absolute;
        left: 194px;
        top: 6px;
      }
      .title-left {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
      }
      .btn-save {
        width: 80px;
        height: 40px;
        background: linear-gradient(0deg, #777dba, #6983be);
        border-radius: 6px;
        color: #fff;
        border: none;
        cursor: pointer;
      }
      .btn-delete {
        width: 80px;
        height: 40px;
        background: #f56c6c;
        border-radius: 6px;
        color: #fff;
        border: none;
        margin-right: 24px;
      }
    }
    .title-content {
      width: 100%;
      padding-top: 35px;
      box-sizing: border-box;
      .btn-reset-pwd {
        width: 72px;
        height: 32px;
        background: #6e81bc;
        border: none;
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        margin-top: 4px;
        margin-left: -25px;
      }
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 274px);
    box-sizing: border-box;
    ::v-deep .el-empty {
      padding: 0;
    }
    .content-card {
      width: 100%;
      background: #ffffff;
      box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.06);
      border-radius: 16px;
      &.content-card-xxl {
        height: 856px;
      }
      &.content-card-xl {
        height: 720px;
      }
      &.content-card-lg {
        height: 704px;
      }
      &.content-card-md {
        height: 512px;
      }
      &.content-card-sm {
        height: 376px;
      }
      &.content-card-xs {
        height: 320px;
        margin-top: 24px;
        overflow: hidden;
      }
    }
    .img-onlyRead {
      pointer-events: none;
    }
    .last {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }
}
</style>
