<template>
  <div>
    <div class="button-box clearflex">
      <el-button @click="addUser" type="primary">新增用户</el-button>
    </div>
    <el-table :data="tableData" border stripe>
		<el-table-column label="头像" min-width="50">
			<template slot-scope="scope">
			  <div :style="{'textAlign':'center'}">
				<CustomPic :picSrc="scope.row.headerImg" />
			  </div>
			</template>
		</el-table-column>
		
		<el-table-column label="用户的id" min-width="100" prop="userId"></el-table-column>
		<el-table-column label="用户名" min-width="150" prop="username"></el-table-column>
		<el-table-column label="昵称" min-width="150" prop="nickname"></el-table-column>
	  
		<el-table-column label="绑定微信" min-width="150" prop="openid">
		  <template slot-scope="{row}">
			<span> {{row.openid?"是":"否"}}</span>
		  </template>
		</el-table-column>
		
		<el-table-column label="用户角色" min-width="150" prop="authorityId">
			<template slot-scope="{row}">
				<span> {{authOptions[row.authorityId]}}</span>
			</template>
		</el-table-column>

      <el-table-column label="操作" min-width="200">
		 
        <template slot-scope="scope">
		  <el-button @click="opdendrawer(scope.row)" size="small" type="primary">设置权限</el-button>
          
		  <el-popover placement="top" width="160" v-model="scope.row.visible" class="ml20">
            <p>确定要删除此用户吗</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="deleteUser(scope.row)">确定</el-button>
            </div>
            <el-button type="danger" icon="el-icon-delete" size="small" slot="reference">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog :visible.sync="addUserDialog" custom-class="user-dialog" title="新增用户">
      <el-form :rules="rules" ref="userForm" :model="userInfo">
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="80px" prop="password">
          <el-input v-model="userInfo.password"></el-input>
        </el-form-item>
        <el-form-item label="别名" label-width="80px" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="头像" label-width="80px">
          <div style="display:inline-block" @click="openHeaderChange">
            <img class="header-img-box" v-if="userInfo.headerImg" :src="userInfo.headerImg" />
            <div v-else class="header-img-box">从媒体库选择</div>
          </div>
        </el-form-item>
        <el-form-item label="用户角色" label-width="80px" prop="authorityId">
			<el-select v-model="userInfo.authorityId" placeholder="请选择">
			    <el-option value="111" label="普通用户"></el-option>
				<el-option value="444" label="经办人"></el-option>
				<el-option value="555" label="负责人"></el-option>
				<el-option value="666" label="分管领导"></el-option>
				<el-option value="777" label="专项负责人"></el-option>
			</el-select>

        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeAddUserDialog">取 消</el-button>
        <el-button @click="enterAddUserDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>
	
	<el-drawer :visible.sync="drawer" :with-header="false" size="440" title="角色配置" v-if="drawer">
		<div class="clearflex p10">
		  <el-button @click="saveRole" class="fl-right" size="small" type="primary">保存</el-button>
		</div>
		<el-table :data="departments" border stripe height="700px">
			<el-table-column label="部门" width="120" prop="department"></el-table-column>
			<el-table-column label="权限" width="320" prop="department">
				<template slot-scope="{row}">
					<el-radio-group v-model="row.isLeader">
					    <el-radio :label="0">无</el-radio>
					    <el-radio :label="1">新增</el-radio>
						<el-radio :label="2">审核</el-radio>
						<el-radio :label="3">发布</el-radio>
					  </el-radio-group>
				</template>
			</el-table-column>
		</el-table>
	</el-drawer>
  </div>
</template>


<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成
const path = process.env.VUE_APP_BASE_API;
import {
  getUserList,
  setUserAuthority,
  register,
  deleteUser
} from "@/api/user";
import { getAuthorityList } from "@/api/authority";
import { getUserDepartmentList, setUserDepartmentList } from "@/api/user";
import infoList from "@/mixins/infoList";
import { mapGetters } from "vuex";
import CustomPic from "@/components/customPic";
import ChooseImg from "@/components/chooseImg";
export default {
  name: "Api",
  mixins: [infoList],
  components: { CustomPic,ChooseImg },
  data() {
    return {
      listApi: getUserList,
      path: path,
      authOptions: {"111":'普通用户', "444":"经办", "555":"负责人","666":"分管领导","777":"专项负责人","888":"超级管理"},
      addUserDialog: false,
	  drawer: false,
      userInfo: {
        username: "",
        password: "",
        nickname: "",
        headerImg: "",
        authorityId: ""
      },
	  userId: 0,
	  departments:[],
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 6, message: "最低6位字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, message: "最低6位字符", trigger: "blur" }
        ],
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" }
        ],
        authorityId: [
          { required: true, message: "请选择用户角色", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters("user", ["token"])
  },
  methods: {
    openHeaderChange(){
      this.$refs.chooseImg.open()
    },
    setOptions(authData) {
      this.authOptions = [];
      this.setAuthorityOptions(authData, this.authOptions);
    },
	opdendrawer(row) {
	  this.departments = []
	  this.userId = +row.userId
	  getUserDepartmentList( {userId:row.userId}).then( res=>{
		 if( res.code == 200){
			console.log("departments", res.data)
			this.departments = res.data;
			this.drawer = true;
		 }
	  })
	},
    async deleteUser(row) {
      const res = await deleteUser({ id: row.ID });
      if (res.code == 200){
        this.getTableData();
        row.visible = false;
      }
    },
	saveRole(){
		let param ={userId:this.userId, roleList:[] }
		for( let i in this.departments){
			let item = this.departments[i];
			param.roleList.push( {isLeader: item.isLeader, departmentId: item.departmentId} )
		}
		setUserDepartmentList( param).then( res=>{
			if( res.code == 200){
				this.$message.successMsg("保存成功", 1)
			}
		})
	},
    async enterAddUserDialog() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          let param = Object.assign({}, this.userInfo)
          param.password = this.$md5( param.password );
          const res = await register(param);
          if (res.code == 200){
			  this.$message.successMsg("创建成功", 1)
          }
          await this.getTableData();
          this.closeAddUserDialog();
        }
      });
    },
    closeAddUserDialog() {
      this.$refs.userForm.resetFields();
      this.addUserDialog = false;
    },
    handleAvatarSuccess(res) {
      this.userInfo.headerImg = res.data.file.url;
    },
    addUser() {
      this.addUserDialog = true;
    }
  },
  async created() {
    this.getTableData();
  }
};
</script>
<style lang="scss">

.button-box {
  padding: 10px 20px;
  .el-button {
    float: right;
  }
}

.user-dialog {
  .header-img-box {
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  border-radius: 20px;
  text-align: center;
  line-height: 200px;
  cursor: pointer;
}
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>