<!--  -->
<template>
  <div>
    <main-top :crumb="crumbData"></main-top>
    <div class="table-interface">
      <div class="top-body">
        <div class="top-title">角色信息:</div>
        <div class="form-con">
          <el-form :disabled="$route.params.type === 2" ref="roleform" :rules="rules" :model="form" label-width="100px">
            <el-form-item label="角色名称：" style="width:318px;" prop="roleName">
              <el-input v-model="form.roleName" maxlength="15" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="角色说明：">
              <el-input type="textarea" maxlength="500" show-word-limit v-model="form.description"></el-input>
            </el-form-item>
            <el-form-item label="是否启用：">
              <el-radio-group v-model="form.state">
                <el-radio :label="0">是</el-radio>
                <el-radio :label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item></el-form-item>
          </el-form>
        </div>
        <div class="form-con" >
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="菜单权限" name="first">
              <div class="menu" v-for="(item,index) in menu" :key="index">
                  <div><el-checkbox :disabled="$route.params.type === 2" @change="handleItem(item)" v-model="item.authority">{{item.name}}</el-checkbox></div>
                  <ul>
                    <li v-for="(sub,idx) in item.children" :key="idx">
                      <el-checkbox :disabled="$route.params.type === 2" @change="handleItem(sub)" class="s-el" v-model="sub.authority">{{sub.name}}</el-checkbox>
                      <div class="verline"></div>
                      <ul>
                        <li v-for="(son,i) in sub.children" :key="i">
                          <el-checkbox :disabled="$route.params.type === 2" @change="handleItem(son)" v-model="son.authority">{{son.name}}</el-checkbox></li>
                      </ul>
                    </li>
                  </ul>
              </div>
            </el-tab-pane>
            <el-tab-pane label="用户列表" name="second">
              <el-table :data="tableData" style="width: 100%">
                <el-table-column
                  v-for="(item, idx) in data"
                  :key="idx"
                  :prop="item.prop"
                  :label="item.label"
                >
                  <template slot-scope="scope">
                    <img
                      style="width:80px;border-radius:50%;"
                      v-if="item.prop === 'head'"
                      :src="scope.row[item.prop]"
                      alt
                    />
                    <span v-else>{{scope.row[item.prop]}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-button :disabled="$route.params.type === 2" type="primary" @click="save">发布</el-button>
        <el-button @click="$router.back()">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

import MainTop from '@/components/main-top'
import SearchBar from '@/components/search-bar'
import { VueEditor } from 'vue2-editor'

function getIds (data) {
  let arr = []
  let fn = res => {
    res && res.forEach(item => {
      item.authority && arr.push(item.id)
      item.children && fn(item.children)
    })
  }
  fn(data)
  return arr
}

let zt = {
  0: '启用',
  1: '停用'
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {
    MainTop,
    VueEditor,
    SearchBar
  },
  data () {
    let type = this.$route.params.type
    const crumbData = [
      {
        name: '角色信息',
        id: 0
      },
      {
        name: type === 3 ? '查看角色' : (type === 1 ? '编辑角色' : '新增角色'),
        id: 1
      }
    ]
    let data = [
      {
        prop: 'id',
        label: '序号'
      },
      {
        prop: 'head',
        label: '用户头像'
      },
      {
        prop: 'userName',
        label: '账号'
      },
      {
        prop: 'phone',
        label: '手机号'
      },
      {
        prop: 'qiyong',
        label: '状态'
      }
    ]
    return {
      isIndeterminate: true,
      crumbData,
      type: this.$route.params.type,
      id: this.$route.params.id,
      activeName: 'first',
      content: '<h1>Some initial content</h1>',
      data,
      tableData: [],
      form: {
        createTime: '',
        description: '',
        id: '',
        roleKey: '',
        roleName: '',
        state: 0
      },
      menu: [],
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleClick (e) {
      if (this.activeName === 'second') {
        this.getTableData()
      }
    },
    async getTableData () {
      let result = await this.$http({
        method: 'post',
        headers: {
          token: window.localStorage.getItem('token')
        },
        url: `/role/findUserListByRoleId`,
        data: {
          id: this.id
        }
      })

      this.tableData = result.data
      this.tableData.forEach((item, i) => {
        item['qiyong'] = zt[item['state']]
        item['idx'] = i + 1
      })
    },
    handleItem (item) {
      let {authority, parentId} = item
      let fn = data => {
        data.children && data.children.forEach(sub => {
          sub.authority = authority
          fn(sub)
        })
      }
      fn(item)

      let fnx = (parent = '', sub, parentId) => {
        if (sub.id === parentId) {
          if (sub.children) {
            let isCheck = false
            sub.children.forEach(it => {
              if (it.authority) {
                isCheck = it.authority
                return false
              }
            })
            sub.authority = isCheck
          }
          parent && fnx('', parent, sub.parentId)
        } else {
          sub.children && sub.children.forEach(it => {
            fnx(sub, it, parentId)
          })
        }
      }
      this.menu && this.menu.forEach(sub => {
        fnx('', sub, parentId)
      })
    },
    save () {
      this.$refs['roleform'].validate(async (valid) => {
        if (valid) {
          let {
            id = '',
            createTime,
            description,
            state,
            roleKey,
            roleName
          } = this.form
          let resources = getIds(this.menu)
          let params = {
            id,
            createTime,
            description,
            roleKey,
            state,
            roleName,
            resources
          }

          let result = await this.$http({
            method: 'post',
            data: params,
            url: `/role/save`
          })

          if (result.code === 0) {
            this.$alert('保存成功', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$router.back()
              }
            })
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg
            })
          }
        }
      })
    },
    async getMeun () {
      let result = await this.$http({
        method: 'post',
        url: `/resource/find`,
        data: {
          id: this.id
        }
      })

      this.menu = result.data
    },
    async getDetail () {
      let result = await this.$http({
        method: 'post',
        headers: {
          token: window.localStorage.getItem('token')
        },
        url: `/role/findRoleById`,
        data: {
          id: this.id
        }
      })

      this.form = result.data
      this.menu = result.data.resources
    }
  },

  mounted () {
    if (this.id && this.id !== 'none') {
      this.getDetail()
    } else {
      this.getMeun()
    }
  }
}
</script>

<style lang='less' scoped>
/* 引入公共css类 */
@import './style.less';

</style>

<style>
.ql-picker-label {
  line-height: 1;
  overflow: hidden;
}

.avatar-uploader .el-upload {
  /* border: 1px dashed #000; */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
