<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <div class="filter-control">
        <span>机构名称:</span>
        <el-input v-model="listQuery.name" placeholder="机构名称" @keyup.enter.native="getList" />
      </div>
      <div class="filter-control">
        <span>手机号:</span>
        <el-input v-model="listQuery.mobile" placeholder="手机号" @keyup.enter.native="getList" />
      </div>
      <div class="filter-control">
        <span>状态:</span>
        <el-select v-model="listQuery.status" clearable @change="getList">
          <el-option label="全部" value="" />
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </div>
      <div class="filter-control">
        <permission-button type="primary" @click="getList">查询</permission-button>
        <permission-button type="primary" @click="handleCreate">添加账号</permission-button>
      </div>
    </div>
    <!-- 搜索区域END -->
    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
      fit
      highlight-current-row
      cell-class-name="table-cell"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" type="index" width="80px" align="center" />
      <el-table-column label="机构名称" prop="name" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.name">{{ row.name }}</span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="140" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.mobile">{{ row.mobile }}</span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="160px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.addTime | formatTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="微信昵称" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.nickName">{{ row.nickName }}</span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="openID" width="280" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.openId">{{ row.openId }}</span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="160px" align="center">
        <template slot-scope="{ row }">
          <template v-if="row.status === 0">
            <span style="margin-right: 10px" class="status danger">停用</span>
            <permission-button type="primary" size="mini" @click="handleChangeStatus(row)">启用</permission-button>
          </template>
          <template v-else>
            <span style="margin-right: 10px" class="status success">启用</span>
            <permission-button type="info" size="mini" @click="handleChangeStatus(row)">停用</permission-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template slot-scope="{ row }">
          <permission-button
            type="primary"
            size="mini"
            style="margin-right: 5px"
            @click="handleResetPwd(row)"
          >重置密码</permission-button>
          <permission-button type="primary" size="mini" @click="handleEdit(row)">编辑</permission-button>
          <permission-button type="primary" size="mini" @click="onChangeClub(row)">更换机构</permission-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格区域END -->
    <pagination
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchUserList"
    />

    <el-dialog title="添加用户" width="30%" :visible.sync="dialogVisible" @close="onDialogClose">
      <el-form ref="form" label-width="80px" :model="formData" :rules="rules">
        <el-form-item label="手机号：" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号" maxlength="11" show-word-limit />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 绑定/更换机构 -->
    <el-dialog title="绑定/更换机构" :visible.sync="dialogChangeClubVisible" width="30%" :show-close="false">
      <el-form ref="changeClubForm" :model="changeClubForm" :rules="changeClubRules" label-width="70px">
        <el-form-item prop="authId" label="机构：">
          <el-select v-model="changeClubForm.authId" placeholder="请选择机构" style="width: 100%" clearable>
            <template v-for="item in bindClubList">
              <el-option :key="item.authId" :label="item.authParty" :value="item.authId" />
            </template>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogChangeClubVisible = false">取 消</el-button>
        <el-button type="primary" @click="onBindClubConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  authUserStatusChange,
  clubUserBindSave,
  createClubUser,
  fetchClubBindList,
  getAuthUserList,
  resetClubUserPassword
} from '@/api/auth'
import { isMobile } from '@/utils/validate'

const resetFormData = () => ({
  clubUserId: '',
  authUserId: '',
  mobile: ''
})

