<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="企微公司" prop="corpId">
        <el-select v-model="queryParams.corpId" placeholder="企微公司" size="small" @change="updateCorpId()">
          <el-option
            v-for="dict in myQwCompanyList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="成员" prop="qwUserIds">
        <el-select v-model="queryParams.qwUserIds" filterable clearable placeholder="选择成员" size="small">
          <el-option
            v-for="dict in companyUserList"
            :key="dict.id"
            :label="dict.qwUserName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则编号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入规则名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型 " prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small" @change="updateCorpId()">
          <el-option
            :key="1"
            :label="'个微'"
            :value="1"
          />
          <el-option
            :key="2"
            :label="'企微'"
            :value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则状态 " prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择规则状态" clearable size="small"
                   @change="updateCorpId()">
          <el-option
            v-for="dict in sysSopStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <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="createTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.createTime"
                        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="['qw:sop:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qw:sop:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['qw:sop:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          plain
          type="warning"
          icon="el-icon-edit"
          :disabled="multiple"
          @click="handleExecute"
          v-hasPermi="['qw:sop:execute']"
        >批量执行SOP
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" border :data="sopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="规则编号" align="center" prop="id" width="160"/>
      <el-table-column label="规则名称" align="center" prop="name" width="150"/>
      <el-table-column label="规则状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <dict-tag :options="sysSopStatus" :value="scope.row.status"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type==1">个微</el-tag>
          <el-tag type="primary" v-else-if="scope.row.type==2">企微<span v-if="scope.row.filterMode == 2">(群聊)</span></el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发送方式" align="center" prop="sendType">
        <template slot-scope="scope">
          <dict-tag :options="sysQwSopType" :value="scope.row.sendType"/>
        </template>
      </el-table-column>
      <el-table-column label="成员" align="center" prop="qwUserIds" width="150">
        <template slot-scope="scope">
          <!-- 点击事件绑定到整个 div -->
          <div @click="toggleRow(scope.row)" v-if="scope.row.filterMode == 1">
            <!-- 显示当前行的成员数量 -->
            <span v-if="!expandedRows[scope.row.id]">
            点击展开 ({{ scope.row.qwUserIds.split(',').length }} 人)
          </span>
            <!-- 展开时显示所有成员 -->
            <div v-show="expandedRows[scope.row.id]">
              <div v-if="scope.row.type==2" v-for="id in scope.row.qwUserIds.split(',')" :key="id"
                   style="display: inline;" class="text-container">
                <el-tag type="success" v-for="list in companyUserList" :key="list.qwUserId" style="margin: 3px;"
                        v-if="list.id==id">
                  {{ list.qwUserName }}
                </el-tag>
              </div>
              <div v-if="scope.row.type==1" v-for="id in scope.row.qwUserIds.split(',')" :key="id"
                   style="display: inline;" class="text-container">
                <el-tag type="success" v-for="list in companyUserLists" :key="list.userId" style="margin: 3px;"
                        v-if="list.userId==id">
                  {{ list.nickName }}
                </el-tag>
              </div>
            </div>
          </div>
          <div @click="toggleRow(scope.row)" v-if="scope.row.filterMode == 2">
            <!-- 显示当前行的成员数量 -->
            <span v-if="!expandedRows[scope.row.id]">
            点击展开 ({{ scope.row.chatId.split(',').length }} 个)
          </span>
            <!-- 展开时显示所有成员 -->
            <div v-show="expandedRows[scope.row.id]">
              <div v-for="id in scope.row.chatId.split(',')" :key="id"
                   style="display: inline;" class="text-container">
                <el-tag type="success" v-for="list in chatList" :key="list.chatId" style="margin: 3px;"
                        v-if="list.chatId == id">
                  {{ list.name }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="模板" align="center" prop="tempId">
        <template slot-scope="scope">
          <div v-for="id in tempList" v-if="id.id==scope.row.tempId">{{ id.name }}</div>
        </template>
      </el-table-column>

      <el-table-column label="新客户自动创建sop" align="center" prop="isAutoSop" width="140">
        <template slot-scope="scope">
          <el-switch
            v-if="(scope.row.sendType==2 || scope.row.sendType==4) && scope.row.filterMode == 1"
            v-model="scope.row.isAutoSop"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchAutoSopChange(scope.row.id,scope.row.isAutoSop)">
          </el-switch>
          <span v-if="scope.row.sendType!=1 && scope.row.isAutoSop == '1' && scope.row.filterMode == 1"
                style="margin-left: 10px;color: #13ce66">已开启</span>
          <span v-if="scope.row.sendType!=1 && scope.row.isAutoSop == '2' && scope.row.filterMode == 1"
                style="margin-left: 10px;color: #ff4949">已关闭</span>
          <span v-if="scope.row.sendType==1 && scope.row.filterMode == 1" style="margin-left: 10px;color: rgb(250,114,3)">企微接口无法设置</span>
        </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="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="修改规则状态时间" align="center" prop="stopTime" width="180"/>
      <el-table-column label="查看操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==2||scope.row.status==0 || scope.row.status == 3 || scope.row.status == 4 "
            size="mini"
            type="text"
            @click="selectSchedule(scope.row)"
            v-hasPermi="['qw:sop:list']"
          >营期
          </el-button>
          <el-button
            v-if="scope.row.status==2 || scope.row.status==0 || scope.row.status == 3 || scope.row.status == 4  "
            size="mini"
            type="text"
            style="color: green;"
            @click="handleScheduleDetail(scope.row)"
            v-hasPermi="['qw:sop:list']"
          >执行详情
          </el-button>
          <el-button
            v-if="scope.row.status==2 || scope.row.status==0 || scope.row.status == 3 || scope.row.status == 4  "
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,2)"
            v-hasPermi="['qw:sop:edit']"
          >查看规则
          </el-button>
          <el-button
            v-if="scope.row.status==2 || scope.row.status==0 || scope.row.status == 3 || scope.row.status == 4  "
            size="mini"
            type="text"
            style="color: green;"
            @click="handleQueryDetails(scope.row)"
            v-hasPermi="['qw:sop:list']"
          >查看模板
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="修改操作" align="center" class-name="small-padding fixed-width" width="100px"
                       fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdateOutTime(scope.row)"
          >修改时间/评级/大小转
          </el-button>
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.filterMode == 2 && (scope.row.status==2||scope.row.status==0 || scope.row.status == 3 || scope.row.status == 4)"
            @click="handleSendMsg(scope.row)"
          >一键发群
          </el-button>
          <el-button
            v-if="scope.row.status == 1  "
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,1)"
            v-hasPermi="['qw:sop:edit']"
          >修改规则
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="color: red;"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:sop: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="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              :label="1"
            >个微
            </el-radio>
            <el-radio
              :label="2"
            >企微
            </el-radio>
            <el-radio
              :label="3"
            >群聊
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!--        <div v-if="form.type==2">-->

        <!--        <el-form-item label="推送方式 ">-->
        <!--          <el-radio-group v-model="form.sendType" @input="handleSendTypeChange">-->
        <!--            <el-radio-->
        <!--              v-for="dict in sysQwSopType"-->
        <!--              :key="dict.dictValue"-->
        <!--              :label="parseInt(dict.dictValue)"-->
        <!--            >{{dict.dictLabel}}</el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!--          <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%">-->
        <!--            <div>-->
        <!--              <el-button-->
        <!--                size="medium"-->
        <!--                icon="el-icon-circle-plus-outline"-->
        <!--                plain-->
        <!--                @click="handlelistUser(form.type,form.sendType)">请选择使用员工</el-button>-->
        <!--            </div>-->
        <!--            <div>-->
        <!--              <el-tag-->
        <!--                style="margin-left: 5px"-->
        <!--                size="medium"-->
        <!--                :key="id"-->
        <!--                v-for="id in userSelectList"-->
        <!--                closable-->
        <!--                :disable-transitions="false"-->
        <!--                @close="handleClosegroupUser(id)">-->
        <!--                <span v-for="list in companyUserList" :key="list.qwUserId" v-if="list.id==id">{{list.qwUserName}}</span>-->
        <!--              </el-tag>-->
        <!--            </div>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="标签规则" prop="filterType">-->
        <!--            <el-radio-group v-model="form.filterType">-->
        <!--              <el-radio-->
        <!--                :label="1"-->
        <!--              >含全部标签</el-radio>-->
        <!--              <el-radio-->
        <!--                :label="2"-->
        <!--              >含任意标签</el-radio>-->
        <!--            </el-radio-group>-->
        <!--          </el-form-item>-->
        <!--          <el-form-item label="选择的标签" prop="tags">-->
        <!--            <el-select v-model="tags" remote multiple placeholder="请选择" filterable  style="width: 100%;">-->
        <!--              <el-option-->
        <!--                v-for="dict in tagList"-->
        <!--                :label="dict.name"-->
        <!--                :value="dict.tagId">-->
        <!--              </el-option>-->
        <!--            </el-select>-->

        <!--          </el-form-item>-->
        <!--          <el-form-item label="排除的标签" prop="excludeTags">-->
        <!--            <el-select v-model="excludeTags" remote multiple placeholder="请选择" filterable  style="width: 100%;">-->
        <!--              <el-option-->
        <!--                v-for="dict in tagList"-->
        <!--                :label="dict.name"-->
        <!--                :value="dict.tagId">-->
        <!--              </el-option>-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </div>-->
        <!--        <div v-if="form.type==1">-->
        <!--          <el-form-item label="推送方式 ">-->
        <!--            <el-tag type="success" v-model="form.sendType=2">AI插件</el-tag>-->
        <!--          </el-form-item>-->
        <!--        </div>-->

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable size="small"
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="模板" prop="tempId">
          <el-select v-model="form.tempId" @focus="selectListSopTemp(form.sendType)" placeholder="请选择模板"
                     v-loading="tempListLoading">
            <el-option
              v-for="dict in tempList"
              :label="dict.name"
              :value="dict.id">
            </el-option>
            <div v-if="tempListLoading" slot="prefix" class="select-prefix">正在查询相应模板...</div>
          </el-select>
        </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="listUser.title" :visible.sync="listUser.open" style="width: 1300px;height: 100%" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    <!-- 单独的修改时间   -->
    <el-dialog :title="outTimeOpen.title" :visible.sync="outTimeOpen.open" width="500px">

      <el-col>

        <el-row>
          <span>过期时间：</span>
          <el-input-number v-model="outTimeOpen.expiryTime" :min="1" :max="100"></el-input-number>
          （小时）
        </el-row>

        <el-row style="margin-top: 3%">
          <span>是否开启客户评级：</span>
          <el-switch
            v-model="outTimeOpen.isRating"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2">
          </el-switch>
          <span v-if="outTimeOpen.isRating == '1'" style="margin-left: 10px;color: #13ce66">已开启</span>
          <span v-if="outTimeOpen.isRating == '2'" style="margin-left: 10px;color: #ff4949">已关闭</span>
        </el-row>
        <el-row>
          <span>小转天数：</span>
          <el-input-number v-model="outTimeOpen.minConversionDay"></el-input-number>
          （天）
        </el-row>
        <el-row>
          <span>大转天数：</span>
          <el-input-number v-model="outTimeOpen.maxConversionDay"></el-input-number>
          （天）
        </el-row>
        <el-row>
          <span>发课开始天数：</span>
          <el-input-number v-model="outTimeOpen.courseDay" :min="1" :max="100"></el-input-number>
          （天）
        </el-row>
        <el-row style="margin-top: 3%">

          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUpdateExpiryTime">确定修改
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetUpdateExpiryTime">取消</el-button>
        </el-row>


      </el-col>
    </el-dialog>
    <!-- 单独的修改时间   -->
    <el-dialog title="语音记录" :visible.sync="voiceForm.open" width="70%" append-to-body>
      <el-row style="height: 600px">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['qw:sop:add']"
        >新增
        </el-button>
        <el-table border :data="voiceForm.list">
          <el-table-column label="员工" align="center" prop="companyUserName"/>
          <el-table-column label="名称" align="center" prop="name"/>
          <el-table-column label="天数" align="center" prop="dayNum">
            <template slot-scope="scope">
              第{{ scope.row.dayNum }}天
            </template>
          </el-table-column>
          <el-table-column label="发送时间" align="center" prop="time"/>
          <el-table-column label="语音文本" align="center" prop="voiceTxt"/>
          <el-table-column label="语音时长" align="center" prop="duration">
            <template slot-scope="scope">
              {{ scope.row.duration }}秒
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="voiceForm.total>0"
          :total="voiceForm.total"
          :page.sync="voiceForm.queryParams.pageNum"
          :limit.sync="voiceForm.queryParams.pageSize"
          @pagination="voice(voiceForm.queryParams.id)"
        />
      </el-row>
    </el-dialog>
    <el-dialog :title="autoSopOpen.title" :visible.sync="autoSopOpen.open" style="width: 1300px;height: 100%"
               append-to-body>
      <el-form ref="autoSopTimeFrom" :model="form.autoSopTime" :rules="autoSopTimeRules">
        <el-form-item label="自动类型" prop="type" style="margin: 2%; display: flex; align-items: center;">
          <el-radio-group v-model="form.autoSopTime.autoSopType">
            <el-radio
              :label="1"
            >当天开始
            </el-radio>
            <el-radio
              :label="2"
            >次日开始
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="display: flex; align-items: center; flex-wrap: nowrap;">
          <div v-if="form.autoSopTime.autoSopType==1" style="display: flex; align-items: center">
            <el-form-item
              label="起始时间"
              prop="autoStartTime"
              label-width="100px"
              style="margin: 2% 0;align-items: center;">
              <el-time-select
                style="width: 120px;"
                placeholder="起始时间"
                v-model="form.autoSopTime.autoStartTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00'
                }">
              </el-time-select>
            </el-form-item>
            <el-form-item
              label="结束时间"
              prop="autoEndTime"
              label-width="100px"
              style="margin: 2% 0; align-items: center; ">
              <el-time-select
                style="width: 120px;"
                placeholder="结束时间"
                v-model="form.autoSopTime.autoEndTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                  minTime: form.autoSopTime.autoEndTime
                }">
              </el-time-select>
            </el-form-item>
          </div>
        </div>
        <el-form-item v-if="form.autoSopTime.autoSopType==1" label="过期消息是否发送" prop="autoSopSend"
                      style="margin: 2%; display: flex; align-items: center;">
          <el-radio-group v-model="form.autoSopTime.autoSopSend">
            <el-radio
              :label="1"
            >是
            </el-radio>
            <el-radio
              :label="2"
            >否
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-alert
          v-if="form.autoSopTime.autoSopType==1"
          title="起始时间-结束时间之内的，当天立即创建SOP，时间之外的 次日创建SOP"
          type="warning"
          style="font-size: 15px; margin-top: 3%;"
          :closable="false"
          show-icon>
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAutoSopTimeFrom">确 定</el-button>
        <el-button @click="cancelAutoSopTime">取 消</el-button>
      </div>
    </el-dialog>
    <!--  执行详情  -->
    <el-drawer :title="sopLogsDialog.title" :visible.sync="sopLogsDialog.open" size="70%" style="font-weight: bolder">
      <sopLogsDetails ref="sopLogsDetails" :rowDetailFrom="sopLogsDialog.sopLogsForm"></sopLogsDetails>
    </el-drawer>


    <el-dialog :title="sendMsgOpen.title" :visible.sync="sendMsgOpen.open"  width="1000px" append-to-body>
      <el-form ref="msgForm" :model="msgForm" :rules="msgRules" label-width="100px">
        <el-form-item label="群">
          <el-select  v-model="msgForm.chatIds" placeholder="请选择群" size="mini" multiple>
            <el-option
              v-for="chatId in sendMsgOpen.row && sendMsgOpen.row.chatId ? sendMsgOpen.row.chatId.split(',') : []"
              :key="chatId"
              :label="chatList.filter(e => e.chatId == chatId) ? chatList.filter(e => e.chatId == chatId)[0].name : ''"
              :value="chatId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送类型">
          <el-radio-group v-model="msgForm.sendType">
            <el-radio :label="1">群</el-radio>
            <el-radio :label="2">群成员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择课程">
          <el-select  v-model="msgForm.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChange()">
            <el-option
              v-for="dict in courseList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
          <el-select  v-model="msgForm.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange()"  >
            <el-option
              v-for="dict in videoList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
          <el-select  v-model="msgForm.courseType" placeholder="请选择消息类型" size="mini" style=" margin-right: 10px;">
            <el-option
              v-for="dict in sysFsSopWatchStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则" prop="setting"  >
          <div v-for="(item, index) in setting" :key="index" style="background-color: #fdfdfd; border: 1px solid #e6e6e6; margin-bottom: 20px;">
            <el-row>
              <el-col :span="22">
                <el-form :model="item" label-width="70px">
                  <el-form-item label="内容类别" style="margin: 2%">
                    <el-radio-group  v-model="item.contentType">
                      <el-radio   :label="item.dictValue" v-for="item in sysQwSopAiContentType"  @change="handleContentTypeChange()">{{item.dictLabel}}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="内容" style="margin-bottom: 2%" >
                    <el-input v-if="item.contentType == 1 " v-model="item.value" type="textarea" :rows="3" placeholder="内容" style="width: 90%;margin-top: 10px;"/>

                    <ImageUpload v-if="item.contentType == 2 " v-model="item.imgUrl" type="image" :num="1"  :width="150" :height="150" />

                    <div v-if="item.contentType == 3 ">
                      <el-card class="box-card">
                        <el-form-item label="链接标题:"  label-width="100px">
                          <el-input v-model="item.linkTitle" placeholder="请输入链接标题" style="width: 90%;"/>
                        </el-form-item>
                        <el-form-item label="链接描述:"   label-width="100px" >
                          <el-input type="textarea" :rows="3" v-model="item.linkDescribe" placeholder="请输入链接描述" style="width: 90%;margin-top: 1%;"/>
                        </el-form-item>
                        <el-form-item label="链接封面:"   label-width="100px">
                          <ImageUpload v-model="item.linkImageUrl" type="image" :num="1" :file-size="2" :width="150" :height="150" style="margin-top: 1%;" />
                        </el-form-item>
                        <el-form-item label="链接地址:"  label-width="100px" >
                          <el-tag type="warning" v-model="item.isBindUrl=1">选择的课程小节 即为卡片链接地址</el-tag>
                        </el-form-item>
                      </el-card>
                    </div>
                    <div v-if="item.contentType == 4">

                    </div>
                    <div v-if="item.contentType == 5 ">

                      <el-form-item label="上传文件:" prop="fileUrl" label-width="100px">
                        <el-upload
                          v-model="item.fileUrl"
                          class="avatar-uploader"
                          :action="uploadUrl"
                          :show-file-list="false"
                          :on-success="(res, file) => handleAvatarSuccessFile(res, file, item)"
                          :before-upload="beforeAvatarUploadFile">
                          <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <el-link v-if="item.fileUrl" type="primary" :href="downloadUrl(item.fileUrl)" download>
                          {{item.fileUrl}}
                        </el-link>
                      </el-form-item>

                    </div>

                    <div v-if="item.contentType == 6 ">
                      <el-form-item label="上传视频：" prop="videoUrl" label-width="100px">
                        <el-upload
                          v-model="item.videoUrl"
                          class="avatar-uploader"
                          :action="uploadUrl"
                          :show-file-list="false"
                          :on-success="(res, file) => handleAvatarSuccessVideo(res, file, item)"
                          :before-upload="beforeAvatarUploadVideo">
                          <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        <video v-if="item.videoUrl"
                               :src="item.videoUrl"
                               controls style="width: 200px;height: 100px">
                        </video>
                      </el-form-item>
                    </div>
                    <div v-if="item.contentType == 7 ">
                      <el-input
                        v-model="item.value"
                        type="textarea" :rows="3" maxlength="66" show-word-limit
                        placeholder="输入要转为语音的内容" style="width: 90%;margin-top: 10px;"
                        @input="handleInputVideoText(item.value,item)"/>
                    </div>

                    <div v-if="item.contentType == 10 ">
                      <el-card class="box-card">
                        <el-form-item label="链接标题:"  label-width="100px">
                          <el-input v-model="item.linkTitle" placeholder="请输入链接标题" style="width: 90%;"/>
                        </el-form-item>
                        <el-form-item label="链接描述:"   label-width="100px" >
                          <el-input type="textarea" :rows="3" v-model="item.linkDescribe" placeholder="请输入链接描述" style="width: 90%;margin-top: 1%;"/>
                        </el-form-item>
                        <el-form-item label="链接封面:"   label-width="100px">
                          <ImageUpload v-model="item.linkImageUrl" type="image" :num="1" :file-size="2" :width="150" :height="150" style="margin-top: 1%;" />
                        </el-form-item>
                        <el-form-item label="链接地址:"  label-width="100px" >
                          <el-tag type="warning" >链接地址自动生成</el-tag>
                        </el-form-item>
                      </el-card>
                    </div>
                  </el-form-item>

                  <el-form-item label="添加短链" v-if="item.contentType == 1 "  >
                    <el-tooltip content="请先根据课程选定课程小节之后再添加" effect="dark" :disabled="!!msgForm.videoId">
                      <el-switch
                        v-model="item.isBindUrl"
                        :disabled="!msgForm.videoId"
                        active-color="#13ce66"
                        inactive-color="#DCDFE6"
                        active-value="1"
                        inactive-value="2">
                      </el-switch>
                    </el-tooltip>

                    <span v-if="item.isBindUrl == '1'" style="margin-left: 10px; color: #13ce66">添加URL</span>
                    <span v-if="item.isBindUrl == '2'" style="margin-left: 10px; color: #b1b4ba">不加URL</span>
                  </el-form-item>
                  <el-form-item label="课节过期时间" v-if="item.isBindUrl == '1'
                                                          && item.contentType != 2
                                                          && item.contentType != 5
                                                          && item.contentType != 6
                                                          && item.contentType != 8
                                                          && item.contentType != 9
                                                          && item.contentType != 10"
                                style="margin-top: 1%" label-width="100px">
                    <el-row>
                      <el-input-number  v-model="item.expiresDays"  :min="1" :max="100" ></el-input-number>
                      （天）
                    </el-row>
                    <el-row>
                      <span class="tip">填写0或不填时，默认为系统配置的默认时间</span>
                    </el-row>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="1" :offset="1">
                <i class="el-icon-delete" @click="delSetList(index)" style="margin-top: 20px;" v-if="setting.length>1"></i>
              </el-col>
            </el-row>
          </div>
          <el-link type="primary" class="el-icon-plus" :underline="false" @click='addSetList()'  >添加内容</el-link>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMsgForm">确 定</el-button>
        <el-button @click="cancelMsgForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addSop,
  courseList,
  delSop,
  exportSop,
  getSopVoiceList,
  listSop,
  updateAutoSopTime,
  updateSop,
  updateSopStatus,
  updateStatus,
  videoList
} from "@/api/qw/sop";
import {sendMsgSop} from "@/api/qw/sopUserLogsInfo";
import {listSopTemp} from "@/api/qw/sopTemp";
import {getQwAllUserList, listUser} from '@/api/company/companyUser'
import qwUserList from '@/views/qw/user/qwUserList.vue'
import ImageUpload from "@/views/qw/sop/ImageUpload";
import CustomerGroupDetails from '@/views/qw/groupMsg/customerGroupDetails.vue'
import sopLogsDetails from '@/views/qw/sopLogs/sopLogsList.vue'
import {listTag,} from "@/api/qw/tag";
import {getMyQwCompanyList} from "@/api/qw/user";
import {allList} from "@/api/qw/groupChat";

