<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="80px">
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="queryParams.accountName" 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="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()" v-hasPermi="['agri:accountManage:remove']">批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" :selectable="rowSelectable" />
        <el-table-column label="账号名称" align="center" prop="accountName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" align="center" prop="mobile" 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="shopCount" width="90">
          <template slot-scope="scope">
            <span>{{ formatShopCount(scope.row.shopCount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditProfile(scope.row)" v-hasPermi="['agri:accountManage:edit']">修改账号</el-button>
            <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)" v-hasPermi="['agri:accountManage:resetPwd']">修改密码</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:accountManage: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="修改账号" :visible.sync="profileOpen" width="560px" append-to-body @close="cancelProfile">
      <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="100px">
        <el-alert
          v-if="profileForm.merchantId != null"
          title="该账号为商户管理员，修改手机号将同步至该商户下全部店铺"
          type="warning"
          :closable="false"
          show-icon
          class="mb12"
        />
        <el-form-item label="账号名称" prop="accountName">
          <el-input v-model="profileForm.accountName" placeholder="请输入账号名称" maxlength="30" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="profileForm.mobile" placeholder="请输入11位手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" placeholder="选填" maxlength="50" />
        </el-form-item>
        <el-form-item v-if="profileForm.shopCount != null" label="店铺数">
          <span class="readonly-text">{{ profileForm.shopCount }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProfile(false)">确 定</el-button>
        <el-button @click="cancelProfile">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="pwdOpen" width="520px" append-to-body @close="cancelPwd">
      <el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="100px">
        <el-form-item label="账号名称">
          <span class="readonly-text">{{ pwdForm.accountName || '—' }}</span>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pwdForm.password" placeholder="请输入新密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" placeholder="请再次输入新密码" type="password" maxlength="20" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwd">确 定</el-button>
        <el-button @click="cancelPwd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAccountManage,
  getAccountManage,
  updateAccountProfile,
  resetAccountPassword,
  delAccountManage
} from "@/api/agri/accountManage"
import passwordRule from "@/utils/passwordRule"

export default {
  name: "AgriAccountManage",
  mixins: [passwordRule],
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入新密码"))
        return
      }
      if (value !== this.pwdForm.password) {
        callback(new Error("两次输入的密码不一致"))
        return
      }
      callback()
    }
    return {
      // 列表加载遮罩
      loading: true,
      // 是否显示检索区
      showSearch: true,
      // 列表总条数
      total: 0,
      // 账号列表数据
      accountList: [],
      // 选中行的 userId 数组
      ids: [],
      // 是否未选中（批量按钮禁用）
      multiple: true,
      // 是否显示修改账号弹窗
      profileOpen: false,
      // 是否显示修改密码弹窗
      pwdOpen: false,
      // 编辑前手机号（用于判断是否需要 confirm）
      originalMobile: "",
      // 列表检索参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountName: undefined
      },
      // 修改账号表单
      profileForm: {},
      // 修改密码表单
      pwdForm: {},
      // 修改账号校验规则
      profileRules: {
        accountName: [
          { required: true, message: "账号名称不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号", trigger: "blur" }
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ]
      },
      // 修改密码校验规则
      pwdRules: {
        password: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度必须介于 6 和 20 之间", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: "blur" }
        ]
      }
    }
  },
  created() {
    // 密码强度规则合并到 pwdRules.password
    this.pwdRules.password = this.pwdValidator
    this.getList()
  },
  methods: {
    /** 查询账号列表 */
    getList() {
      this.loading = true
      listAccountManage(this.queryParams).then(response => {
        this.accountList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 店铺数展示：非商户管理员为空 */
    formatShopCount(shopCount) {
      if (shopCount === null || shopCount === undefined || shopCount === "") {
        return "—"
      }
      return shopCount
    },
    /** 搜索 */
    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
    },
    /** 打开修改账号弹窗 */
    handleEditProfile(row) {
      getAccountManage(row.userId).then(response => {
        const data = response.data || {}
        this.originalMobile = data.mobile || ""
        this.profileForm = {
          userId: data.userId,
          merchantId: data.merchantId,
          accountName: data.accountName,
          mobile: data.mobile,
          email: data.email,
          shopCount: data.shopCount
        }
        this.profileOpen = true
      })
    },
    /** 关闭修改账号弹窗 */
    cancelProfile() {
      this.profileOpen = false
      this.profileForm = {}
      this.originalMobile = ""
      this.resetForm("profileForm")
    },
    /** 提交修改账号（商户管理员改手机号需 confirm） */
    submitProfile(confirmed) {
      this.$refs["profileForm"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          userId: this.profileForm.userId,
          accountName: this.profileForm.accountName,
          mobile: this.profileForm.mobile,
          email: this.profileForm.email
        }
        if (this.profileForm.mobile !== this.originalMobile) {
          payload.confirm = confirmed === true
        }
        updateAccountProfile(payload).then(response => {
          if (response.data && response.data.needConfirm) {
            this.$modal.confirm(response.data.confirmMessage || "将同步至该商户下全部店铺，是否继续？").then(() => {
              this.submitProfile(true)
            }).catch(() => {})
            return
          }
          this.$modal.msgSuccess("修改成功")
          this.profileOpen = false
          this.getList()
        })
      })
    },
    /** 打开修改密码弹窗 */
    handleResetPwd(row) {
      getAccountManage(row.userId).then(response => {
        const data = response.data || {}
        this.pwdForm = {
          userId: data.userId,
          accountName: data.accountName,
          password: undefined,
          confirmPassword: undefined
        }
        this.pwdOpen = true
        this.$nextTick(() => {
          this.resetForm("pwdForm")
        })
      })
    },
    /** 关闭修改密码弹窗 */
    cancelPwd() {
      this.pwdOpen = false
      this.pwdForm = {}
      this.resetForm("pwdForm")
    },
    /** 提交修改密码 */
    submitPwd() {
      this.$refs["pwdForm"].validate(valid => {
        if (!valid) {
          return
        }
        resetAccountPassword({
          userId: this.pwdForm.userId,
          password: this.pwdForm.password,
          confirmPassword: this.pwdForm.confirmPassword
        }).then(() => {
          this.$modal.msgSuccess("修改成功，下次登录请使用新密码")
          this.pwdOpen = false
        })
      })
    },
    /** 删除账号（单独或批量） */
    handleDelete(row) {
      const userIds = row ? [row.userId] : this.ids
      if (!userIds.length) {
        return
      }
      const tip = row
        ? '是否确认删除账号「' + (row.accountName || row.userId) + '」？'
        : '是否确认删除选中的 ' + userIds.length + ' 个账号？删除后不可恢复。'
      this.$modal.confirm(tip).then(() => {
        return delAccountManage(userIds.join(","))
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.mb12 {
  margin-bottom: 12px;
}
.readonly-text {
  color: #606266;
}
</style>
