<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
      <el-form-item label="租户" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="全部租户" filterable clearable size="small">
          <el-option v-for="c in companyOptions" :key="c.value" :label="c.label" :value="c.value" />
        </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" prop="id" width="60" />
      <el-table-column label="租户" prop="companyName" width="120" />
      <el-table-column label="配置名" prop="configName" min-width="140" />
      <el-table-column label="画像来源" prop="profileSource" width="120" />
      <el-table-column label="刷新策略" prop="refreshStrategy" width="100" />
      <el-table-column label="最大字段" prop="maxFields" width="80" />
      <el-table-column label="状态" width="80">
        <template slot-scope="{row}"><el-switch v-model="row.enabled" :active-value="1" :inactive-value="0" @change="handleStatusChange(row)" /></template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="{row}">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#F56C6C" @click="handleDelete(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="dialogTitle" :visible.sync="dialogVisible" width="580px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租户" prop="companyId" v-if="isAdd">
          <el-select v-model="form.companyId" placeholder="选择租户" filterable style="width:100%">
            <el-option v-for="c in companyOptions" :key="c.value" :label="c.label" :value="c.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="配置名" prop="configName">
          <el-input v-model="form.configName" placeholder="配置名称" />
        </el-form-item>
        <el-form-item label="画像来源">
          <el-select v-model="form.profileSource" style="width:100%">
            <el-option label="CRM订单" value="crm_order" />
            <el-option label="CRM标签" value="crm_tag" />
            <el-option label="企微档案" value="wechat_profile" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="刷新策略">
          <el-select v-model="form.refreshStrategy" style="width:100%">
            <el-option label="实时" value="realtime" />
            <el-option label="每小时" value="hourly" />
            <el-option label="每天" value="daily" />
            <el-option label="手动" value="manual" />
          </el-select>
        </el-form-item>
        <el-form-item label="最大字段数">
          <el-input-number v-model="form.maxFields" :min="1" :max="50" />
        </el-form-item>
        <el-form-item label="字段映射">
          <el-input v-model="form.fieldMappings" type="textarea" :rows="4" placeholder='JSON格式, 如 [{"source":"crm_tag","field":"age","target":"用户年龄"}]' />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllCompanies } from '@/api/workflow/lobster-admin'
import request from '@/utils/request'

export default {
  name: 'ProfileConfig',
  data() {
    return {
      loading: false, list: [], total: 0,
      companyOptions: [],
      queryParams: { pageNum: 1, pageSize: 10, companyId: null },
      dialogVisible: false, dialogTitle: '', isAdd: false,
      form: { companyId: null, configName: '', profileSource: 'crm_tag', refreshStrategy: 'daily', maxFields: 10, fieldMappings: '', remark: '' },
      rules: { configName: [{ required: true, message: '不能为空', trigger: 'blur' }] }
    }
  },
  created() { this.loadCompanies(); this.getList() },
  methods: {
    async loadCompanies() { try { const res = await listAllCompanies(); this.companyOptions = (res.data || []).map(c => ({ value: c.companyId, label: c.companyName || '未知' })) } catch (e) {} },
    async getList() {
      this.loading = true
      try {
        const res = await request({ url: '/workflow/lobster/profile-config/list', method: 'get', params: this.queryParams })
        this.list = (res.data || [])
        this.total = this.list.length
      } catch (e) { this.list = []
      } finally { this.loading = false }
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.$refs.queryForm.resetFields(); this.handleQuery() },
    handleAdd() { this.isAdd = true; this.dialogTitle = '新增画像配置'; this.form = { companyId: this.queryParams.companyId, configName: '', profileSource: 'crm_tag', refreshStrategy: 'daily', maxFields: 10, fieldMappings: '', remark: '', enabled: 1 }; this.dialogVisible = true },
    handleEdit(row) { this.isAdd = false; this.dialogTitle = '修改画像配置'; this.form = { ...row }; this.dialogVisible = true },
    async handleStatusChange(row) {
      try {
        await request({ url: '/workflow/lobster/profile-config/save', method: 'post', data: row })
        this.$message.success('状态已更新')
      } catch (e) { this.$message.error('更新失败') }
    },
    async submitForm() {
      this.$refs.formRef.validate(async v => {
        if (!v) return
        try {
          await request({ url: '/workflow/lobster/profile-config/save', method: 'post', data: this.form })
          this.$message.success(this.isAdd ? '新增成功' : '修改成功')
          this.dialogVisible = false; this.getList()
        } catch (e) { this.$message.error('保存失败') }
      })
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除?', '警告', { type: 'warning' })
        await request({ url: `/workflow/lobster/profile-config/${row.id}`, method: 'delete', params: { companyId: row.companyId } })
        this.$message.success('删除成功'); this.getList()
      } catch (e) { if (e !== 'cancel') this.$message.error('删除失败') }
    }
  }
}
</script>
