<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="筛选方式" prop="filterType">
        <el-select
          v-model="queryParams.filterType"
          placeholder="请选择筛选方式"
          clearable
          size="small"
        >
          <el-option
            v-for="item in filterTypeOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板" prop="tempId">
        <el-select
          v-model="queryParams.tempId"
          placeholder="请选择模板"
          clearable
          filterable
          size="small"
          style="width: 200px;"
        >
          <el-option
            v-for="item in tempList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="固定营期" prop="isFixed">
        <el-select
          v-model="queryParams.isFixed"
          placeholder="请选择固定营期"
          clearable
          size="small"
        >
          <el-option
            v-for="item in isFixedOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="营期时间" prop="startTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择营期时间">
        </el-date-picker>
      </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"
          v-hasPermi="['wx:wxSop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="handleBatchExecute"
          v-hasPermi="['qw:sop:batchExecuteWx']"
        >批量执行个微SOP</el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="wxSopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status === 0">停止</el-tag>
          <el-tag type="success" v-else-if="scope.row.status === 1">启用</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === 2">执行中</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="筛选方式" align="center" prop="filterType">
        <template slot-scope="scope">
          <dict-tag :options="filterTypeOptions" :value="scope.row.filterType" />
        </template>
      </el-table-column>
      <el-table-column label="模板" align="center" prop="tempId">
        <template slot-scope="scope">
          <span
            v-for="item in tempList"
            :key="item.id"
            v-if="String(item.id) === String(scope.row.tempId)"
          >
            {{ item.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否固定营期" align="center" prop="isFixed">
        <template slot-scope="scope">
          <dict-tag :options="isFixedOptions" :value="scope.row.isFixed" />
        </template>
      </el-table-column>
      <el-table-column label="过期时间(小时)" align="center" prop="expiryTime">
        <template slot-scope="scope">
          {{ scope.row.expiryTime }} 小时
        </template>
      </el-table-column>
      <el-table-column label="营期开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 2 || scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="handleViewSchedule(scope.row)"
            v-hasPermi="['wx:wxSop:list']"
          >营期</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['wx:wxSop:list']"
          >执行详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wx:wxSop:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wx:wxSop:remove']"
          >删除</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"
    />

    <!-- 添加或修改个微SOP对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body class="wx-sop-dialog">
      <div class="wx-sop-dialog-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="130px" class="wx-sop-form">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document"></i>
              <span>基本信息</span>
            </div>
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入规则名称" clearable maxlength="50" show-word-limit />
            </el-form-item>
            <el-form-item label="模板" prop="tempId">
              <el-select
                v-model="form.tempId"
                placeholder="请选择模板"
                filterable
                clearable
                style="width: 100%;"
                v-loading="tempListLoading"
                @focus="loadTempList"
              >
                <el-option
                  v-for="item in tempList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <Tip title="选择想要发送的模板规则" />
            </el-form-item>
          </div>

          <!-- 筛选规则 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-s-operation"></i>
              <span>筛选规则</span>
            </div>
            <el-form-item label="筛选方式" prop="filterType">
              <el-radio-group v-model="form.filterType">
                <el-radio :label="'0'">按标签</el-radio>
                <el-radio :label="'1'">按群聊</el-radio>
              </el-radio-group>
              <Tip :title="'标签：按标签筛选客户进入SOP；群聊：按群聊筛选进入SOP'" />
            </el-form-item>
            <template v-if="form.filterType === '0'">
              <el-form-item label="选择的标签" prop="selectTags">
                <el-select
                  v-model="selectTagsList"
                  multiple
                  filterable
                  clearable
                  placeholder="请选择进入SOP的标签"
                  style="width: 100%;"
                  @change="onSelectTagsChange"
                >
                  <el-option
                    v-for="item in tagsOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="排除的标签" prop="excludeTags">
                <el-select
                  v-model="excludeTagsList"
                  multiple
                  filterable
                  clearable
                  placeholder="请选择不想进入SOP的标签"
                  style="width: 100%;"
                  @change="onExcludeTagsChange"
                >
                  <el-option
                    v-for="item in tagsOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
            <el-form-item label="执行账号" prop="accountIds">
              <el-button
                type="primary"
                plain
                icon="el-icon-user"
                size="small"
                @click="openQwUserSelect"
              >
                选择账号
                <el-tag v-if="selectedQwUsers && selectedQwUsers.length" type="success" size="mini" style="margin-left: 6px;">
                  {{ selectedQwUsers.length }}
                </el-tag>
              </el-button>
              <div v-if="selectedQwUsers && selectedQwUsers.length" class="selected-tags">
                <el-tag
                  v-for="item in selectedQwUsers"
                  :key="item.id"
                  size="mini"
                  closable
                  @close="removeQwUser(item)"
                >
                  {{ item.wxNickName || item.wxNo || item.companyUserName }}
                </el-tag>
              </div>
              <Tip title="从企微账号列表中选择用于执行个微SOP的账号" />
            </el-form-item>
          </div>

          <!-- 时间与营期 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-time"></i>
              <span>时间与营期</span>
            </div>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    clearable
                    size="small"
                    v-model="form.startTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择开始时间"
                    style="width: 100%;"
                  />
                  <Tip title="SOP开始发送时间" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="过期时间" prop="expiryTime">
                  <div class="expiry-time-wrap">
                    <el-input-number
                      v-model="form.expiryTime"
                      :min="1"
                      :max="100"
                      controls-position="right"
                      style="flex: 1;"
                    />
                    <span class="unit-text">小时</span>
                  </div>
                  <Tip title="待发送消息超过此时间未发送将自动作废" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="固定营期" prop="isFixed">
              <el-radio-group v-model="form.isFixed">
                <el-radio :label="'0'">否</el-radio>
                <el-radio :label="'1'">是</el-radio>
              </el-radio-group>
              <Tip title="固定营期：不管什么时候进入SOP的客户，营期时间都为任务开始时间" />
            </el-form-item>
          </div>

          <!-- 其他 -->
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-edit-outline"></i>
              <span>其他</span>
            </div>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注（选填）" maxlength="200" show-word-limit />
            </el-form-item>
          </div>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>

      <qw-user-select @success="selectQwUserFun" ref="qwUserSelect" />
    </el-dialog>
  </div>
</template>

<script>
import { listWxSop, getWxSop, delWxSop, addWxSop, updateWxSop, exportWxSop, updateWxStatus } from "@/api/wx/wxSop";
import { listSopTemp } from "@/api/qw/sopTemp";
import Tip from "@/components/Tip";
import QwUserSelect from "@/views/components/QwUserSelect.vue";

export default {
  name: "WxSop",
  components: { Tip, QwUserSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 模板下拉数据
      tempList: [],
      tempListLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个微SOP表格数据
      wxSopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 选择的企微账号
      selectedQwUsers: [],
      // 标签库（与线索客户打标签共用 crm_customer_tag）
      tagsOptions: [],
      selectTagsList: [],
      excludeTagsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        filterType: null,
        selectTags: null,
        excludeTags: null,
        tempId: null,
        isFixed: null,
        expiryTime: null,
        startTime: null,
      },
      // 本地字典（筛选方式、是否固定营期）
      filterTypeOptions: [
        { dictValue: "0", dictLabel: "按标签筛选" },
        { dictValue: "1", dictLabel: "按群聊筛选" },
      ],
      isFixedOptions: [
        { dictValue: "0", dictLabel: "否" },
        { dictValue: "1", dictLabel: "是" },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
        tempId: [{ required: true, message: "请选择模板", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
    this.loadTempList();
    this.getDicts("crm_customer_tag").then((response) => {
      this.tagsOptions = response.data || [];
    });
  },
  methods: {
    loadTempList() {
      this.tempListLoading = true;
      listSopTemp()
        .then(response => {
          this.tempList = response.rows || [];
        })
        .finally(() => {
          this.tempListLoading = false;
        });
    },
    onSelectTagsChange(val) {
      this.form.selectTags = Array.isArray(val) ? val.join(",") : "";
    },
    onExcludeTagsChange(val) {
      this.form.excludeTags = Array.isArray(val) ? val.join(",") : "";
    },
    syncTagsFromForm() {
      this.selectTagsList = this.form.selectTags ? String(this.form.selectTags).split(",").filter(Boolean) : [];
      this.excludeTagsList = this.form.excludeTags ? String(this.form.excludeTags).split(",").filter(Boolean) : [];
    },
    /** 查询个微SOP列表 */
    getList() {
      this.loading = true;
      listWxSop(this.queryParams).then(response => {
        this.wxSopList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        filterType: "0",
        selectTags: null,
        excludeTags: null,
        tempId: null,
        tempName: null,
        isFixed: "0",
        accountIds: null,
        expiryTime: 24,
        startTime: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.selectTagsList = [];
      this.excludeTagsList = [];
      this.resetForm("form");
    },
    // 打开企微账号选择
    openQwUserSelect() {
      this.$nextTick(() => {
        this.$refs.qwUserSelect && this.$refs.qwUserSelect.setRows(this.selectedQwUsers);
      });
    },
    // 选择企微账号回调（数据源与外呼任务分配账号一致）
    selectQwUserFun(e) {
      this.selectedQwUsers = e.rows || [];
      const ids = e.ids || [];
      this.form.accountIds = ids.join(",");
      this.$forceUpdate();
    },
    removeQwUser(item) {
      this.selectedQwUsers = this.selectedQwUsers.filter((u) => u.id !== item.id);
      this.form.accountIds = this.selectedQwUsers.map((u) => u.id).join(",");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加个微SOP";
      this.loadTempList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWxSop(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改个微SOP";
        // 兼容后端返回 number，确保 radio 正常回显
        this.form.filterType =
          this.form.filterType === null || typeof this.form.filterType === "undefined"
            ? "0"
            : String(this.form.filterType);
        this.form.isFixed =
          this.form.isFixed === null || typeof this.form.isFixed === "undefined"
            ? "0"
            : String(this.form.isFixed);
        this.syncTagsFromForm();
        // 回显执行账号
        this.selectedQwUsers = response.data.selectedQwUsers || [];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = this.buildSubmitPayload();
          if (this.form.id != null) {
            updateWxSop(payload).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWxSop(payload).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 构建提交数据，确保与后端 WxSop 字段一致 */
    buildSubmitPayload() {
      const f = this.form;
      return {
        id: f.id,
        name: f.name,
        filterType: f.filterType != null ? parseInt(f.filterType, 10) : 0,
        selectTags: f.selectTags || null,
        excludeTags: f.excludeTags || null,
        tempId: f.tempId != null ? String(f.tempId) : null,
        isFixed: f.isFixed != null ? parseInt(f.isFixed, 10) : 0,
        expiryTime: f.expiryTime != null ? parseInt(f.expiryTime, 10) : 24,
        startTime: f.startTime || null,
        remark: f.remark || null,
        accountIds: f.accountIds || null
      };
    },
    /** 查看营期按钮操作 */
    handleViewSchedule(row) {
      this.$router.push({
        path: '/wxSop/sopUserLogsWx/sopUserLogsScheduleWx/' + row.id,
        query: {
          name: row.name,
          tempId: row.tempId
        }
      });
    },
    /** 查看执行详情按钮操作 */
    handleViewDetail(row) {
      this.$router.push({
        path: '/wxSop/wxSop/sopLogsList/' + row.id,
        query: {
          name: row.name,
          tempId: row.tempId
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除个微SOP编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delWxSop(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 批量执行个微SOP */
    handleBatchExecute() {
      if (this.ids.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }

      // 过滤出启用状态的SOP
      const enabledSops = this.wxSopList.filter(item => 
        this.ids.includes(item.id) && item.status === 1
      );

      if (enabledSops.length === 0) {
        this.$message.warning("所选SOP中没有启用状态的记录，只能执行启用状态的SOP");
        return;
      }

      const enabledIds = enabledSops.map(item => item.id);
      const notEnabledCount = this.ids.length - enabledIds.length;

      let confirmMsg = `是否确认批量执行所选的${enabledIds.length}条个微SOP？`;
      if (notEnabledCount > 0) {
        confirmMsg += `\n注意：已自动过滤${notEnabledCount}条非启用状态的记录`;
      }

      this.$confirm(confirmMsg, "批量执行确认", {
        confirmButtonText: "确定执行",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: true
      }).then(() => {
        this.loading = true;
        return updateWxStatus(enabledIds.join(","));
      }).then(response => {
        this.loading = false;
        
        console.log('批量执行个微SOP接口返回数据:', response);
        
        // 解析后端返回的统计信息
        if (response && response.msg) {
          const successCount = response.data?.successCount || enabledIds.length;
          const failCount = response.data?.failCount || 0;
          
          let msg = `批量执行完成！`;
          msg += `\n成功：${successCount}条`;
          if (failCount > 0) {
            msg += `\n失败：${failCount}条`;
          }
          
          this.msgSuccess(msg);
        } else {
          this.msgSuccess(`已成功执行${enabledIds.length}条个微SOP`);
        }
        
        // 刷新列表
        this.getList();
      }).catch(error => {
        this.loading = false;
        if (error !== 'cancel' && error !== 'close') {
          console.error('批量执行个微SOP失败:', error);
          this.msgError("批量执行失败，请稍后重试");
        }
      });
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有个微SOP数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportWxSop(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.wx-sop-dialog-content {
  padding: 8px 16px 24px;
  max-height: 70vh;
  overflow-y: auto;
}

.wx-sop-form {
  .form-section {
    background: #fafbfc;
    border-radius: 10px;
    padding: 24px 28px;
    margin-bottom: 24px;
    border: 1px solid #ebeef5;
  }

  .form-section:last-of-type {
    margin-bottom: 0;
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 14px;
    border-bottom: 1px solid #e4e7ed;
  }

  .section-title i {
    font-size: 18px;
    color: #409eff;
  }

  ::v-deep .el-form-item {
    margin-bottom: 22px;
  }

  ::v-deep .el-form-item:last-child {
    margin-bottom: 0;
  }

  .expiry-time-wrap {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
  }

  .unit-text {
    color: #909399;
    font-size: 13px;
    flex-shrink: 0;
  }

  .selected-tags {
    margin-top: 12px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .selected-tags .el-tag {
    margin: 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 16px 0 8px;
}
</style>
