<template>
  <div class="app-container">
    <!-- ===== 搜索栏 ===== -->
    <el-card shadow="never" class="mb16 filter-card">
    <el-form :model="proxyQuery" ref="proxyQueryForm" :inline="true" size="small">
      <el-form-item label="关键词" prop="proxyName">
        <el-input v-model="proxyQuery.proxyName" placeholder="用户名/姓名" clearable @keyup.enter.native="loadProxyList" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="proxyQuery.status" placeholder="全部" clearable style="width:120px">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="loadProxyList">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetProxyQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>

    <!-- ===== 操作栏 ===== -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="openProxyDialog(null)" v-hasPermi="['admin:proxy:add']">新增代理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="loadProxyList" />
    </el-row>

    <!-- ===== 代理列表 ===== -->
    <el-table border v-loading="proxyLoading" :data="proxyList" size="small" style="width:100%">
      <el-table-column label="ID" prop="proxyId" min-width="60" align="center" />
      <el-table-column label="代理名称" prop="proxyName" min-width="110" />
      <el-table-column label="联系人" prop="contactName" min-width="80" align="center" />
      <el-table-column label="联系方式" prop="contactMobile" min-width="110" align="center" />
      <el-table-column label="平台折扣(%)" prop="platformDiscount" min-width="90" align="center">
        <template slot-scope="s">{{ s.row.platformDiscount || s.row.profitShareRatio || 0 }}%</template>
      </el-table-column>
      <el-table-column label="代理余额" align="center" min-width="90">
        <template slot-scope="s">
          <span style="color:#1890ff;font-weight:bold">¥{{ s.row.balance || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="累计佣金" align="center" min-width="90">
        <template slot-scope="s">¥{{ s.row.totalCommission || 0 }}</template>
      </el-table-column>
      <el-table-column label="发展客户" align="center" prop="tenantCount" min-width="80" />
      <el-table-column label="到期时间" align="center" prop="expireTime" min-width="95" />
      <el-table-column label="状态" align="center" min-width="70">
        <template slot-scope="s">
          <el-switch v-model="s.row.status" :active-value="1" :inactive-value="0"
            @change="handleStatusChange(s.row)" v-hasPermi="['admin:proxy:edit']" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="s">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openProxyDialog(s.row)" v-hasPermi="['admin:proxy:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-key" style="color:#722ed1" @click="handleResetPwd(s.row)" v-hasPermi="['admin:proxy:edit']">重置密码</el-button>
          <el-button v-if="s.row.status === 1" size="mini" type="text" style="color:#fa8c16" @click="handleToggleStatus(s.row, 0)" v-hasPermi="['admin:proxy:edit']">禁用</el-button>
          <el-button v-else size="mini" type="text" style="color:#52c41a" @click="handleToggleStatus(s.row, 1)" v-hasPermi="['admin:proxy:edit']">启用</el-button>
          <el-button size="mini" type="text" style="color:#f5222d" icon="el-icon-delete" @click="handleDeleteProxy(s.row)" v-hasPermi="['admin:proxy:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="proxyTotal>0" :total="proxyTotal" :page.sync="proxyQuery.pageNum" :limit.sync="proxyQuery.pageSize" @pagination="loadProxyList" />

    <!-- ===== 代理编辑弹窗 ===== -->
    <el-dialog :title="proxyFormTitle" :visible.sync="proxyDialogVisible" width="560px" append-to-body>
      <el-form ref="proxyForm" :model="proxyForm" :rules="proxyRules" label-width="110px">
        <el-form-item label="代理名称" prop="proxyName">
          <el-input v-model="proxyForm.proxyName" placeholder="请输入代理名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="proxyForm.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactMobile">
          <el-input v-model="proxyForm.contactMobile" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="proxyForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="proxyForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item v-if="!proxyForm.proxyId" label="登录密码" prop="password">
          <el-input v-model="proxyForm.password" placeholder="请输入密码" show-password>
            <el-button slot="append" icon="el-icon-refresh" @click="generatePwd" title="随机生成密码">生成</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="平台折扣(%)" prop="profitShareRatio">
          <el-input-number v-model="proxyForm.profitShareRatio" :min="0" :max="100" :precision="2" style="width:100%" />
        </el-form-item>
        <el-form-item label="开户费" prop="accountFee">
          <el-input-number v-model="proxyForm.accountFee" :min="0" :precision="2" style="width:100%" />
        </el-form-item>
        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker v-model="proxyForm.expireTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择到期时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="proxyForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="proxyForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="proxyDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="proxySubmitting" @click="submitProxyForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProxy, getProxy, addProxy, updateProxy, delProxy, changeProxyStatus, resetProxyPwd
} from '@/api/admin/proxy'
import { generateRandomPwd } from '@/utils/index'

export default {
  name: 'AdminProxy',
  data() {
    return {
      showSearch: true,
      // ======== 代理列表 ========
      proxyLoading: false,
      proxyList: [],
      proxyTotal: 0,
      proxyQuery: { pageNum: 1, pageSize: 10, proxyName: null, status: null },
      // ======== 代理表单 ========
      proxyDialogVisible: false,
      proxyFormTitle: '',
      proxySubmitting: false,
      proxyForm: {
        proxyId: null, proxyName: '',
        contactName: '', contactMobile: '', email: '', companyName: '',
        password: '',
        profitShareRatio: 0, accountFee: 0, expireTime: null, status: 1, remark: ''
      },
      proxyRules: {
        proxyName: [{ required: true, message: '请输入代理名称', trigger: 'blur' }],
        contactMobile: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.loadProxyList()
  },
  methods: {
    loadProxyList() {
      this.proxyLoading = true
      listProxy(this.proxyQuery).then(r => {
        this.proxyList = r.rows
        this.proxyTotal = r.total
        this.proxyLoading = false
      })
    },
    resetProxyQuery() {
      this.resetForm('proxyQueryForm')
      this.loadProxyList()
    },

    openProxyDialog(row) {
      this.reset()
      if (row) {
        this.proxyFormTitle = '编辑代理'
        getProxy(row.proxyId).then(r => {
          this.proxyForm = { ...this.proxyForm, ...r.data }
          this.proxyDialogVisible = true
        })
      } else {
        this.proxyFormTitle = '新增代理'
        this.proxyForm.password = generateRandomPwd(12)
        this.proxyDialogVisible = true
      }
    },
    /** 随机生成密码 */
    generatePwd() {
      this.proxyForm.password = generateRandomPwd(12)
    },
    /** 重置代理密码 */
    handleResetPwd(row) {
      const newPwd = generateRandomPwd(12)
      this.$prompt('为代理 "' + row.proxyName + '" 重置密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: newPwd,
        inputPattern: /^.{6,30}$/,
        inputErrorMessage: '密码长度必须介于 6 和 30 之间',
        inputType: 'text'
      }).then(({ value }) => {
        resetProxyPwd(row.proxyId, value).then(() => {
          this.$message.success('密码重置成功，新密码为：' + value)
        }).catch(() => {
          this.$message.error('密码重置失败')
        })
      }).catch(() => {})
    },
    submitProxyForm() {
      this.$refs['proxyForm'].validate(valid => {
        if (!valid) return
        this.proxySubmitting = true
        const req = this.proxyForm.proxyId ? updateProxy(this.proxyForm) : addProxy(this.proxyForm)
        req.then(() => {
          this.$message.success(this.proxyForm.proxyId ? '修改成功' : '新增成功')
          this.proxyDialogVisible = false
          this.loadProxyList()
        }).finally(() => { this.proxySubmitting = false })
      })
    },
    handleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '禁用'
      this.$confirm(`确认${text}代理 "${row.proxyName}"？`, '提示', { type: 'warning' }).then(() => {
        changeProxyStatus(row.proxyId, row.status).then(() => this.$message.success(`${text}成功`))
      }).catch(() => { row.status = row.status === 1 ? 0 : 1 })
    },
    handleToggleStatus(row, targetStatus) {
      row.status = targetStatus
      this.handleStatusChange(row)
    },
    handleDeleteProxy(row) {
      this.$confirm(`确认删除代理 "${row.proxyName}"？`, '提示', { type: 'warning' }).then(() => {
        delProxy(row.proxyId).then(() => {
          this.$message.success('删除成功')
          this.loadProxyList()
        })
      })
    },
    reset() {
      this.proxyForm = {
        proxyId: null, proxyName: '',
        contactName: '', contactMobile: '', email: '', companyName: '',
        password: '',
        profitShareRatio: 0, accountFee: 0, expireTime: null, status: 1, remark: ''
      }
      if (this.$refs['proxyForm']) this.$refs['proxyForm'].resetFields()
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
.mb16 { margin-bottom: 16px; }
.filter-card { padding-bottom: 0; }
</style>
