<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 规则Tab -->
      <el-tab-pane label="自动标签规则" name="rules">
        <el-form :model="rulesQueryParams" ref="rulesQueryForm" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="规则状态" prop="isApply">
            <el-select v-model="rulesQueryParams.isApply" placeholder="请选择规则状态" clearable size="small">
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="规则类型" prop="type">
            <el-select v-model="rulesQueryParams.type" placeholder="请选择规则类型" clearable size="small">
              <el-option label="关键词打标签" :value="1" />
              <el-option label="客户入群行为打标签" :value="2" />
              <el-option label="分时段打标签" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRulesQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetRulesQuery">重置</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="handleRulesAdd"
              v-hasPermi="['qw:autoTagsRules:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="rulesSingle"
              @click="handleRulesUpdate" v-hasPermi="['qw:autoTagsRules:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="rulesMultiple"
              @click="handleRulesDelete" v-hasPermi="['qw:autoTagsRules:remove']">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getRulesList"></right-toolbar>
        </el-row>

        <el-table v-loading="rulesLoading" :data="autoTagsRulesList" @selection-change="handleRulesSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" width="60" />
          <el-table-column label="主表ID" align="center" prop="autoTagsId" width="80" />
          <el-table-column label="群集合" align="center" prop="rules" :show-overflow-tooltip="true" />
          <el-table-column label="标签集合" align="center" prop="tags" :show-overflow-tooltip="true" />
          <el-table-column label="规则状态" align="center" prop="isApply" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isApply === 1 ? 'success' : 'danger'">{{ scope.row.isApply === 1 ? '启用' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="规则类型" align="center" prop="type" width="140">
            <template slot-scope="scope">
              <span v-if="scope.row.type === 1">关键词打标签</span>
              <span v-else-if="scope.row.type === 2">入群行为打标签</span>
              <span v-else-if="scope.row.type === 3">分时段打标签</span>
              <span v-else>{{ scope.row.type }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRulesUpdate(scope.row)"
                v-hasPermi="['qw:autoTagsRules:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRulesDelete(scope.row)"
                v-hasPermi="['qw:autoTagsRules:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="rulesTotal>0" :total="rulesTotal" :page.sync="rulesQueryParams.pageNum"
          :limit.sync="rulesQueryParams.pageSize" @pagination="getRulesList" />
      </el-tab-pane>

      <!-- 日志Tab -->
      <el-tab-pane label="自动标签日志" name="logs">
        <el-form :model="logsQueryParams" ref="logsQueryForm" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="规则类型" prop="type">
            <el-select v-model="logsQueryParams.type" placeholder="请选择规则类型" clearable size="small">
              <el-option label="关键词打标签" :value="1" />
              <el-option label="客户入群行为打标签" :value="2" />
              <el-option label="分时段打标签" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="员工ID" prop="qwUserid">
            <el-input v-model="logsQueryParams.qwUserid" placeholder="请输入员工ID" clearable size="small"
              @keyup.enter.native="handleLogsQuery" />
          </el-form-item>
          <el-form-item label="客户ID" prop="externalUserId">
            <el-input v-model="logsQueryParams.externalUserId" placeholder="请输入客户ID" clearable size="small"
              @keyup.enter.native="handleLogsQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLogsQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetLogsQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="logsMultiple"
              @click="handleLogsDelete" v-hasPermi="['qw:autoTagsLogs:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="logsExportLoading"
              @click="handleLogsExport" v-hasPermi="['qw:autoTagsLogs:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getLogsList"></right-toolbar>
        </el-row>

        <el-table v-loading="logsLoading" :data="autoTagsLogsList" @selection-change="handleLogsSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" width="60" />
          <el-table-column label="主表ID" align="center" prop="autoTagId" width="80" />
          <el-table-column label="规则类型" align="center" prop="type" width="140">
            <template slot-scope="scope">
              <span v-if="scope.row.type === 1">关键词打标签</span>
              <span v-else-if="scope.row.type === 2">入群行为打标签</span>
              <span v-else-if="scope.row.type === 3">分时段打标签</span>
              <span v-else>{{ scope.row.type }}</span>
            </template>
          </el-table-column>
          <el-table-column label="员工ID" align="center" prop="qwUserid" :show-overflow-tooltip="true" />
          <el-table-column label="客户ID" align="center" prop="externalUserId" :show-overflow-tooltip="true" />
          <el-table-column label="标签ID" align="center" prop="tagId" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleLogsDelete(scope.row)"
                v-hasPermi="['qw:autoTagsLogs:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="logsTotal>0" :total="logsTotal" :page.sync="logsQueryParams.pageNum"
          :limit.sync="logsQueryParams.pageSize" @pagination="getLogsList" />
      </el-tab-pane>
    </el-tabs>

    <!-- 规则对话框 -->
    <el-dialog :title="rulesDialogTitle" :visible.sync="rulesDialogOpen" width="500px" append-to-body>
      <el-form ref="rulesForm" :model="rulesForm" :rules="rulesFormRules" label-width="100px">
        <el-form-item label="主表ID" prop="autoTagsId">
          <el-input v-model="rulesForm.autoTagsId" placeholder="请输入自动打标签主表ID" />
        </el-form-item>
        <el-form-item label="规则状态" prop="isApply">
          <el-radio-group v-model="rulesForm.isApply">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="rulesForm.type" placeholder="请选择规则类型">
            <el-option label="关键词打标签" :value="1" />
            <el-option label="客户入群行为打标签" :value="2" />
            <el-option label="分时段打标签" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司ID" prop="companyId">
          <el-input v-model="rulesForm.companyId" placeholder="请输入公司ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRulesForm">确 定</el-button>
        <el-button @click="rulesDialogOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAutoTagsRules, getAutoTagsRules, delAutoTagsRules, addAutoTagsRules, updateAutoTagsRules } from "@/api/qw/autoTagsRules";
import { listAutoTagsLogs, delAutoTagsLogs, exportAutoTagsLogs } from "@/api/qw/autoTagsLogs";

export default {
  name: "AutoTags",
  data() {
    return {
      activeTab: "rules",
      showSearch: true,
      // === Rules ===
      rulesLoading: false,
      rulesTotal: 0,
      autoTagsRulesList: [],
      rulesSingle: true,
      rulesMultiple: true,
      rulesIds: [],
      rulesDialogOpen: false,
      rulesDialogTitle: "",
      rulesForm: {},
      rulesFormRules: {},
      rulesQueryParams: { pageNum: 1, pageSize: 10, autoTagsId: null, isApply: null, type: null, companyId: null },
      // === Logs ===
      logsLoading: false,
      logsTotal: 0,
      autoTagsLogsList: [],
      logsSingle: true,
      logsMultiple: true,
      logsIds: [],
      logsExportLoading: false,
      logsQueryParams: { pageNum: 1, pageSize: 10, autoTagId: null, type: null, qwUserid: null, externalUserId: null },
    };
  },
  created() {
    this.getRulesList();
  },
  methods: {
    handleTabClick(tab) {
      if (tab.name === "rules") this.getRulesList();
      else if (tab.name === "logs") this.getLogsList();
    },
    // ========== Rules ==========
    getRulesList() {
      this.rulesLoading = true;
      listAutoTagsRules(this.rulesQueryParams).then(res => {
        this.autoTagsRulesList = res.rows;
        this.rulesTotal = res.total;
        this.rulesLoading = false;
      });
    },
    handleRulesQuery() { this.rulesQueryParams.pageNum = 1; this.getRulesList(); },
    resetRulesQuery() { this.resetForm("rulesQueryForm"); this.handleRulesQuery(); },
    handleRulesSelectionChange(selection) {
      this.rulesIds = selection.map(i => i.id);
      this.rulesSingle = selection.length !== 1;
      this.rulesMultiple = !selection.length;
    },
    handleRulesAdd() {
      this.rulesForm = { id: null, autoTagsId: null, rules: null, tags: null, isApply: null, type: null, companyId: null };
      this.rulesDialogOpen = true;
      this.rulesDialogTitle = "添加自动标签规则";
    },
    handleRulesUpdate(row) {
      this.rulesForm = {};
      const id = row.id || this.rulesIds;
      getAutoTagsRules(id).then(res => {
        this.rulesForm = res.data;
        this.rulesDialogOpen = true;
        this.rulesDialogTitle = "修改自动标签规则";
      });
    },
    submitRulesForm() {
      this.$refs["rulesForm"].validate(valid => {
        if (valid) {
          if (this.rulesForm.id != null) {
            updateAutoTagsRules(this.rulesForm).then(() => { this.msgSuccess("修改成功"); this.rulesDialogOpen = false; this.getRulesList(); });
          } else {
            addAutoTagsRules(this.rulesForm).then(() => { this.msgSuccess("新增成功"); this.rulesDialogOpen = false; this.getRulesList(); });
          }
        }
      });
    },
    handleRulesDelete(row) {
      const ids = row.id || this.rulesIds;
      this.$confirm('是否确认删除规则编号为"' + ids + '"的数据项?', "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" })
        .then(() => delAutoTagsRules(ids)).then(() => { this.getRulesList(); this.msgSuccess("删除成功"); }).catch(() => {});
    },
    // ========== Logs ==========
    getLogsList() {
      this.logsLoading = true;
      listAutoTagsLogs(this.logsQueryParams).then(res => {
        this.autoTagsLogsList = res.rows;
        this.logsTotal = res.total;
        this.logsLoading = false;
      });
    },
    handleLogsQuery() { this.logsQueryParams.pageNum = 1; this.getLogsList(); },
    resetLogsQuery() { this.resetForm("logsQueryForm"); this.handleLogsQuery(); },
    handleLogsSelectionChange(selection) {
      this.logsIds = selection.map(i => i.id);
      this.logsSingle = selection.length !== 1;
      this.logsMultiple = !selection.length;
    },
    handleLogsDelete(row) {
      const ids = row.id || this.logsIds;
      this.$confirm('是否确认删除日志编号为"' + ids + '"的数据项?', "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" })
        .then(() => delAutoTagsLogs(ids)).then(() => { this.getLogsList(); this.msgSuccess("删除成功"); }).catch(() => {});
    },
    handleLogsExport() {
      this.$confirm('是否确认导出所有自动标签日志数据?', "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" })
        .then(() => { this.logsExportLoading = true; return exportAutoTagsLogs(this.logsQueryParams); })
        .then(res => { this.download(res.msg); this.logsExportLoading = false; }).catch(() => {});
    },
  }
};
</script>
