<template>
    <div class="add-role-page">
        <Card v-if="loading" class="loading-card">
        <Spin fix size="large" />
      </Card>
      <Card>
          <div class="head">
          <Icon type="md-bookmark" color="#2d8cf0" :size="28" />
          <label>{{ title }}</label>
        </div>
          <div class="item">
          <label class="label">角色名称：</label>
          <Input
            placeholder="请输入角色名称，15以内"
            v-model="form.roleName"
            :maxlength="15"
            :readonly="isEdit"
            style="width: 400px"
          />
        </div>
        <div class="item">
          <label class="label">角色归属：</label>
          <RadioGroup v-model="form.type" @on-change="changeRadio">
          <Radio :label="4" :disabled="isEdit" class="ivu-radio">平台</Radio>
          <Radio :label="5" :disabled="isEdit" class="ivu-radio">商户</Radio>
          <Radio :label="6" :disabled="isEdit" class="ivu-radio">自营</Radio>
        </RadioGroup>
        </div>
        <div class="item">
          <label class="label">备注：</label>
          <Input
            placeholder="请输入备注，30字符以内"
            v-model="form.remarks"
            :maxlength="30"
            clearable
            style="width: 400px"
          />
        </div>
        <div class="item">
          <label class="label">权限：</label>
          <div class="auth-con">
            <Tree :data="allAuth" show-checkbox multiple ref="tree" @on-check-change="changeAuthList"></Tree>
            <div class="check-auth">
              <Tag v-for="(item, index) in form.authJson" :key="index">{{item.title}}</Tag>
            </div>
          </div>

        </div>
        <div class="footer-con">
          <Button
            type="default"
            @click="handleCancel"
            v-if="isAdd"
            style="margin-right: 30px"
          >重置</Button
          >
          <Button
            type="primary"
            @click="handleSubmit"
          >确定</Button
          >
        </div>
      </Card>
    </div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
  computed: {
    isEdit () {
      return this.routeName === 'edit_role'
    },
    isAdd () {
      return this.routeName === 'add_role'
    },
    title () {
      if (this.routeName === 'edit_role') {
        return '编辑角色 - 填写角色信息'
      } else {
        return '添加角色 - 填写角色信息'
      }
    },
    authData () {
      return this.form.authJson
    }
  },
  data () {
    return {
      loading: false,
      form: {
        roleName: '',
        remarks: '',
        type: 4,
        roleId: '',
        authJson: []
      },
      allAuth: [{
        title: 'parent 1',
        expand: true,
        children: [
          {
            title: 'parent 1-1',
            expand: true,
            children: [
              {
                title: 'leaf 1-1-1'
              },
              {
                title: 'leaf 1-1-2'
              }
            ]
          },
          {
            title: 'parent 1-2',
            children: [
              {
                title: 'leaf 1-2-1'
              },
              {
                title: 'leaf 1-2-1'
              }
            ]
          }
        ]
      }],
      routeName: ''
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    handleCancel () {
      this.form = {
        roleName: '',
        remarks: '',
        type: 4,
        roleId: '',
        authJson: []

      }
      this.getTotalAuthRole(4)
    },
    handleSubmit () {
      if (!this.form.roleName) {
        return this.$Message.warning('请输入角色名称！')
      }
      if (!this.form.authJson.length) {
        return this.$Message.warning('请选择角色权限！')
      }
      if (!this.form.remarks) {
        return this.$Message.warning('请输入备注！')
      }
      let apiName = this.isAdd ? 'addRoleManage' : 'editRoleManage'
      let title = this.isAdd ? '添加成功！' : '编辑成功！'
      this.api({
        apiName,
        postdata: this.form,
        success: (res) => {
          this.$Notice.success({ title })
          let route = this.$route
          let toRouteName = 'role_management'
          this.closeTag({ route, toRouteName })
        }
      })
    },
    changeRadio (type) {
      this.getTotalAuthRole(type)
      this.form.authJson = []
    },
    getTotalAuthRole (type) {
      this.allAuth = [{
        title: '全部权限',
        expand: true,
        children: []
      }]
      this.api({
        apiName: 'totalAuthRole',
        postdata: { type },
        success: (res) => {
          let value = this.formatRes(res.data)
          this.allAuth.forEach(item => {
            item.title = value[0].title
            item.children = value[0].children
            item.categoryId = value[0].menuIndex
          })
        }
      })
    },
    changeAuthList () {
      let checkedNodes = this.$refs.tree.getCheckedNodes().filter((item) => {
        return !item.children.length
      })
      this.form.authJson = checkedNodes
    },
    formatRes (res) {
      const arr = []
      let obj = {}
      res.forEach(item => {
        const tmp = { ...item }
        if (item.menuName) {
          if (tmp.subAuthMenu || tmp.subAuthMenu == null) {
            tmp.children = this.formatRes(tmp.subAuthMenu)
            obj = {
              title: tmp.menuName,
              children: tmp.children,
              menuIndex: tmp.menuIndex,
              checked: tmp.select
            }
          }
          arr.push(obj)
        }
      })
      return arr
    },
    getRoleManageDetail (roleId) {
      this.loading = true
      this.api({
        apiName: 'detailRoleManage',
        postdata: { roleId },
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          let { roleId, roleName, type, remarks, auth } = res.data
          this.form.roleId = roleId
          this.form.roleName = roleName
          this.form.type = type
          this.form.remarks = remarks
          let value = this.formatRes(auth)
          this.allAuth.forEach(item => {
            item.title = value[0].title
            item.children = value[0].children
            item.categoryId = value[0].menuIndex
            item.expand = true
          })
          this.$nextTick(() => {
            this.form.authJson = this.$refs.tree.getCheckedNodes().filter((item) => {
              return !item.children.length
            })
          })
        }
      })
    },
    initData () {
      let routeName = this.$route.name
      console.log(routeName)
      let { roleId } = this.$route.query
      this.form.roleId = roleId
      this.routeName = routeName
      if (routeName == 'edit_role') {
        this.getRoleManageDetail(roleId)
      } else {
        this.loading = false
        this.getTotalAuthRole(this.form.type)
      }
    }
  },
  mounted () {
    this.initData()
  }
}
</script>
<style lang="less" scoped>
.add-role-page {
     height: 100%;
}
 .loading-card {
      height: 100%;
    }
    .head {
      color: #17233d;
      font-size: 18px;
      font-weight: bold;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      i {
        margin-right: 10px;
      }
    }
    .item {
      display: flex;
    //   align-items: center;
      margin-bottom: 10px;
      .ivu-radio{
        width: 150px;
      }
    }
    .item .label {
      display: block;
      width: 150px;
      text-align: right;
    }
    .auth-con {
      display: flex;
      .check-auth {
        width: 260px;
        margin-left: 20px;
        border: 1px solid #e5e5e5;
        border-radius: 5px;
      }
    }
    .footer-con {
      margin-left: 150px;
    // text-align: center;
  }
</style>
