<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入管理员名称" v-model="listQuery.username">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <!--<el-table-column align="center" width="100px" label="管理员ID" prop="id" sortable>
      </el-table-column>-->
      <el-table-column type="index" label="序号" header-align="center" align="center">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="管理员名称" prop="username">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="管理员昵称" prop="nickname">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="管理员头像" prop="avatar">
      </el-table-column>

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row, false)">编辑</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row, true)">角色</el-button>
          <el-button type="danger" size="mini"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <template v-if="!dialogFlag">
        <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
          <!-- <el-form-item label="管理员名称" prop="username">
            <el-input v-if="dialogStatus=='create'" v-model="dataForm.username" auto-complete="off"></el-input>
            <el-input v-else v-model="dataForm.username" disabled auto-complete="off"></el-input>
          </el-form-item> -->
          <el-form-item label="管理员" prop="username">
                    <el-select :disabled="dialogStatus=='create'?false:true" v-model="dataForm.username" filterable clearable placeholder="请选择" style="width: 280px">
                        <el-option :key="item.loginId" v-for="item in recipientsList" :label="item.deptName+'_'+item.userName+'_'+item.employeNo" :value="item.loginId">
                        </el-option>
                    </el-select>
          </el-form-item>
          <el-form-item label="管理员密码" prop="password">
            <el-input type="password" v-model="dataForm.password"  auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPassword">
            <el-input type="password" v-model="dataForm.checkPassword" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="管理员昵称" prop="nickname">
            <el-input v-model="dataForm.nickname"></el-input>
          </el-form-item>

          <!--<el-form-item label="关联微信" prop="phone">
            <el-tooltip class="item" effect="dark" content="输入手机号码" placement="top-start">
              <el-input ref="phone" v-model="dataForm.phone" @blur="getWxUserId"></el-input>
            </el-tooltip>
          </el-form-item>-->
          <el-form-item label="关联微信用户" prop="userId">
            <el-select
            style="width: 280px"
              v-model="dataForm.userId"
              :filterable="selectfilterable"
              :remote="selectremote"
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="selectLoading">
              <el-option
                v-for="item in optionsOrgUser"
                :key="item.id"
                :label="item.userName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="管理员头像" prop="avatar">
            <el-input v-model="dataForm.avatar"></el-input>
            <el-upload action="#" list-type="picture" :show-file-list="false" :limit="1" :http-request="uploadAvatar">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
      <template v-else>
        <el-form status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
          <el-form-item label="管理员角色">
            <el-select v-model="role" multiple placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <template v-if="!dialogFlag">
          <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </template>
        <template v-if="dialogFlag">
          <el-button  type="primary" @click="updateUserRoles">确定</el-button>
        </template>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    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>


<script>
import { listAdmin, createAdmin, updateAdmin, deleteAdmin, getWxUserId, getUser} from '@/api/admin'
import { selectUserByUserName } from "@/api/organize"
import { roleList, selectAdminRole, addAdminRole } from '@/api/role'
import { createStorage } from '@/api/storage'
import { allUserList } from "@/api/public";
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'Admin',
  directives: {
    waves
  },
  data() {
    var validateUserName = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        if(this.dialogStatus === 'create'){
          getUser({userName:value}).then(response=>{
            if (response.data.data){
              callback(new Error("用户名已存在"))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }

      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        const reg = /([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*/;
        //const reg = /^(?!\d+$)[\da-zA-Z]+$/;
        if (!reg.test(value)) {
          callback(new Error('请输入字母、数字组合'))
        }
        if (this.dataForm.checkPassword !== '') {
          this.$refs.dataForm.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      recipientsList: [],
      list: null,
      role: undefined,
      total: null,
      listLoading: true,
      selectLoading: false,
      selectfilterable: true,
      selectremote: true,
      optionsOrgUser: null,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        nickname: undefined,
        sort: '+id'
      },
      dataForm: {
        id: undefined,
        username: undefined,
        nickname: undefined,
        password: undefined,
        checkPassword: undefined,
        avatar: undefined,
        userId: undefined,
        phone: undefined
      },
      typeDate: {
        imgBelongs:"3"
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        username: [{ required: true, message: '管理员不能为空', trigger: 'blur' }],
        nickname: [{ required: true, message: '管理员昵称不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min:8, max:18, message: '长度在 8 到 18 个字符' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        phone: [{required: true, message: '手机号码不能为空', trigger: 'blur'}],
        userId: [{required: true, message: '关联微信用户不能为空', trigger: 'blur'}]
      },
      downloadLoading: false,
      roleList: [
        {
          value: 1,
          label: 'admin'
        }
      ],
      dialogFlag: false
    }
  },
  created() {
    this.getList();
    this.getRoleList();
    this.getAllUserList(); 
  },
  methods: {
    getAllUserList() {
            allUserList().then(response => {
                this.recipientsList = response.data.data;
            }).catch(() => {});
        },
    getList() {
      this.listLoading = true
      listAdmin(this.listQuery).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        username: undefined,
        password: undefined,
        checkPassword: undefined,
        avatar: undefined
      }
      this.role = []
    },
    uploadAvatar(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      createStorage(formData).then(res => {
        this.dataForm.avatar = res.data.data.url
      }).catch(() => {
        this.$message.error('上传失败，请重新上传')
      })
    },
    remoteMethod(query){
      this.selectLoading = true;
      selectUserByUserName({"userName":query}).then(res => {
        this.optionsOrgUser = res.data.data
        this.selectLoading = false;
      })
    },
    handleCreate() {
      this.resetForm()
      this.dialogFlag = false
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAdmin(this.dataForm).then(response => {
            this.list.unshift(response.data.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row, type) {
      this.dialogFlag = type
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      if (!type) {
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else {
        this.getUserRoles()
      }
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateAdmin(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      deleteAdmin(row).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['管理员ID', '管理员名称','管理员昵称', '管理员头像']
        const filterVal = ['id', 'username', 'nickname', 'avatar']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '管理员信息')
        this.downloadLoading = false
      })
    },
    getRoleList() {
      roleList({ page: 1, limit: 100 })
        .then(response => {
          this.roleList = response.data.data.items
        })
    },
    getUserRoles() {
      selectAdminRole({ userId: this.dataForm.id })
        .then(response => {
          var role = response.data.data
          if (role) {
            role = role.map( function(val) {
              return val - 0
            })
          } else {
            role = []
          }
          this.role = role
        })
    },
    updateUserRoles() {
      addAdminRole({ roleList: this.role.join(','), userId: this.dataForm.id })
        .then(response => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
    },

    getWxUserId() {
      console.log(this.dataForm.phone)
      if(this.dataForm.phone) {
        getWxUserId({'phone' : this.dataForm.phone}).then(response => {
          let userId = response.data.data.userId
          if(userId != 0) {
            this.dataForm.userId = userId
          } else {
            this.$alert('无法查询该手机关联的微信用户Id,请重新输入', '提示', {
              type: 'warning',
              callback: action => {
                this.dataForm.phone = undefined
                this.$refs['phone'].focus()
              }
            })
          }
        }).catch(() => {

        })
      }
    }
  }
}
</script>
