<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="账号" prop="username">
        <el-input v-model="queryParams.username" placeholder="账号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option label="正常" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['subteam:user:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['subteam:user:edit']" type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['subteam:user:remove']" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column label="主键ID" prop="id" width="80" />
      <el-table-column label="账号" prop="username" />
      <el-table-column label="昵称" prop="nickname" />
      <el-table-column label="团队" prop="deptName" />
      <el-table-column label="手机" prop="phone" width="120" />
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="String(scope.row.status)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="openDeptScoreDialog(scope.row, 'issue')"
            v-hasPermi="['ai:user:deptScoreIssue']"
          >下放积分</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="openDeptScoreDialog(scope.row, 'reclaim')"
            v-hasPermi="['ai:user:deptScoreReclaim']"
          >回收积分</el-button>
          <el-button v-hasPermi="['subteam:user:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['subteam:user:resetPwd']" size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)">密码</el-button>
          <el-button v-hasPermi="['subteam:user:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</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-dialog :title="title" :visible.sync="open" width="640px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <el-form-item label="昵称" prop="nickname"><el-input v-model="form.nickname" /></el-form-item>
        <el-row v-if="!form.id">
          <el-col :span="12"><el-form-item label="账号" prop="username"><el-input v-model="form.username" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="密码" prop="password"><el-input v-model="form.password" type="password" show-password /></el-form-item></el-col>
        </el-row>
        <el-form-item label="手机" prop="phone"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="邮箱" prop="email"><el-input v-model="form.email" /></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="备注"><el-input v-model="form.remark" type="textarea" /></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>
    <el-dialog
      :title="deptScoreMode === 'issue' ? '下放积分' : '回收积分'"
      :visible.sync="deptScoreOpen"
      width="480px"
      append-to-body
      @close="cancelDeptScore"
    >
      <el-form ref="deptScoreFormRef" :model="deptScoreForm" :rules="deptScoreRules" label-width="88px">
        <el-form-item label="所属团队">
          <span>{{ deptScoreForm.deptName || '—' }}</span>
        </el-form-item>
        <el-form-item label="用户账号">
          <span>{{ deptScoreForm.username }}</span>
        </el-form-item>
        <el-form-item label="积分数量" prop="amount">
          <el-input-number
            v-model="deptScoreForm.amount"
            :min="1"
            :max="100000000"
            :precision="0"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="deptScoreForm.remark"
            type="textarea"
            :rows="2"
            maxlength="50"
            show-word-limit
            placeholder="选填，最多50字"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeptScore">确 定</el-button>
        <el-button @click="cancelDeptScore">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSubteamUser, getSubteamUser, addSubteamUser, updateSubteamUser, delSubteamUser,
  resetSubteamUserPwd
} from '@/api/subteam'
import { issueDeptScore, reclaimDeptScore } from '@/api/ai/user'

export default {
  name: 'SubteamUser',
  dicts: ['sys_normal_disable'],
  data() {
    return {
      loading: true,
      showSearch: true,
      dateRange: [],
      userList: [],
      total: 0,
      ids: [],
      single: true,
      multiple: true,
      title: '',
      open: false,
      deptScoreOpen: false,
      deptScoreMode: 'issue',
      deptScoreForm: {
        userId: null,
        username: '',
        deptName: '',
        amount: undefined,
        remark: ''
      },
      deptScoreRules: {
        amount: [
          { required: true, message: '请输入积分数量', trigger: 'blur' },
          {
            type: 'number',
            min: 1,
            max: 100000000,
            message: '请输入 1～100000000 的整数',
            trigger: 'blur'
          }
        ],
        remark: [{ max: 50, message: '备注最多50个字', trigger: 'blur' }]
      },
      queryParams: { pageNum: 1, pageSize: 10, username: undefined, phone: undefined, status: undefined },
      form: {},
      rules: {
        nickname: [{ required: true, message: '必填', trigger: 'blur' }],
        username: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [{ required: true, message: '必填', trigger: 'blur' }],
        email: [{ type: 'email', message: '邮箱格式', trigger: ['blur', 'change'] }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listSubteamUser(this.addDateRange(this.queryParams, this.dateRange, 'CreateTime')).then(res => {
        this.userList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(r => r.id)
      this.single = rows.length !== 1
      this.multiple = !rows.length
    },
    reset() {
      this.form = { id: undefined, username: undefined, nickname: undefined, password: undefined,
        phone: undefined, email: undefined, status: 0, remark: undefined }
      this.resetForm('form')
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增AI用户'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getSubteamUser(id).then(r => {
        this.form = r.data || {}
        this.form.status = Number(this.form.status || 0)
        this.open = true
        this.title = '修改AI用户'
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.form.id) {
          updateSubteamUser(this.form).then(() => { this.$modal.msgSuccess('成功'); this.open = false; this.getList() })
        } else {
          addSubteamUser(this.form).then(() => { this.$modal.msgSuccess('成功'); this.open = false; this.getList() })
        }
      })
    },
    cancel() { this.open = false },
    handleDelete(row) {
      const userIds = row.id || this.ids
      this.$modal.confirm('确认删除？').then(() => delSubteamUser(userIds)).then(() => { this.getList(); this.$modal.msgSuccess('已删除') }).catch(() => {})
    },
    handleResetPwd(row) {
      this.$prompt('新密码', '重置', { inputType: 'password' }).then(({ value }) => {
        resetSubteamUserPwd({ id: row.id, password: value }).then(() => this.$modal.msgSuccess('已重置'))
      }).catch(() => {})
    },
    openDeptScoreDialog(row, mode) {
      if (!row.deptId) {
        this.$modal.msgWarning('请先分配归属部门后再操作积分')
        return
      }
      this.deptScoreMode = mode
      this.deptScoreForm = {
        userId: row.id,
        username: row.username || row.userId || '',
        deptName: row.deptName || '',
        amount: undefined,
        remark: ''
      }
      this.deptScoreOpen = true
      this.$nextTick(() => {
        if (this.$refs.deptScoreFormRef) {
          this.$refs.deptScoreFormRef.clearValidate()
        }
      })
    },
    submitDeptScore() {
      this.$refs.deptScoreFormRef.validate(valid => {
        if (!valid) {
          return
        }
        const raw = this.deptScoreForm.amount
        const amount = typeof raw === 'number' ? Math.trunc(raw) : parseInt(String(raw), 10)
        if (!Number.isFinite(amount) || amount < 1 || amount > 100000000) {
          this.$modal.msgWarning('请输入 1～100000000 的整数积分')
          return
        }
        const payload = {
          userId: this.deptScoreForm.userId,
          amount,
          remark: this.deptScoreForm.remark || undefined
        }
        const req = this.deptScoreMode === 'issue' ? issueDeptScore : reclaimDeptScore
        req(payload).then(() => {
          this.$modal.msgSuccess('操作成功')
          this.deptScoreOpen = false
          this.getList()
        })
      })
    },
    cancelDeptScore() {
      this.deptScoreOpen = false
      this.deptScoreForm = { userId: null, username: '', deptName: '', amount: undefined, remark: '' }
    }
  }
}
</script>
