<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.orgName">
      </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>
      <el-button class="filter-item" type="warning" icon="el-icon-delete" v-waves @click="delAll">批量删除
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" @selection-change="handleSelectionChange" border fit
              highlight-current-row>
      <el-table-column type="selection" width="55px"> </el-table-column>
      <!--<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="organizeName">
      </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="createDate">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="是否解散" >
        <template slot-scope="scope">
          <span>{{scope.row.isDelete?"未解散":"已解散"}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="组织说明" prop="organizeMemo">
      </el-table-column>
      <el-table-column align="center" min-width="100px" label="优先级" prop="weight">
      </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="handleOrganizeUser(scope.row)">查看</el-button>
          <el-button type="danger" size="mini"  @click="handleOrgDelete(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">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="名称" prop="organizeName">
          <el-input v-model="dataForm.organizeName"></el-input>
        </el-form-item>
        <el-form-item label="组织说明" prop="organizeMemo">
          <el-input v-model="dataForm.organizeMemo"></el-input>
        </el-form-item>
        <el-tooltip content="优先级越大，位置越靠前！" placement="top-start">
          <el-form-item label="优先级" prop="weight">
            <el-input-number :precision="0" :step="1" v-model="dataForm.weight"></el-input-number>
          </el-form-item>
        </el-tooltip>
        <el-form-item label="封面图片" prop="avatar">
          <el-tooltip content="建议图片宽高比260*200" placement="top-start">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadUrl"
            :show-file-list="false"
            :data="typeDate"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          </el-tooltip>
        </el-form-item>

        <!--<el-form-item v-if="dialogStatus=='update'" label="选择群主">-->
          <!--<el-select v-model="dataForm.adminUserId" placeholder="请选择">-->
            <!--<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="选择群主">
          <el-select
            v-model="dataForm.adminUserId"
            :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>

        <!-- v-if="dialogStatus=='update'" -->
        <el-form-item label="是否解散">

          <el-select v-model="dataForm.isDelete" placeholder="请选择">
            <el-option :key="false" label="解散" :value="false">
            </el-option>
            <el-option :key="true" label="未解散" :value="true">
            </el-option>
          </el-select>

        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>



    <el-dialog title="查看" :visible.sync="dialogUserVisible" width="85%">
      <el-table size="small" :data="userlist" 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 align="center" min-width="100px" label="用户名称" prop="userName">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="是否审核" prop="isNormal">
          <template slot-scope="scope">
            <span v-if="scope.row.isNormal == 0">未审核</span>
            <span v-if="scope.row.isNormal == 1">审核通过</span>
            <span v-if="scope.row.isNormal == 2">审核拒绝</span>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="用户类型" prop="priType">
          <template slot-scope="scope">
            <span v-if="scope.row.priType == 1">群主</span>
            <span v-if="scope.row.priType == 2">管理员</span>
            <span v-if="scope.row.priType == 3">普通成员</span>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="入群时间" prop="createDate">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="申请说明" prop="userMemo">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="是否退群" prop="isDelete">
          <template slot-scope="scope">
            <span>{{scope.row.isDelete?"未退群":"已退群"}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="退群原因" prop="deleteMemo">
        </el-table-column>

        <el-table-column align="center" min-width="100px" label="是否限制发帖" prop="isForbidden">
          <template slot-scope="scope">
            <span>{{scope.row.isForbidden?"限制":"未限制"}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!--<el-button v-if="scope.row.isNormal == '0'" type="primary" size="small" @click="updateNormal(scope.row)">审核</el-button>-->

            <el-dropdown v-if="scope.row.isNormal == '0'" size="small" >
              <el-button type="primary" size="small">
                审核<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="updateNormal(scope.row,'1')" >同意</el-dropdown-item>
                <el-dropdown-item @click.native="updateNormal(scope.row,'2')" >拒绝</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <el-button v-if="scope.row.isForbidden" type="primary" size="small" @click="updateForbidden(scope.row,false)">取消限制发帖</el-button>
            <el-button v-if="scope.row.isForbidden == false" type="primary" size="small" @click="updateForbidden(scope.row,true)">限制发帖</el-button>
            <el-button v-if="scope.row.isNormal == '1' && scope.row.isDelete" type="danger" size="small"  @click="updateDelete(scope.row)">踢人</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background @size-change="handleUserSizeChange" @current-change="handleUserCurrentChange" :current-page="userListQuery.page"
                       :page-sizes="[10,20,30,50]" :page-size="userListQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </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 { selectOrg,createOrg,updateOrg ,selectUserByUserName ,deleteOrgList,deleteOrg} from "@/api/organize"
  import { selectOrganizeUserByOrgId ,updateOrganizeUserById,selectOrganizeUserByOrgIdNoDel,sendWXMsg} from "@/api/organizeuser"
  import { createStorage } from '@/api/storage'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'Admin',
    directives: {
      waves
    },
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          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 {
        list: null,
        userlist: null,
        role: undefined,
        total: null,
        listLoading: true,
        selectLoading: false,
        selectfilterable: true,
        selectremote: true,
        optionsOrgUser: null,
        listQuery: {
          page: 1,
          limit: 20,
          orgName: undefined,
          sort: '+id'
        },
        userListQuery: {
          page: 1,
          limit: 20,
          fkOrganizeId: undefined,
          sort: '+id'
        },
        dataForm: {
          id: undefined,
          organizeName: undefined,
          organizeMemo: undefined,
          isDelete: undefined,
          //coverImage: undefined,
          adminUserId: undefined,
          url: undefined
        },
        typeDate: {
          imgBelongs:"3"
        },
        dialogFormVisible: false,
        dialogUserVisible: false,
        dialogStatus: '',
        imageUrl:'',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          organizeName: [{ required: true, message: '组织名称不能为空', trigger: 'blur' }],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPassword: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur' }
          ]
        },
        downloadLoading: false,
        dialogFlag: false,
        delarr:[],
        multipleSelection:[]
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        this.listQuery.orgType = 2
        selectOrg(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()
      },
      handleUserSizeChange(val) {
        this.userListQuery.limit = val
        this.getUserList()
      },
      handleUserCurrentChange(val) {
        this.userListQuery.page = val
        this.getUserList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          organizeName: undefined,
          organizeMemo: undefined,
          isDelete: undefined
        }
        this.role = []
      },
      getUserList(){
        this.listLoading = true

        selectOrganizeUserByOrgId(this.userListQuery).then(response => {
          this.userlist = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.userlist = []
          this.total = 0
          this.listLoading = false
        })
      },
      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('上传失败，请重新上传')
        })
      },
      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) {
            this.dataForm.organizeType = '2';
            createOrg(this.dataForm).then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row, type) {
        this.dialogFlag = type
        // this.dataForm = Object.assign({}, {"id":row.id,"organizeName":row.organizeName,"organizeMemo":row.organizeMemo,"isDelete":row.isDelete})
        this.imageUrl = row.url
        this.dialogStatus = 'update'
        this.dialogFormVisible = true

        this.dataForm = Object.assign({}, {"id":row.id,"organizeName":row.organizeName,"organizeMemo":row.organizeMemo,"isDelete":row.isDelete,"adminUserId":row.ownerUserName,"url":row.url})


        // selectOrganizeUserByOrgIdNoDel({"fkOrganizeId":row.id}).then(res => {
        //   this.optionsOrgUser = res.data.data.items
        //   this.dataForm = Object.assign({}, {"id":row.id,"organizeName":row.organizeName,"organizeMemo":row.organizeMemo,"isDelete":row.isDelete,"adminUserId":res.data.data.adminUser})
        // })

        if (!type) {
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.getUserRoles()
        }
      },remoteMethod(query){
        this.selectLoading = true;
        selectUserByUserName({"userName":query}).then(res => {
          this.optionsOrgUser = res.data.data
          this.selectLoading = false;
        })
      },
      handleOrganizeUser(row){
        this.dialogUserVisible = true
        this.userListQuery.fkOrganizeId = row.id
        this.getUserList()
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateOrg(this.dataForm).then(() => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      updateNormal(row,isNormal){
        updateOrganizeUserById({"id":row.id,"isNormal":isNormal,"isDelete":true}).then(() => {
          this.dialogFormVisible = false
          this.userListQuery.fkOrganizeId =row.fkOrganizeId
          this.getUserList()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })

          sendWXMsg({"orgUserId":row.id}).then(()=>{

          })


        })
      },
      updateDelete(row){
        updateOrganizeUserById({"id":row.id,"isDelete":false}).then(() => {
          this.dialogFormVisible = false
          this.userListQuery.fkOrganizeId =row.fkOrganizeId
          this.getUserList()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      updateForbidden(row,siF){
        updateOrganizeUserById({"id":row.id,"isForbidden":siF}).then(() => {
          this.dialogFormVisible = false
          this.userListQuery.fkOrganizeId =row.fkOrganizeId
          this.getUserList()
          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', 'organizeName', 'userName','createDate','organizeMemo']
          excel.export_json_to_excel2(tHeader, this.list, filterVal, '行业专委会信息')
          this.downloadLoading = false
        })
      },
      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
          })
      },
      uploadUrl(item) {
        const formData = new FormData()
        formData.append('file', item.file)
        createStorage(formData).then(res => {
          this.dataForm.url = res.data.data.url
          this.imageUrl = res.data.data.url;
          //this.dataForm.coverImage = res.data.data.id;
        }).catch(() => {
          this.$message.error('上传失败，请重新上传')
        })
      },
      beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      handleOrgDelete(row) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteOrg(row).then(response =>{
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
        }).catch(() => {

        })
      },
      delAll(){
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const length = this.multipleSelection.length;

          if (length > 0) {
            for (let i = 0; i < length; i++){
              this.delarr.push(this.multipleSelection[i].id)
            }
            const orgIds = this.delarr.join(",");
            deleteOrgList({orgIds:orgIds}).then(()=>{
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList();
            }).catch(() => {

            })
          } else {

            this.$notify({
              title: 'warning',
              message: '请选择要删除的信息！',
              type: 'warning'
            });
          }

        }).catch(() => {

        })
      },
      handleSelectionChange(val){
        this.multipleSelection = val;
        console.log(val)
      }
    }
  }
</script>