export default {
  name: "Sop",
  components: {CustomerGroupDetails, qwUserList, ImageUpload, sopLogsDetails},
  data() {
    return {
      // 存储每一行的展开状态
      expandedRows: {},
      //模板查询
      tempListLoading: false,
      voiceLoading :false,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      uploadUrlByVoice:process.env.VUE_APP_BASE_API+"/common/uploadOSSByHOOKVoice",
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      videoList:[],
      // 选中数组
      ids: [],
      //选中的map
      selectionMap: {},
      myQwCompanyList: [],
      //销售员工列表
      companyUserLists: [],
      chatList: [],
      courseList: [],
      sendMsgOpen:{
        title:'一键批量群发',
        open:false,
        row: {},
        ids:null,
      },
      // videoList:[],
      tags: null,
      excludeTags: null,
      // 非单个禁用
      single: true,
      setting: [],
      tagList: [],
      tempList: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      msgForm:{
        videoId:null,
        courseId:null,
        courseType:null,
        userIdParam:null,
        sendType:1,
        setting:null,
        ids:null,
        sopId: null,
        startTime: null,
        chatIds: [],
        isRegister:2
      },
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      companyUserList: [],
      // 状态字典
      statusOptions: [],
      //sop状态
      sysSopStatus: [],

      autoSopOpen: {
        title: '',
        open: false,
        id: null,
        isAutoSop: null,
      },
      outTimeOpen: {
        title: '',
        open: false,
        id: null,
        tempId: null,
        expiryTime: null,
        isRating: null,
      },
      voiceForm: {
        list: [],
        open: false,
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id: null,
        },
      },

      //企微SOP发送类型
      sysQwSopType: [],
      sysQwSopAiContentType: [],

      //SOP课程观看状态
      sysFsSopWatchStatus: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        name: null,
        status: null,
        sendType: null,
        type: null,
        qwUserIds: null,
        setting: null,
        createBy: null,
        corpId: null,
        createTime: null
      },
      sopLogsDialog: {
        title: '',
        open: false,
        sopLogsForm: [],
      },
      // 表单参数
      form: {
        autoSopTime: {autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2},
      },
      userSelectList: [],
      listUser: {
        title: "",
        open: false
      },
      msgRules:{},
      // 表单校验
      rules: {
        name: [{required: true, message: "名称不能为空", trigger: "submit"}],
        type: [{required: true, message: "不能为空", trigger: "submit"}],
        sendType: [{required: true, message: "不能为空", trigger: "submit"}],
        startTime: [{required: true, message: "开始时间不能为空", trigger: "submit"}],
        tempId: [{required: true, message: "模板不能为空", trigger: "submit"}],
      },
      autoSopTimeRules: {
        autoSopType: [{required: true, message: "选项不能为空", trigger: "submit"}],
        autoStartTime: [{required: true, message: "起始时间不能为空", trigger: "submit"}],
        autoEndTime: [{required: true, message: "结束时间不能为空", trigger: "submit"}],
      }
    };
  },
  created() {

    this.getDicts("sys_sop_status").then(response => {
      this.sysSopStatus = response.data;
    });

    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });

    this.getDicts("sys_qw_sop_type").then(response => {
      this.sysQwSopType = response.data;
    });


    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });
    this.getDicts("sys_fs_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });
    listUser().then(res => {
        this.companyUserLists = res.rows;
      }
    );

    courseList().then(response => {
      this.courseList = response.list;
    });


    getMyQwCompanyList().then(response => {
      this.myQwCompanyList = response.data;
      if (this.myQwCompanyList != null) {
        this.queryParams.corpId = this.myQwCompanyList[0].dictValue;
        this.refreshData(this.queryParams.corpId);
        this.getList();
      }
    });


  },
  watch: {
    userSelectList(newList) {
      this.form.qwUserIds = newList.map(item => item.id);
    }
  },
  methods: {
    voice(id) {
      this.voiceForm.queryParams.id = id;
      getSopVoiceList(this.voiceForm.queryParams).then(res => {
        this.voiceForm.list = res.rows;
        this.voiceForm.total = res.total;
        this.voiceForm.open = true;
      })
    },
    // 单元格点击事件
    handleCellClick(row, column, cell, event) {
      // 判断是否为规则编号列
      if (column.property === 'id') {
        this.handleRowClick(row); // 触发规则编号点击事件
      }
    },
    // handleUpdateTags(){
    //
    // },
    // handleUpdateQwUser(){
    //
    // },
    // handleUpdateSopTemp(){
    //
    // },
    handleRowClick(row, column, event) {
      // 判断状态是否符合条件
      if (row.status == 2 || row.status == 0 || row.status == 3 || row.status == 4) {
        this.handleUpdate(row, 2);
      }
    },
    // 切换某一行的展开状态
    toggleRow(row) {
      this.$set(this.expandedRows, row.id, !this.expandedRows[row.id]);
    },
    getSwitchVal(status) {
      return [2, 3, 4].includes(status) ? 2 : 0;
    },

    onSwitchChange(row, val) {
      this.loading = true;
      // ① 调用接口更新后端
      updateSopStatus({id: row.id, status: val})
        .then(() => {
          row.status = val;
          this.loading = false;
          this.$message.success("切换成功！");
        })
        .catch(() => {
          this.loading = false;
          this.$message.error("操作失败，请重试");
        });
    },

    switchSopStatusChange(row, checked) {

      let loadingRock = this.$loading({
        lock: true,
        text: '暂停中-请勿刷新页面-重复点击',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });


      updateSopStatus({id: row, status: checked}).then(response => {
        this.$message.success("修改成功");
        this.getList();
      }).finally(res => {
        loadingRock.close();
      })


    },

    //新客户自动创建sop
    switchAutoSopChange(row, checked) {

      if (checked == 1) {
        this.autoSopOpen.title = '请设置相应时间段'
        this.autoSopOpen.open = true;
        this.autoSopOpen.id = row;
        this.autoSopOpen.isAutoSop = 1;
      } else {
        this.form.autoSopTime.createTime = this.formatDateTo24HourString(new Date());
        updateAutoSopTime({
          id: row,
          isAutoSop: checked,
          autoSopTime: JSON.stringify(this.form.autoSopTime)
        }).then(response => {
          this.getList();
        })
      }


    },
    updateCorpId() {
      this.reset();
      this.refreshData(this.queryParams.corpId);
      this.queryParams.qwUserId = null;
      this.getList();
    },

    //刷新部分数据
    refreshData(row) {
      getQwAllUserList(row).then(response => {
        this.companyUserList = response.data;
      });

      listTag({corpId: row}).then(response => {
        this.tagList = response.rows;
      });

      if (row != null) {
        allList(row).then(e => {
          this.chatList = e.data;
        })
      }
    },

    //查询模板
    selectListSopTemp(type) {
      this.tempListLoading = true; // 开始查询，显示加载提示
      listSopTemp({sendType: type}).then(response => {
        this.tempList = response.rows;
        this.tempListLoading = false;
      });
    },
    handlelistUser(type, sendType) {

      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.queryParams.corpId, type, sendType);
      }, 1);
      this.listUser.title = "选择企业成员"
      this.listUser.open = true;

    },
    selectUserList(list) {
      this.listUser.open = false;
      list.forEach(obj => {
        if (!this.userSelectList.some(item => item == obj.id)) {
          this.userSelectList.push(obj.id);
        }
      });

    },

    //修改过期时间
    handleUpdateOutTime(val) {
      this.outTimeOpen.title = "修改过期时间/评级";
      this.outTimeOpen.id = val.id;
      this.outTimeOpen.tempId = val.tempId;
      this.outTimeOpen.expiryTime = val.expiryTime;
      this.outTimeOpen.isRating = val.isRating;
      this.outTimeOpen.open = true;
    },

    handleUpdateExpiryTime() {
      updateSop({
        id: this.outTimeOpen.id,
        tempId: this.outTimeOpen.tempId,
        expiryTime: this.outTimeOpen.expiryTime,
        isRating: this.outTimeOpen.isRating,
        minConversionDay: this.outTimeOpen.minConversionDay,
        maxConversionDay: this.outTimeOpen.maxConversionDay,
        courseDay: this.outTimeOpen.courseDay
      }).then(response => {
        this.msgSuccess("修改成功");
        this.resetUpdateExpiryTime()
        this.getList();
      });
    },
    resetUpdateExpiryTime() {
      this.outTimeOpen = {
        title: '',
        open: false,
        id: null,
        expiryTime: null,
        courseDay: null,
        minConversionDay: null,
        maxConversionDay: null,
        isRating: null,
      }
    },
    addContent(index) {
      // this.setting[index].content.push({type:1})
      if (this.form.sendType == 2) {
        this.setting[index].content.push({type: 1});
      } else {
        if (this.setting[index].content.length < 9) {
          this.setting[index].content.push({type: 1});
        } else {
          this.$message({
            message: '最多只能添加 9 个内容',
            type: 'warning'
          });
        }
      }

    },

    //选择变动时的变动
    handleSendTypeChange(val) {
      this.tempList = [];
      this.form.tempId = null;
      if (val == 1) {
        // 遍历 this.setting 数组并清空每个对象的 content 属性
        this.setting.forEach(item => {
          if (item.content.length > 9) {
            item.content = item.content.slice(0, 9); // 保留前 9 个元素
          }
        });
      }
    },
    delContent(index, contentIndex) {
      this.setting[index].content.splice(contentIndex, 1)
    },

    //添加SOP规则类型
    handleCommand(command) {
      this.setting.push({
        sopType: command,
        ruleType: null,
        name: null,
        type: 1,
        content: [],
        isBindUrl: 1,
        url: null,
        day: "0",
        hour: "0",
        minute: "0",
        time: ""
      })
    },

    //添加课程SOP
    handleCrouseCommand(command, val) {
      console.log("command", command)
      console.log("val", val)
    },

    delSetting(index) {
      this.setting.splice(index, 1)
    },
    handleClosegroupUser(list) {
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
      }
    },
    /** 查询企微sop列表 */
    getList() {
      this.loading = true;
      listSop(this.queryParams).then(response => {

        this.sopList = response.rows;
        this.total = response.total;
        this.loading = false;


        listSopTemp().then(res => {
          this.tempList = res.rows;
        });

      });
    },

    addSetList(){
      const newSetting = {
        contentType:'1',
        value: '',
      };
      // 将新设置项添加到 content.setting 数组中
      this.setting.push(newSetting);

    },

    handleContentTypeChange() {

      //如果是链接的才上
      if (this.msgForm.courseId != null ) {
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === this.msgForm.courseId);
        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的标题/封面上值
          if (selectedCourse && this.setting[i].contentType == 3 && this.msgForm.courseId != null) {
            this.$set(this.setting[i], 'linkTitle', selectedCourse.dictLabel);
            this.$set(this.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
          }

        }

      }
      if (this.msgForm.videoId != null ) {
        // 查找选中的课节对应的 label
        const selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === this.msgForm.videoId);

        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的描述上值
          if (selectedVideo && this.setting[i].contentType == 3  && this.msgForm.videoId != null) {
            this.$set(this.setting[i], 'linkDescribe', selectedVideo.dictLabel);
          }
        }
      }


    },
    videoIdChange() {
      if (this.msgForm.videoId != null ) {
        // 查找选中的课节对应的 label
        const selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === this.msgForm.videoId);

        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的描述上值
          if (selectedVideo && this.setting[i].contentType == 3  && this.msgForm.videoId != null) {
            this.$set(this.setting[i], 'linkDescribe', selectedVideo.dictLabel);
          }
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // courseChange(){
    //   videoList(this.form.courseId).then(response => {
    //     this.videoList = response.list;
    //   });
    // },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        sendType: 2,
        type: 2,
        filterType: 2,
        qwUserIds: null,
        corpId: null,
        setting: null,
        createBy: null,
        createTime: null,
        isAutoSop: null,
        autoSopTime: {autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2},
      };
      this.resetForm("form");
      this.tags = null;
      this.excludeTags = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId = this.myQwCompanyList[0].dictValue;
      this.refreshData(this.queryParams.corpId);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectionMap = selection;
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push('/qw/sop/addSop/' + this.queryParams.corpId)
      // this.open = true;
      // this.setting=[]
      // this.userSelectList=[]
      // this.title = "添加企微sop";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.$router.push('/qw/sop/updateSop/' + row.id + '/' + type)
    },


    /**
     * 查看SOP任务内营期
     */
    selectSchedule(row) {
      const query = {
        id: row.id,
        name: row.name,
        tempId: row.tempId,
        filterMode: row.filterMode
      }
      // 使用 params 传递参数
      this.$router.push({
        path: `/qw/sopUserLogs/sopUserLogsSchedule/${query.id}`,
        query// 如果需要传递更多参数，可以使用 query
      });
    },


    /**
     * 查看营期内详情
     */
    handleScheduleDetail(row) {
      this.sopLogsDialog.title = '规则执行详情';
      this.sopLogsDialog.open = true;
      this.sopLogsDialog.sopLogsForm = row;
    },

    handleAvatarSuccessFile(res, file, item) {
      if (res.code === 200) {
        // 使用 $set 确保响应式更新
        this.$set(item, 'fileUrl', res.url);
      } else {
        this.msgError(res.msg);
      }
    },
    beforeAvatarUploadFile(file){
      const isLt1M = file.size / 1024 / 1024 < 10;
      if (!isLt1M) {
        this.$message.error('上传大小不能超过 10MB!');
      }
      return isLt1M;
    },
    //下载文件
    downloadUrl(materialUrl) {
      // 直接返回文件 URL
      return materialUrl;
    },

    handleAvatarSuccessVideo(res, file, item) {
      if(res.code==200){
        // 使用 $set 确保响应式更新
        this.$set(item, 'videoUrl', res.url);
      }
      else{
        this.msgError(res.msg);
      }
    },

    beforeAvatarUploadVideo(file){
      const isLt30M = file.size / 1024 / 1024 < 10;
      const isMP4 = file.type === 'video/mp4';

      if (!isMP4) {
        this.$message.error('仅支持上传 MP4 格式的视频文件!');
        return false;
      }

      if (!isLt30M) {
        this.$message.error('上传大小不能超过 10MB!');
        return false;
      }

      return true;
    },

    handleInputVideoText(value,content){
      // 允许的字符：中文、英文（大小写）、数字和指定标点符号（，。！？）
      const regex = /^[\u4e00-\u9fa5，。！？,!?]+$/;

      // 删除不符合条件的字符
      const filteredValue = value.split('').filter(char => regex.test(char)).join('');

      this.$set(content, 'value', filteredValue);

    },
    /**
     * 查看模板
     */
    handleQueryDetails(row) {
      this.$router.push(`/qw/sopTemp/updateSopTemp/${row.tempId}/3`)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.userSelectList.length <= 0) {
            return this.$message("请选择员工")
          }
          this.form.qwUserIds = this.userSelectList.join(",");
          this.form.corpId = this.queryParams.corpId;
          if (this.tags != null && this.tags.length > 0) {
            this.form.tags = (this.tags).toString()
          } else {
            return this.$message.error("选择的标签不能为空！！请选择筛选的标签")
          }
          if (this.excludeTags != null) {
            this.form.excludeTags = (this.excludeTags).toString()
          }

          this.form.setting = JSON.stringify(this.setting)
          if (this.form.id != null) {
            updateSop(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSop(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    submitAutoSopTimeFrom() {
      this.$refs["autoSopTimeFrom"].validate(valid => {
        if (valid) {
          this.autoSopOpen.open = false
          this.form.autoSopTime.createTime = this.formatDateTo24HourString(new Date());
          updateAutoSopTime({
            id: this.autoSopOpen.id,
            isAutoSop: this.autoSopOpen.isAutoSop,
            autoSopTime: JSON.stringify(this.form.autoSopTime)
          }).then(response => {
            this.msgSuccess("修改成功");
          });
        }
        this.getList();
        this.reset();
      });
    },

    formatDateTo24HourString(date) {
      let year = date.getFullYear();
      let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份需要加 1 并补零
      let day = ('0' + date.getDate()).slice(-2); // 日需要补零
      let hours = ('0' + date.getHours()).slice(-2); // 小时需要补零
      let minutes = ('0' + date.getMinutes()).slice(-2); // 分钟需要补零
      let seconds = ('0' + date.getSeconds()).slice(-2); // 秒需要补零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    cancelAutoSopTime() {
      this.autoSopOpen.open = false
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除企微sop编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSop(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /**
     * 批量执行SOP任务
     */
    handleExecute() {

      const ids = this.selectionMap
        .filter(item => item.status === 1)
        .map(item => item.id);

      if (ids.length === 0) {
        this.msgError("选择的任务已经执行或正在执行，请选择待执行的任务");
        return;
      }

      this.$confirm('是否确认立即执行sop编号为"' + ids + '"的数据项?', "警告【只能立即执行（待执行的）】", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        // 执行更新操作
        return updateStatus(ids); // 返回一个Promise，直接在此链式调用
      }).then(res => {
        let msg = "";

        // 判断成功和失败的任务，并显示消息
        if (res.suc.length > 0) {
          msg += "执行成功的SOP任务【" + res.suc.join(", ") + "】。<br>"; // 优化：将数组转换为字符串
        }
        if (res.err.length > 0) {
          msg += "失败的SOP任务【" + res.err.join(", ") + "】，原因是已经执行或正在执行。<br>";
        }

        // 显示确认框，显示成功与失败信息
        return this.$confirm(msg, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true // 允许HTML标签
        });

      }).then(() => {
        // 操作完成后刷新列表，并显示成功信息
        this.getList();
        this.msgSuccess("执行完成");
      }).catch(() => {
        // 处理任何异常，操作取消或者失败时显示提示信息
        this.msgError("操作失败，请重试");
      }).finally(() => {
        this.loading = false; // 操作完成后关闭加载状态
      });

    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企微sop数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSop(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /**
     * 一键群发
     */
    handleSendMsg(row){
      this.sendMsgOpen.open = true;
      this.sendMsgOpen.id = row.id;
      this.sendMsgOpen.row = row;
      this.msgForm.chatIds = row.chatId.split(",");
    },
    submitMsgForm(){
      this.$refs["msgForm"].validate(valid => {
        if (valid) {
          this.msgForm.setting=JSON.stringify(this.setting)
          this.msgForm.sopId=this.sendMsgOpen.row.id;
          this.msgForm.filterMode=this.sendMsgOpen.row.filterMode;

          if (this.setting.length <= 0) {
            return this.$message.error("请添加规则")
          }
          if (this.msgForm.courseId===null || this.msgForm.courseId===''){
            return this.$message.error("课程不能为空")
          }

          if (this.msgForm.videoId===null || this.msgForm.videoId===''){
            return this.$message.error("课节不能为空")
          }

          if (this.msgForm.courseType===null || this.msgForm.courseType===''){
            return this.$message.error("消息类型不能为空")
          }

          for (let i = 0; i < this.setting.length; i++) {
            if (this.setting[i].contentType == 1 && (this.setting[i].value == null || this.setting[i].value == "")) {
              return this.$message.error("内容不能为空")
            }
            if (this.setting[i].contentType == 2 && (this.setting[i].imgUrl == null || this.setting[i].imgUrl == "")) {
              return this.$message.error("图片不能为空")
            }
            if (this.setting[i].contentType == 3 && (this.setting[i].linkTitle == null || this.setting[i].linkTitle == "")) {
              return this.$message.error("链接标题不能为空")
            }
            if (this.setting[i].contentType == 3 && (this.setting[i].linkDescribe == null || this.setting[i].linkDescribe == "")) {
              return this.$message.error("链接描述不能为空")
            }
            if (this.setting[i].contentType == 3 && (this.setting[i].linkImageUrl == null || this.setting[i].linkImageUrl == "")) {
              return this.$message.error("链接图片不能为空")
            }
            if (this.setting[i].contentType == 3 && this.setting[i].type == 1 && (this.setting[i].linkUrl == null || this.setting[i].linkUrl == "")) {
              return this.$message.error("链接地址不能为空")
            }
            if (this.setting[i].contentType == 5 && (this.setting[i].fileUrl == null || this.setting[i].fileUrl == "")) {
              return this.$message.error("文件不能为空")
            }
            if (this.setting[i].contentType == 6 && (this.setting[i].videoUrl == null || this.setting[i].videoUrl == "")) {
              return this.$message.error("视频不能为空")
            }
            if (this.setting[i].contentType == 7 && (this.setting[i].value == null || this.setting[i].value == "")) {
              return this.$message.error("语音不能为空")
            }
          }

          this.sendMsgOpen.open = false;

          const loading = this.$loading({
            lock: true,
            text: '正在执行中请稍后~~请不要刷新页面！！',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          sendMsgSop(this.msgForm).then(response => {
            this.msgSuccess("一键群发成功");
            loading.close();
            this.setting=[];
            this.msgForm = {
              videoId:null,
              courseId:null,
              courseType:null,
              setting:null,
              isRegister:2,
              sendType:1,
              filterMode:2,

            }
            this.getList();
          }).finally(()=>{
            loading.close();
          });

        }
      });
    },
    courseChange() {
      if (this.msgForm.courseId != null ) {
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === this.msgForm.courseId);
        for (let i = 0; i < this.setting.length; i++) {
          //响应式直接给链接的标题/封面上值
          if (selectedCourse && this.setting[i].contentType == 3 && this.msgForm.courseId != null) {
            this.$set(this.setting[i], 'linkTitle', selectedCourse.dictLabel);
            this.$set(this.setting[i], 'linkImageUrl', selectedCourse.dictImgUrl);
          }

        }

      }
      videoList(this.msgForm.courseId).then(response => {
        this.videoList=response.list;
      });
    },
    cancelMsgForm(){
      this.sendMsgOpen.open = false;
      this.resetSendMsgSop();
    },
  }
};
</script>
<style scoped>
.custom-input /deep/ .el-input__inner {
  height: 20px;
  padding: 0 4px;
  text-align: center;
  display: block;
}

.custom-input /deep/ .el-input__icon {
  line-height: 20px;
}

.el-button--text {
  cursor: pointer;
}
</style>
