<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="管理员名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="昵称/登录名" clearable style="width: 220px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:platformAdmin:add']">添加管理员</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()" v-hasPermi="['agri:platformAdmin:remove']">批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="adminList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" :selectable="rowSelectable" />
        <el-table-column label="管理员名称" align="center" prop="adminName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" align="center" prop="phonenumber" width="120" />
        <el-table-column label="邮箱" align="center" prop="email" min-width="140" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.email || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleNames" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.roleNames || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:platformAdmin:edit']">编辑</el-button>
            <el-button
              v-if="scope.row.userId !== 1"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['agri:platformAdmin:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="管理员名称" prop="adminName">
          <el-input v-model="form.adminName" placeholder="请输入管理员名称（昵称）" maxlength="30" />
        </el-form-item>
        <el-form-item label="登录名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入登录名" maxlength="30" :disabled="form.userId != null" />
        </el-form-item>
        <el-form-item v-if="form.userId == null" label="初始密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入11位手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="选填" maxlength="50" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" multiple placeholder="请至少选择一个角色" style="width: 100%">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPlatformAdmin,
  getPlatformAdmin,
  addPlatformAdmin,
  updatePlatformAdmin,
  delPlatformAdmin,
  platformAdminRoleOptions
} from "@/api/agri/platformAdmin"
import passwordRule from "@/utils/passwordRule"

export default {
  name: "AgriPlatformAdmin",
  mixins: [passwordRule],
  data() {
    return {
      // 列表加载遮罩
      loading: true,
      // 是否显示检索区
      showSearch: true,
      // 列表总条数
      total: 0,
      // 管理员列表数据
      adminList: [],
      // 弹窗标题
      title: "",
      // 是否显示弹窗
      open: false,
      // 选中行的 userId 数组
      ids: [],
      // 是否未选中（批量按钮禁用）
      multiple: true,
      // 可选角色列表
      roleOptions: [],
      // 列表检索参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      // 添加/编辑表单
      form: {},
      // 表单校验规则
      rules: {
        adminName: [
          { required: true, message: "管理员名称不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "登录名不能为空", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号", trigger: "blur" }
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        roleIds: [
          { required: true, type: "array", min: 1, message: "请至少选择一个角色", trigger: "change" }
        ]
      }
    }
  },
  created() {
    // 密码校验规则来自 passwordRule 混入
    this.rules.password = this.pwdValidator
    this.getList()
    this.loadRoleOptions()
  },
  methods: {
    /** 查询管理员列表 */
    getList() {
      this.loading = true
      listPlatformAdmin(this.queryParams).then(response => {
        this.adminList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 加载表单可选角色（admin、merchant） */
    loadRoleOptions() {
      platformAdminRoleOptions().then(response => {
        this.roleOptions = response.data || []
      })
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置检索 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 表格多选变更 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.multiple = !selection.length
    },
    /** 内置超管不可勾选批量删除 */
    rowSelectable(row) {
      return row.userId !== 1
    },
    /** 重置表单 */
    reset() {
      this.form = {
        userId: undefined,
        adminName: undefined,
        userName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        avatar: undefined,
        roleIds: []
      }
      this.resetForm("form")
    },
    /** 打开添加弹窗 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加管理员"
    },
    /** 打开编辑弹窗并回显 */
    handleUpdate(row) {
      this.reset()
      getPlatformAdmin(row.userId).then(response => {
        const data = response.data || {}
        this.form = {
          userId: data.userId,
          adminName: data.adminName,
          userName: data.userName,
          phonenumber: data.phonenumber,
          email: data.email,
          avatar: data.avatar,
          roleIds: data.roleIds || []
        }
        this.open = true
        this.title = "编辑管理员"
      })
    },
    /** 关闭弹窗 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 提交添加或编辑 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        if (this.form.userId != null) {
          updatePlatformAdmin(this.buildUpdatePayload()).then(() => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addPlatformAdmin(this.buildCreatePayload()).then(() => {
            this.$modal.msgSuccess("添加成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 组装新增请求体 */
    buildCreatePayload() {
      return {
        adminName: this.form.adminName,
        userName: this.form.userName,
        phonenumber: this.form.phonenumber,
        email: this.form.email,
        avatar: this.form.avatar,
        password: this.form.password,
        roleIds: this.form.roleIds
      }
    },
    /** 组装编辑请求体（不含登录名、密码） */
    buildUpdatePayload() {
      return {
        userId: this.form.userId,
        adminName: this.form.adminName,
        phonenumber: this.form.phonenumber,
        email: this.form.email,
        avatar: this.form.avatar,
        roleIds: this.form.roleIds
      }
    },
    /** 删除管理员（单独或批量） */
    handleDelete(row) {
      const userIds = row ? [row.userId] : this.ids
      if (!userIds.length) {
        return
      }
      const tip = row
        ? '是否确认删除管理员「' + (row.adminName || row.userName) + '」？'
        : '是否确认删除选中的 ' + userIds.length + ' 名管理员？删除后不可恢复。'
      this.$modal.confirm(tip).then(() => {
        return delPlatformAdmin(userIds.join(","))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
</style>
