<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="keyword">
          <el-input v-model="queryParams.keyword" placeholder="会员名称/昵称/手机号" clearable style="width: 220px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 120px">
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </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:member:add']">添加会员</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="memberList">
        <el-table-column label="会员名称" align="center" min-width="160">
          <template slot-scope="scope">
            <div>{{ scope.row.memberCode || '—' }}</div>
            <div class="sub-mobile">{{ scope.row.mobile || '—' }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="会员等级" align="center" prop="memberLevelLabel" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.memberLevelLabel || '—' }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="是否启用" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
              v-hasPermi="['agri:member:edit']"
            />
          </template>
        </el-table-column>
        <el-table-column label="累计消费次数" align="center" prop="orderCount" width="120" />
        <el-table-column label="累计消费金额" align="center" prop="totalAmount" width="120" />
        <el-table-column label="注册日期" align="center" prop="registerTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.registerTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:member:query']">查看详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-s-order" @click="handleOrders(scope.row)" v-hasPermi="['agri:member:query']">查看订单</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="open" width="560px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入11位手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="会员名称" prop="memberCode">
          <el-input v-model="form.memberCode" placeholder="选填，不填则系统自动生成" maxlength="64" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="选填，不填则同会员名称" maxlength="64" />
        </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="memberLevel">
          <el-select v-model="form.memberLevel" placeholder="选填" clearable style="width: 100%">
            <el-option
              v-for="dict in dict.type.biz_member_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" maxlength="500" placeholder="选填" show-word-limit />
        </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>

    <!-- 详情抽屉 -->
    <member-detail :visible.sync="detailOpen" :member-id="currentMemberId" @view-orders="handleOrdersFromDetail" />

    <!-- 订单抽屉 -->
    <member-orders :visible.sync="ordersOpen" :member-id="currentMemberId" :member-name="currentMemberName" />
  </div>
</template>

<script>
import { listMember, addMember, updateMemberStatus } from "@/api/agri/member"
import MemberDetail from "./detail"
import MemberOrders from "./orders"
import passwordRule from "@/utils/passwordRule"

export default {
  name: "AgriMember",
  dicts: ['biz_member_level'],
  mixins: [passwordRule],
  components: { MemberDetail, MemberOrders },
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      memberList: [],
      open: false,
      detailOpen: false,
      ordersOpen: false,
      currentMemberId: null,
      currentMemberName: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        status: undefined
      },
      // 添加会员表单
      form: {},
      rules: {
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号", trigger: "blur" }
        ],
        password: [],
        status: [
          { required: true, message: "请选择是否启用", trigger: "change" }
        ]
      }
    }
  },
  created() {
    // 密码校验规则来自 passwordRule 混入
    this.rules.password = this.pwdValidator
    this.getList()
  },
  methods: {
    /** 查询会员列表 */
    getList() {
      this.loading = true
      listMember(this.queryParams).then(response => {
        this.memberList = 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()
    },
    /** 重置添加表单 */
    reset() {
      this.form = {
        mobile: undefined,
        password: undefined,
        memberCode: undefined,
        nickName: undefined,
        avatar: undefined,
        memberLevel: undefined,
        status: "0",
        remark: undefined
      }
      this.resetForm("form")
    },
    /** 打开添加会员弹窗 */
    handleAdd() {
      this.reset()
      this.open = true
    },
    /** 关闭弹窗 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 提交添加会员 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        addMember(this.form).then(() => {
          this.$modal.msgSuccess("添加成功")
          this.open = false
          this.getList()
        })
      })
    },
    /** 查看详情 */
    handleDetail(row) {
      this.currentMemberId = row.memberId
      this.detailOpen = true
    },
    /** 查看订单 */
    handleOrders(row) {
      this.currentMemberId = row.memberId
      this.currentMemberName = row.memberCode || row.nickName || ""
      this.ordersOpen = true
    },
    /** 从详情页跳转查看订单 */
    handleOrdersFromDetail(detail) {
      this.detailOpen = false
      this.handleOrders(detail)
    },
    /** 切换启用状态（禁用须二次确认） */
    handleStatusChange(row) {
      const newStatus = row.status
      const isDisable = newStatus === "1"
      const doUpdate = () => {
        updateMemberStatus(row.memberId, { status: newStatus }).then(() => {
          this.$modal.msgSuccess("操作成功")
        }).catch(() => {
          row.status = isDisable ? "0" : "1"
        })
      }
      if (isDisable) {
        this.$modal.confirm("禁用后该会员将无法登录 C 端并无法下单，是否继续？").then(doUpdate).catch(() => {
          row.status = "0"
        })
      } else {
        doUpdate()
      }
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.sub-mobile {
  color: #909399;
  font-size: 12px;
  margin-top: 2px;
}
</style>
