<template>
  <div>
    <i-page-header class="product_tabs" title="管理员列表"></i-page-header>
    <Card :bordered="false" dis-hover class="ivu-mt">

      <Form ref="formValidate" :model="formValidate"  :label-width="labelWidth" :label-position="labelPosition" @submit.native.prevent>
        <Row type="flex"  :gutter="24">
          <Col v-bind="grid">
            <FormItem label="状态："  label-for="name">
              <Select v-model="formValidate.roleId"  placeholder="请选择"  @on-change="userSearchs" clearable>
                <Option :value="item.id" :key="item.id"  v-for="item in roleData">{{item.name}}</Option>
              </Select>

            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="搜索："  label-for="status2">
              <Input search enter-button placeholder="请输入管理员账号" v-model="formValidate.keyword" @on-search="userSearchs"/>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex">
          <Col v-bind="grid">
            <Button type="primary" @click="tapAdd" v-if="$utils.checkPermissions(paths,'admin/save')" icon="md-add">添加管理员</Button>
          </Col>
        </Row>
      </Form>

        <Table :columns="columns1" :data="tableData" class="mt25" no-userFrom-text="暂无数据" no-filtered-userFrom-text="暂无筛选结果"  :loading="loading" highlight-row>
          <template slot-scope="{ row, index }" slot="roles">
            <div v-if="row.roleName != ''">
              <Tag color="blue"  v-text="row.roleName"></Tag>
            </div>
          </template>
          <template slot-scope="{ row, index }" slot="status">
            <el-tag v-if="row.status == 1">开启</el-tag>
            <el-tag type="info" v-else>关闭</el-tag>
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <a @click="tapEdit(row.id)" v-if="$utils.checkPermissions(paths,'admin/save')">编辑</a>
            <Divider type="vertical" v-if="$utils.checkPermissions(paths,'admin/del')"/>
            <a @click="tapDel(row.id)" v-if="$utils.checkPermissions(paths,'admin/del')">删除</a>
          </template>

          <template slot-scope="{row,index}" slot="avatar">
            <el-avatar icon="el-icon-user-solid" :src="row.avatar"></el-avatar>
          </template>

        </Table>

      <div class="acea-row row-right page">
        <Page :total="page.count" show-elevator show-total @on-change="tapPage"
              :page-size="page.pageSize"/>
      </div>

    </Card>


    <el-dialog :title="title" :visible.sync="dialogVisible" width="40%" :before-close="editClose">

      <el-form ref="admin" :model="admin" label-width="80px">
        <el-form-item label="账号" prop="username" :rules="[{ required: true, message: '请输入登录账户'}]">
          <el-input placeholder="请输入账号" autocomplete="off" v-model="admin.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请输入管理员姓名'}]">
          <el-input  placeholder="请输入姓名" v-model="admin.name"></el-input>
        </el-form-item>
		<el-form-item label="昵称" prop="nickname" :rules="[{ required: true, message: '请输入昵称'}]">
		  <el-input  placeholder="请输入昵称" v-model="admin.nickname"></el-input>
		</el-form-item>
        <el-form-item label="角色类型">
          <el-select v-model="admin.role_id"  placeholder="角色类型" style=" width: 100%">
            <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in roleData"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码">
          <el-input type="password" placeholder="请输入登录密码"  v-model="admin.password"></el-input>
        </el-form-item>
        <el-form-item label="是否禁用" style="margin-bottom: 0;">
          <el-radio-group v-model="admin.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAdmin">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>