export default {
  name: 'SupplierUserList',
  data() {
    const validateMobile = (rule, value, callback) => {
      console.log(value)
      if (isMobile(value)) {
        callback()
      } else {
        callback(new Error('手机号格式不正确'))
      }
    }

    return {
      total: 0,
      authId: '', // 机构id
      editType: 'add',
      dialogChangeClubVisible: false,
      listLoading: false,
      listQuery: {
        authUserId: '', // 机构id
        name: '', // 用户名
        status: '',
        mobile: '', // 手机号
        pageNum: 0, // 页码
        pageSize: 10 // 分页大小
      },
      list: [],
      srcList: [],
      dialogVisible: false,
      formData: resetFormData(),
      rules: {
        // name: [{ required: true, message: '请输入用户姓名', trigger: ['blur'] }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: ['blur'] },
          { validator: validateMobile, message: '手机号格式不正确', trigger: ['blur'] }
        ]
      },
      changeClubForm: {
        clubUserId: '',
        authId: '',
        authParty: ''
      },
      changeClubRules: {
        authId: [{ required: true, message: '请选择机构', trigger: ['change'] }]
      },
      bindClubList: []
    }
  },
  computed: {
    ...mapGetters(['authUserId'])
  },
  created() {
    this.getList()
  },
  methods: {
    // 更换机构
    async onChangeClub(row) {
      try {
        this.changeClubForm.clubUserId = row.clubUserId
        const res = await fetchClubBindList()
        console.log(res)
        this.bindClubList = res.data
        this.dialogChangeClubVisible = true
      } catch (error) {
        console.log(error)
      }
    },

    // 绑定机构确定
    async onBindClubConfirm() {
      try {
        const bindClub = this.bindClubList.find((item) => item.authId === this.changeClubForm.authId)
        if (bindClub) {
          this.changeClubForm.authParty = bindClub.authParty
        }
        await this.$refs.changeClubForm.validate()
        this.onBindClub()
      } catch (error) {
        console.log(error)
      }
    },

    // 绑定机构
    async onBindClub() {
      try {
        await clubUserBindSave(this.changeClubForm)
        this.dialogChangeClubVisible = false
        this.getList()
        this.$message.success('机构绑定成功!')
      } catch (error) {
        console.log(error)
      } finally {
        this.$refs.changeClubForm.resetFields()
      }
    },

    // 更新列表
    getList() {
      this.listQuery.pageNum = 1
      this.fetchUserList()
    },

    // 获取列表数据
    async fetchUserList() {
      this.listLoading = true
      this.listQuery.authUserId = this.authUserId
      try {
        const res = await getAuthUserList(this.listQuery)
        this.list = res.data.list
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.listLoading = false
      }
    },

    // 创建用户
    handleCreate() {
      this.dialogVisible = true
      this.editType = 'add'
    },
    // 修改用户
    handleEdit(row) {
      this.formData.clubUserId = row.clubUserId
      this.formData.authUserId = row.authUserId
      this.formData.mobile = row.mobile
      this.dialogVisible = true
      this.editType = 'edit'
    },

    async handleChangeStatus(row) {
      try {
        const status = row.status === 0 ? 1 : 0
        await authUserStatusChange({
          clubUserId: row.clubUserId,
          status
        })
        this.getList()
        this.$message.success('用户状态修改成功')
      } catch (error) {
        console.log(error)
        this.$message.error('用户状态修改失败')
      }
    },

    // 保存用户信息
    async onSave() {
      let valide = false
      try {
        valide = await this.$refs.form.validate()
      } catch (error) {
        console.log(error)
      }
      if (!valide) return

      this.formData.authUserId = this.authUserId
      try {
        await createClubUser(this.formData)
        this.$message.success(`${this.editType === 'add' ? '添加' : '修改'}用户成功`)
        this.fetchUserList()
        this.dialogVisible = false
      } catch (error) {
        console.log(error)
      }
    },
    // 删除用户
    // async handleRemove(row) {
    //   let confirmType = ''
    //   try {
    //     confirmType = await this.$confirm('确认删除改用户？', '提示', {
    //       confirmButtonText: '确认',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     })
    //   } catch (error) {
    //     console.log(error)
    //   }

    //   if (!confirmType) return

    //   try {
    //     await removeClubUser({ clubUserId: row.clubUserId })
    //     this.$message.success('删除用户成功')
    //     this.fetchUserList()
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },

    // 重置密码
    async handleResetPwd(row) {
      try {
        await resetClubUserPassword({ clubUserId: row.clubUserId })
        this.$message.success('重置密码成功')
      } catch (error) {
        console.log(error)
      }
    },

    onDialogClose() {
      this.$refs.form.resetFields()
      this.formData = resetFormData()
    },

    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  ::v-deep {
    .el-dialog__body {
      padding-bottom: 0;
    }
  }
}

.el-table .cell {
  overflow: visible;
}
.el-badge {
  margin: 0 6px;
}
</style>
