<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <el-form :model="queryParams" :inline="true" label-width="100px">
        <el-form-item label="租户ID">
          <el-select
            v-model="queryParams.tenantId"
            filterable
            clearable
            placeholder="请选择租户"
            style="width: 220px"
            :loading="tenantLoading"
          >
            <el-option
              v-for="item in tenantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租户名称">
          <el-input v-model="queryParams.tenantName" clearable placeholder="租户名称" style="width: 160px" />
        </el-form-item>
        <el-form-item label="登录账号">
          <el-input v-model="queryParams.loginAccount" clearable placeholder="登录账号" style="width: 160px" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="queryParams.nickname" clearable placeholder="昵称" style="width: 140px" />
        </el-form-item>
        <el-form-item label="推荐人手机">
          <el-input v-model="queryParams.referrerPhone" clearable placeholder="推荐人手机号" style="width: 160px" />
        </el-form-item>
        <el-form-item label="推荐人姓名">
          <el-input v-model="queryParams.referrerName" clearable placeholder="推荐人姓名" style="width: 140px" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            style="width: 360px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-delete" @click="resetQuery">清空</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="action-container" shadow="never">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button
        type="danger"
        icon="el-icon-shopping-cart-full"
        :loading="rushBuyLoading"
        :disabled="!multipleSelection.length"
        style="margin-left: 12px"
        @click="handleRushBuy"
      >
        开始抢单
      </el-button>
    </el-card>

    <el-card class="table-container" shadow="never">
      <el-table
        ref="dataTable"
        v-loading="loading"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="租户ID" prop="tenantId" min-width="180" show-overflow-tooltip />
        <el-table-column label="租户名称" prop="tenantName" min-width="120" show-overflow-tooltip />
        <el-table-column label="登录账号" prop="loginAccount" min-width="120" show-overflow-tooltip />
        <el-table-column label="昵称" prop="nickname" min-width="100" show-overflow-tooltip />
        <el-table-column label="抢购单数" prop="maxGrabCount" width="90" align="center" />
        <el-table-column label="最大金额" prop="maxGrabAmount" width="90" align="center" />
        <el-table-column label="前端Token" prop="tokenFront" min-width="160" show-overflow-tooltip />
        <el-table-column label="推荐人手机" prop="referrerPhone" min-width="120" show-overflow-tooltip />
        <el-table-column label="推荐人姓名" prop="referrerName" min-width="100" show-overflow-tooltip />
        <el-table-column label="登录网址" prop="loginUrl" min-width="160" show-overflow-tooltip />
        <el-table-column label="最新充值点数" prop="latestRechargePoints" width="110" align="center" />
        <el-table-column label="剩余点数" prop="remainingPoints" width="90" align="center" />
        <el-table-column label="累计点数" prop="totalPoints" width="90" align="center" />
        <el-table-column label="创建时间" prop="createTime" min-width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" prop="updateTime" min-width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="140">
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" style="color:#F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="queryParams.current"
        :page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="760px" top="5vh" @close="resetForm">
      <el-form ref="dataForm" :model="form" :rules="formRules" label-width="120px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="租户" prop="tenantId">
              <el-select
                v-model="form.tenantId"
                filterable
                clearable
                placeholder="请选择租户"
                style="width: 100%"
                :loading="tenantLoading"
                @change="handleTenantChange"
              >
                <el-option
                  v-for="item in tenantOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租户名称" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="租户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="loginAccount">
              <el-input v-model="form.loginAccount" placeholder="登录账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="loginPassword">
              <el-input
                v-model="form.loginPassword"
                type="password"
                show-password
                :placeholder="isEdit ? '留空则不修改' : '登录密码'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录网址" prop="loginUrl">
              <el-input v-model="form.loginUrl" placeholder="登录网址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="前端token" prop="tokenFront">
          <el-input
            v-model="form.tokenFront"
            type="textarea"
            :rows="2"
            placeholder="前端 token"
          />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="推荐人手机" prop="referrerPhone">
              <el-input v-model="form.referrerPhone" placeholder="推荐人手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐人姓名" prop="referrerName">
              <el-input v-model="form.referrerName" placeholder="推荐人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="抢单最大金额" prop="maxGrabAmount">
              <el-input-number
                v-model="form.maxGrabAmount"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抢购单数" prop="maxGrabCount">
              <el-input-number
                v-model="form.maxGrabCount"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="最新充值点数" prop="latestRechargePoints">
              <el-input-number
                v-model="form.latestRechargePoints"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="剩余点数" prop="remainingPoints">
              <el-input-number
                v-model="form.remainingPoints"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="累计点数" prop="totalPoints">
              <el-input-number
                v-model="form.totalPoints"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addLbBuyAccount,
  deleteLbBuyAccount,
  getLbBuyAccountList,
  rushBuyLbBuyAccount,
  updateLbBuyAccount
} from '@/api/lb-buy-account'
import { getAllTenantList } from '@/api/tenant'
import { getBusinessHeaders } from '@/utils/business-headers'