<script>
    import IPageHeader from "../../../../layouts/system/page-header/index";
    import {SystemRole} from "../../../../api/system/role";
    import {SystemAdminDel, SystemAdminInfo, SystemAdminList, SystemAdminUpdate} from "../../../../api/system/admin";
    import { mapState, mapActions } from 'vuex';
    import UiUpload from "../../../../ui/upload/index";
    import Setting from "../../../../setting";
    import util from "../../../../libs/util";
    export default {
        name: "index",
        components: {UiUpload, IPageHeader},
        computed: {
            ...mapState('system/layout', [
                'isMobile'
            ]),
            ...mapState('system/user',['paths']),

            labelWidth () {
                return this.isMobile ? undefined : 50;
            },
            labelPosition () {
                return this.isMobile ? 'top' : 'left';
            }
        },
        data() {
            return {
                title:"添加管理员",
                dialogVisible:false,
                upUrl : "",
                upHeaders : {},
                grid: {
                    xl: 7,
                    lg: 7,
                    md: 12,
                    sm: 24,
                    xs: 24
                },
                columns1: [
                    {
                        title: '姓名',
                        key: 'name',
                        minWidth: 100
                    },
                    {
                        title: '账号',
                        key: 'username',
                        minWidth: 100
                    },
					{
					    title: '昵称',
					    key: 'nickname',
					    minWidth: 100
					},
                    {
                        title: '身份',
                        key: 'roleName',
                        slot : 'roles',
                        minWidth: 100
                    },
                    {
                        title: '开启',
                        slot: 'status',
                        minWidth: 90
                    },
					// {
     //                    title: '推送',
     //                    slot: 'isKf',
     //                    minWidth: 90
     //                },
					// {
					//     title: '员工编码',
					//     key: 'adcode',
					//     minWidth: 100
					// },
					// {
					//     title: 'OPENID',
					//     key: 'openid',
					//     minWidth: 90
					// },
                    {
                        title: '操作',
                        key: 'action',
                        slot: 'action',
						align:'left',
						fixed:'right',
                        minWidth: 150
                    }
                ],
                loading: true,
                //角色列表
                roleData : [],
                tableData: [],
                page : {
                    count : 0,//一共多少数量
                    pageSize : 0,//每一页码数量
                    page : 1,//当前页码
                },
                formValidate:{
                    keyword : "",
                    roleId : 0
                },
                admin : {
                    name : '',
					// isKf:0,
                    username : '',
					nickname : '',
                    status : 1,
                    role_id : '',
                    password:"",
                    avatar : ''
                }
            }
        },

        created() {
            var upHeaders = {};
            //上传路径
            this.upUrl = Setting.apiBaseURL + "/systemv1/upload/index";
            console.log(this.upUrl);
            //上传header数据
            const token = util.cookies.get('system_token');
            if (token) {
                upHeaders['SYSTEM-ACC-TOKEN'] = token;
            }
            this.upHeaders = upHeaders;
           // console.log(this.);
          //  pageCache = new PageCache(this);
        },
        mounted(){
          this.initView();
        },
        watch: {
            '$route'(to, from) {
                pageCache.routeView(to,(type,data)=>{
                    if(type == 'update') {
                        delete data.columns1;
                        Object.assign(this.$data,data);
                        this.initView();
                    }

                    if(type == 'cache') {
                        this.$forceUpdate();
                        delete data.columns1;
                        Object.assign(this.$data,data);
                    }
                });
            }
        },
        methods: {
            initView : function(){
                var roleId = this.$route.query.roleId || 0;
                this.formValidate.roleId = parseInt(roleId);
                this.getData();
                this.getRole();
            },
            /**
             * 获取role
             */
            getRole:function(){
                SystemRole().then(res=>{
                    if(res.code == 200) {
                        this.roleData = [
                            {'name':'请选择角色','id':0}
                        ];
                      //  this.formValidate.roleId = 0;
                        this.roleData = this.roleData.concat(res.data);
                    }
                })
                    .catch(err=>{});
            },
            /**
             * 获取数据
             */
            getData:function () {
                var data = {
                    page : this.page.page,
                    roleId : this.formValidate.roleId,
                    keyword : this.formValidate.keyword
                };
                SystemAdminList(data)
                    .then(res=>{
                        this.loading = false;
                        if(res.code == 200) {
                            this.tableData = res.data.list;
                            this.page.pageSize = res.data.pageSize;
                            this.page.count = res.data.pageCount;
                        } else {
                            this.$alert(res.msg);
                        }
                    })
                    .catch(err=>{
                        this.loading = false;
                        this.$utils.loadingClose();
                        this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                    });
            },
			
            userSearchs () {
                this.page.page = 1;
                this.getData();
            },
            /**
             * 分页
             */
            tapPage:function(index){
                this.page.page = index;
                this.getData();
            },
            /**
             * 添加新管理人员
             */
            tapAdd:function () {
              this.dialogVisible = true;
              this.$refs['admin'].resetFields();
              this.admin = this.$utils.resetFields(this.admin,{status:1});
            },
            //修改内容
            editClose:function () {
                this.dialogVisible = false;
            },
            //上传头像
            handleAvatarSuccess:function (res) {
                if(res.code == -1) {
                    this.$Notice.error({
                        title : "系统提示",
                        content:res.msg
                    });
                } else {
                    this.admin.avatar = res.data.img;
                }
            },
            /**
             * 提交参数
             */
            subAdmin:function () {
                this.$refs['admin'].validate((valid) => {
                    if (valid) {
                        this.$utils.loading(this,"提交数据中...");
                        SystemAdminUpdate(this.admin)
                            .then(res=>{
                                this.$utils.loadingClose();
                                if(res.code == 200) {
                                    this.$message({
                                        message: res.msg,
                                        type: 'success'
                                    });
                                    this.getData();
                                    this.dialogVisible = false;
                                } else {
                                    this.$alert(res.msg);
                                }
                            })
                            .catch(err=>{
                                this.$utils.loadingClose();
                                this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                            });
                    }
                });
            },
			
            /**
             * 删除管理账号
             */
            tapDel:function(id){
                this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$utils.loading(this, "删除数据中...");
                    SystemAdminDel({id: id})
                        .then(res => {
                            this.$utils.loadingClose();
                            this.loading = true;
                            if (res.code == 200) {
                                this.getData();
                            } else {
                                this.$alert(res.msg);
                            }
                        })
                        .catch(err => {
                            this.$utils.loadingClose();
                            this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                        });
                });
            },

            /**
             * 修改管理员
             */
            tapEdit:function(id){
                this.$utils.loading(this,"获取数据中...");
                SystemAdminInfo({id:id})
                    .then(res=>{
                        this.$utils.loadingClose();
                        if(res.code == 200) {
                            this.admin = {...res.data,password:""};
                            this.dialogVisible = true;
                            this.title = "修改管理员";
                        } else {
                            this.$alert(res.msg);
                        }
                    })
                    .catch(err=>{
                        this.$utils.loadingClose();
                        this.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
                    });
            },
        }
    }
</script>
<style scoped>

</style>
