<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="employeeName">
          <el-input v-model="queryParams.employeeName" 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">
      <div slot="header" class="card-header">
        <span>员工列表</span>
        <span class="header-tip" v-if="quota.merchantName">商户：{{ quota.merchantName }}</span>
        <span class="quota-tip">员工 {{ quota.usedCount != null ? quota.usedCount : '—' }}/{{ quota.maxCount != null ? quota.maxCount : '—' }}</span>
      </div>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="quotaFull"
            @click="handleAdd"
            v-hasPermi="['agri:seller:employee:add']"
          >创建员工</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="refreshPage"></right-toolbar>
      </el-row>

      <el-alert v-if="quotaFull" title="子管理员人数已达上限，无法新建或启用员工，请联系平台调整店铺设置" type="warning" :closable="false" show-icon class="mb12" />

      <el-table border v-loading="loading" :data="employeeList">
        <el-table-column label="员工账号" align="center" prop="loginAccount" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="员工名称" align="center" prop="employeeName" min-width="110" :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="status" width="90">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:seller:employee:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-user" @click="handleEditProfile(scope.row)" v-hasPermi="['agri:seller:employee:edit']">修改账号</el-button>
            <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)" v-hasPermi="['agri:seller:employee:resetPwd']">修改密码</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:seller:employee: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="cancelForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="员工名称" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工名称" maxlength="30" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="11位手机号，即登录账号" maxlength="11" :disabled="form.userId != null" />
        </el-form-item>
        <el-form-item v-if="form.userId == null" label="登录说明">
          <span class="form-tip">手机号将作为员工登录账号；创建后须「修改密码」方可登录</span>
        </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="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </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="cancelForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改账号弹窗 -->
    <el-dialog title="修改账号" :visible.sync="profileOpen" width="520px" append-to-body @close="cancelProfile">
      <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="100px">
        <el-form-item label="员工名称" prop="employeeName">
          <el-input v-model="profileForm.employeeName" 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>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProfile">确 定</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.employeeName || '—' }}</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 {
  listSellerEmployee,
  sellerEmployeeQuota,
  sellerEmployeeRoleOptions,
  getSellerEmployee,
  addSellerEmployee,
  updateSellerEmployee,
  updateSellerEmployeeProfile,
  resetSellerEmployeePassword,
  delSellerEmployee
} from "@/api/agri/seller/employee"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import passwordRule from "@/utils/passwordRule"