const DEFAULT_FORM = () => ({
  id: '',
  tenantId: '',
  tenantName: '',
  loginAccount: '',
  loginPassword: '',
  nickname: '',
  referrerPhone: '',
  referrerName: '',
  loginUrl: '',
  tokenFront: '',
  maxGrabAmount: undefined,
  maxGrabCount: undefined,
  latestRechargePoints: undefined,
  remainingPoints: undefined,
  totalPoints: undefined
})

export default {
  name: 'LbRushOrderAccount',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!this.isEdit && !value) {
        callback(new Error('请输入登录密码'))
        return
      }
      callback()
    }
    return {
      loading: false,
      submitLoading: false,
      rushBuyLoading: false,
      tenantLoading: false,
      list: [],
      multipleSelection: [],
      total: 0,
      tenantOptions: [],
      createTimeRange: [],
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      queryParams: {
        current: 1,
        size: 10,
        tenantId: '',
        tenantName: '',
        loginAccount: '',
        nickname: '',
        referrerPhone: '',
        referrerName: ''
      },
      form: DEFAULT_FORM(),
      formRules: {
        tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        loginAccount: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        loginPassword: [{ validator: validatePassword, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getTenantOptions()
    this.initDefaultTenantFilter()
    this.fetchList()
  },
  methods: {
    getTenantIdFromBusinessHeaders() {
      const headers = getBusinessHeaders()
      const value = headers && headers['X-Tenant-Id']
      return value ? String(value).trim() : ''
    },
    initDefaultTenantFilter() {
      const tenantId = this.getTenantIdFromBusinessHeaders()
      if (tenantId) this.queryParams.tenantId = tenantId
    },
    getTenantOptions() {
      this.tenantLoading = true
      getAllTenantList()
        .then((response) => {
          if (response && (response.code === 20000 || response.code === 200)) {
            const tenantList = Array.isArray(response.data) ? response.data : (response.data?.data || [])
            this.tenantOptions = tenantList.map((item) => ({
              value: item.id,
              label: item.tenantName ? `${item.tenantName} (${item.tenantCode || '-'})` : (item.tenantCode || item.id),
              tenantName: item.tenantName || ''
            }))
          } else {
            this.tenantOptions = []
          }
        })
        .catch(() => {
          this.tenantOptions = []
        })
        .finally(() => {
          this.tenantLoading = false
        })
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    handleRushBuy() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先勾选要抢单的账号')
        return
      }
      const ids = this.multipleSelection.map((row) => row.id).filter(Boolean)
      if (!ids.length) {
        this.$message.warning('所选账号缺少有效 ID')
        return
      }
      const accountLabels = this.multipleSelection
        .map((row) => row.loginAccount || row.nickname || row.id)
        .join('、')
      this.$confirm(
        `确定对以下 ${ids.length} 个账号发起抢单吗？\n${accountLabels}`,
        '开始抢单',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.rushBuyLoading = true
        return rushBuyLbBuyAccount({ ids })
      }).then((res) => {
        const isSuccess = res && (res.success === true || res.code === 200 || res.code === 20000)
        if (!isSuccess) {
          this.$message.error((res && res.message) || '抢单失败')
          return
        }
        this.$message.success((res && res.message) || '抢单完成')
        this.fetchList()
      }).catch(() => {}).finally(() => {
        this.rushBuyLoading = false
      })
    },
    handleTenantChange(tenantId) {
      const option = this.tenantOptions.find((item) => item.value === tenantId)
      if (option && option.tenantName) {
        this.form.tenantName = option.tenantName
      }
    },
    fetchList() {
      this.loading = true
      getLbBuyAccountList(this.buildListParams())
        .then((res) => {
          if (res && (res.code === 20000 || res.code === 200 || res.success === true)) {
            this.list = Array.isArray(res.data) ? res.data : []
            this.total = typeof res.total === 'number'
              ? res.total
              : (res.page && typeof res.page.total === 'number' ? res.page.total : this.list.length)
          } else {
            this.list = []
            this.total = 0
          }
        })
        .catch(() => {
          this.list = []
          this.total = 0
        })
        .finally(() => {
          this.loading = false
          this.$nextTick(() => {
            this.$refs.dataTable && this.$refs.dataTable.clearSelection()
          })
        })
    },
    buildListParams() {
      const params = {
        current: this.queryParams.current,
        size: this.queryParams.size,
        tenantId: this.queryParams.tenantId || undefined,
        tenantName: this.queryParams.tenantName || undefined,
        loginAccount: this.queryParams.loginAccount || undefined,
        nickname: this.queryParams.nickname || undefined,
        referrerPhone: this.queryParams.referrerPhone || undefined,
        referrerName: this.queryParams.referrerName || undefined
      }
      const range = this.createTimeRange || []
      if (range[0]) params.createTimeStart = range[0]
      if (range[1]) params.createTimeEnd = range[1]
      Object.keys(params).forEach((key) => {
        if (params[key] === undefined || params[key] === '') delete params[key]
      })
      return params
    },
    handleQuery() {
      this.queryParams.current = 1
      this.fetchList()
    },
    resetQuery() {
      this.queryParams = {
        current: 1,
        size: 10,
        tenantId: '',
        tenantName: '',
        loginAccount: '',
        nickname: '',
        referrerPhone: '',
        referrerName: ''
      }
      this.createTimeRange = []
      this.initDefaultTenantFilter()
      this.fetchList()
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchList()
    },
    handleCurrentChange(current) {
      this.queryParams.current = current
      this.fetchList()
    },
    handleAdd() {
      this.dialogTitle = '新增抢单账号'
      this.isEdit = false
      this.resetFormData()
      const tenantId = this.getTenantIdFromBusinessHeaders()
      if (tenantId) {
        this.form.tenantId = tenantId
        this.handleTenantChange(tenantId)
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm && this.$refs.dataForm.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑抢单账号'
      this.isEdit = true
      this.form = {
        ...DEFAULT_FORM(),
        ...this.pickFormFields(row),
        id: row.id,
        loginPassword: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.dataForm && this.$refs.dataForm.clearValidate()
      })
    },
    pickFormFields(row) {
      const fields = DEFAULT_FORM()
      Object.keys(fields).forEach((key) => {
        if (key === 'id' || key === 'loginPassword') return
        if (row[key] !== undefined && row[key] !== null) {
          fields[key] = row[key]
        }
      })
      return fields
    },
    handleDelete(row) {
      this.$confirm('确定删除该抢单账号吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => deleteLbBuyAccount(row.id))
        .then((res) => {
          this.$message.success((res && res.message) || '删除成功')
          this.fetchList()
        })
        .catch(() => {})
    },
    handleSubmit() {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) return
        const payload = this.buildPayload()
        this.submitLoading = true
        const req = this.isEdit ? updateLbBuyAccount(payload) : addLbBuyAccount(payload)
        req.then((res) => {
          this.$message.success((res && res.message) || (this.isEdit ? '更新成功' : '新增成功'))
          this.dialogVisible = false
          this.fetchList()
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    buildPayload() {
      const payload = { ...this.form }
      if (this.isEdit) {
        if (!payload.loginPassword) delete payload.loginPassword
      }
      Object.keys(payload).forEach((key) => {
        if (payload[key] === undefined || payload[key] === '') delete payload[key]
      })
      return payload
    },
    resetForm() {
      this.$refs.dataForm && this.$refs.dataForm.resetFields()
      this.resetFormData()
    },
    resetFormData() {
      this.form = DEFAULT_FORM()
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      const date = new Date(String(dateTime).replace('T', ' '))
      if (Number.isNaN(date.getTime())) return String(dateTime)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container,
  .action-container {
    margin-bottom: 20px;
  }

  .table-container {
    .el-pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