export default {
  name: "AgriSellerEmployee",
  dicts: ['sys_normal_disable'],
  mixins: [passwordRule],
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入新密码"))
        return
      }
      if (value !== this.pwdForm.password) {
        callback(new Error("两次输入的密码不一致"))
        return
      }
      callback()
    }
    const validateRoleIds = (rule, value, callback) => {
      if (!value || !value.length) {
        callback(new Error("请至少选择一个角色"))
        return
      }
      callback()
    }
    return {
      loading: true,
      showSearch: true,
      total: 0,
      employeeList: [],
      title: "",
      open: false,
      profileOpen: false,
      pwdOpen: false,
      quota: {},
      roleOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: undefined
      },
      form: {},
      profileForm: {},
      pwdForm: {},
      rules: {
        employeeName: [
          { 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"] }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        roleIds: [
          { required: true, validator: validateRoleIds, trigger: "change" }
        ]
      },
      profileRules: {
        employeeName: [
          { 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" }
        ]
      }
    }
  },
  computed: {
    /** 配额已满时禁用创建 */
    quotaFull() {
      if (this.quota.usedCount == null || this.quota.maxCount == null) {
        return false
      }
      return this.quota.usedCount >= this.quota.maxCount
    }
  },
  created() {
    this.pwdRules.password = this.pwdValidator
    this.initPage()
  },
  methods: {
    /** 初始化页面 */
    initPage() {
      this.loadShopContext().then(() => {
        this.refreshPage()
      }).catch(() => {
        this.refreshPage()
      })
    },
    /** 加载店铺上下文 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 刷新列表与配额 */
    refreshPage() {
      this.loadQuota()
      this.loadRoleOptions()
      this.getList()
    },
    /** 加载配额 */
    loadQuota() {
      sellerEmployeeQuota().then(response => {
        this.quota = response.data || {}
      }).catch(() => {
        this.quota = {}
      })
    },
    /** 加载当前店铺可选角色 */
    loadRoleOptions() {
      sellerEmployeeRoleOptions().then(response => {
        this.roleOptions = response.data || []
      }).catch(() => {
        this.roleOptions = []
      })
    },
    /** 查询员工列表 */
    getList() {
      this.loading = true
      listSellerEmployee(this.queryParams).then(response => {
        this.employeeList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    resetFormData() {
      this.form = {
        userId: undefined,
        employeeName: undefined,
        mobile: undefined,
        email: undefined,
        avatar: undefined,
        status: "0",
        roleIds: []
      }
      this.resetForm("form")
    },
    /** 打开创建员工 */
    handleAdd() {
      if (this.quotaFull) {
        this.$modal.msgWarning("子管理员人数已达上限")
        return
      }
      this.resetFormData()
      this.open = true
      this.title = "创建员工"
    },
    /** 打开编辑员工 */
    handleUpdate(row) {
      this.resetFormData()
      getSellerEmployee(row.userId).then(response => {
        const data = response.data || {}
        this.form = {
          userId: data.userId,
          employeeName: data.employeeName,
          mobile: data.mobile,
          email: data.email,
          avatar: data.avatar,
          status: data.status != null ? data.status : "0",
          roleIds: data.roleIds ? [].concat(data.roleIds) : []
        }
        this.open = true
        this.title = "编辑员工"
      })
    },
    cancelForm() {
      this.open = false
      this.resetFormData()
    },
    /** 提交创建或编辑 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          employeeName: this.form.employeeName,
          mobile: this.form.mobile,
          email: this.form.email,
          avatar: this.form.avatar,
          status: this.form.status,
          roleIds: this.form.roleIds
        }
        if (this.form.userId != null) {
          payload.userId = this.form.userId
          updateSellerEmployee(payload).then(() => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.refreshPage()
          })
        } else {
          addSellerEmployee(payload).then(response => {
            this.$modal.msgSuccess("创建成功，请为该员工设置登录密码")
            this.open = false
            this.refreshPage()
            const userId = response.userId
            if (userId) {
              this.$modal.confirm("是否立即为该员工设置登录密码？").then(() => {
                this.handleResetPwd({ userId: userId, employeeName: payload.employeeName })
              }).catch(() => {})
            }
          })
        }
      })
    },
    /** 打开修改账号 */
    handleEditProfile(row) {
      getSellerEmployee(row.userId).then(response => {
        const data = response.data || {}
        this.profileForm = {
          userId: data.userId,
          employeeName: data.employeeName,
          mobile: data.mobile,
          email: data.email
        }
        this.profileOpen = true
      })
    },
    cancelProfile() {
      this.profileOpen = false
      this.profileForm = {}
      this.resetForm("profileForm")
    },
    submitProfile() {
      this.$refs["profileForm"].validate(valid => {
        if (!valid) {
          return
        }
        updateSellerEmployeeProfile(this.profileForm).then(() => {
          this.$modal.msgSuccess("修改成功")
          this.profileOpen = false
          this.getList()
        })
      })
    },
    /** 打开修改密码 */
    handleResetPwd(row) {
      this.pwdForm = {
        userId: row.userId,
        employeeName: row.employeeName,
        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
        }
        resetSellerEmployeePassword({
          userId: this.pwdForm.userId,
          password: this.pwdForm.password,
          confirmPassword: this.pwdForm.confirmPassword
        }).then(() => {
          this.$modal.msgSuccess("修改成功，员工下次登录请使用新密码")
          this.pwdOpen = false
        })
      })
    },
    /** 删除员工 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除员工「' + (row.employeeName || row.loginAccount) + '」？删除后将无法登录商家端。').then(() => {
        return delSellerEmployee(row.userId)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.refreshPage()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.card-header {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}
.header-tip {
  color: #909399;
  font-size: 13px;
  font-weight: normal;
}
.quota-tip {
  color: #606266;
  font-size: 13px;
  font-weight: normal;
  margin-left: 4px;
}
.mb12 {
  margin-bottom: 12px;
}
.form-tip {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}
.readonly-text {
  color: #606266;
}
</style>
