<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板类型" prop="sendType">
        <el-select v-model="queryParams.sendType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in sysQwSopType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input
          v-model="queryParams.sort"
          placeholder="请输入排序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属销售" prop="createBy">
        <el-select v-model="queryParams.createBy" clearable filterable remote
                   placeholder="请输入关键词" :remote-method="loadCompanyUserOptions"
                   v-select-load-more="loadMoreCompanyUserOptions"
                   :loading="companyUserOptionsLoading"
                   @change="handleCompanyUserChange"
                   @visible-change="handleCompanyUserDropdownVisible">
          <el-option
            v-for="item in companyUserOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          plain-->
        <!--          icon="el-icon-plus"-->
        <!--          size="mini"-->
        <!--          @click="handleAdd"-->
        <!--          v-hasPermi="['qw:sopTemp:add']"-->
        <!--        >新增</el-button>-->

        <el-dropdown
          v-hasPermi="['qw:sopTemp:add']"
          @command="handleCommand"
          trigger="click"
          placement="bottom-start"
        >
          <el-dropdown-menu slot="dropdown" style="width: 120px;">
            <el-dropdown-item
              v-for="option in sysQwSopType"
              :key="option.dictValue"
              :command="option.dictValue"
            >
              <i :class="option.iconClass" style="margin-right: 10px;"></i>
              {{ option.dictLabel }}
            </el-dropdown-item>
          </el-dropdown-menu>
          <span class="el-dropdown-link">
              <el-button type="primary" icon="el-icon-plus" plain size="mini">
                新增模板
              </el-button>
            </span>
        </el-dropdown>
      </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:sopTemp:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['qw:sopTemp:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="sopTempList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模板编号" align="center" prop="id"/>
      <el-table-column label="公司名称" align="center">
        <template slot-scope="scope">
          <el-tag v-for="item in companys" v-if="scope.row.companyId == item.companyId">{{item.companyName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="模板标题" align="center" prop="name"/>
      <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="gap"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="创建人" align="center" prop="createByName"/>
      <el-table-column label="创建部门" align="center" prop="createByDeptName"/>
      <el-table-column label="修改时间" align="center" prop="updateTime"/>
      <el-table-column label="排序" align="center" prop="sort"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-connection"

            @click="copyTemplate(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >复制模板
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="shareTemplate(scope.row)"
            v-hasPermi="['qw:sopTemp:share']"
          >分享模板</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleQueryDetails(scope.row)"
            v-hasPermi="['qw:sopTemp:list']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate2(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >管理规则
          </el-button>
          <el-button
            v-if="scope.row.sendType == 11"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleBatchOfficial(scope.row)"
            v-hasPermi="['qw:sopTemp:edit']"
          >开关官方群发
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateRed(scope.row)"
            v-if="scope.row.sendType == 5"
            v-hasPermi="['qw:sopTemp:edit']"
          >红包设置
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:sopTemp: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"
    />

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      custom-class="sop-temp-dialog"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="sop-temp-form">
        <div class="form-section">
          <div class="form-section__title">基本信息</div>
          <el-row :gutter="28">
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入模板标题" maxlength="50" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in statusOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.sendType != 5">
              <el-form-item label="所属项目" prop="project">
                <el-select v-model="form.project" placeholder="请选择项目" filterable clearable class="w-full">
                  <el-option
                    v-for="dict in projectOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属部门" prop="createByDept">
                <treeselect
                  class="dept-treeselect"
                  :clearable="false"
                  v-model="form.createByDept"
                  :options="deptOptions"
                  :show-count="true"
                  placeholder="请选择归属部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.sendType == 11 && !form.id">
              <el-form-item label="课程" prop="courseId">
                <el-select v-model="form.courseId" placeholder="请选择课程" filterable class="w-full">
                  <el-option
                    v-for="dict in courseList"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="parseInt(dict.dictValue)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="间隔天数" prop="gap">
                <el-input-number v-model="form.gap" :min="1" controls-position="right" class="num-input" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :min="0" controls-position="right" class="num-input" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div
          class="form-section"
          v-if="form.sendType == 11 && (form.id === null || form.id === undefined)"
        >
          <div class="form-section__title">
            发送能力
            <span class="form-section__hint">按需选择看课通道，可多选叠加</span>
          </div>
          <div class="capability-grid">
            <div class="capability-item">
              <div class="capability-item__meta">
                <span class="capability-item__name">官方群发</span>
                <span class="capability-item__desc">首条走企微官方群发</span>
              </div>
              <el-switch v-model="form.openOfficial" active-value="1" inactive-value="0" />
            </div>
            <div class="capability-item">
              <div class="capability-item__meta">
                <span class="capability-item__name">小程序看课</span>
                <span class="capability-item__desc">生成小程序卡片内容</span>
              </div>
              <el-switch v-model="form.openMiniprogram" active-value="1" inactive-value="0" />
            </div>
            <div class="capability-item" v-if="showAppCourseToggle">
              <div class="capability-item__meta">
                <span class="capability-item__name">APP 看课</span>
                <span class="capability-item__desc">与官方群发二选一</span>
              </div>
              <el-switch v-model="form.openAppCourse" active-value="1" inactive-value="0" />
            </div>
            <div class="capability-item">
              <div class="capability-item__meta">
                <span class="capability-item__name">飞书看课</span>
                <span class="capability-item__desc">叠加飞书链接内容</span>
              </div>
              <el-switch v-model="form.openFeishu" active-value="1" inactive-value="0" />
            </div>
            <div class="capability-item" v-if="projectFrom === 'sxjz'">
              <div class="capability-item__meta">
                <span class="capability-item__name">SIP 外呼</span>
                <span class="capability-item__desc">叠加外呼催课任务</span>
              </div>
              <el-switch v-model="form.openSipCall" active-value="1" inactive-value="0" />
            </div>
            <div class="capability-item">
              <div class="capability-item__meta">
                <span class="capability-item__name">@所有人</span>
                <span class="capability-item__desc">群消息是否 @所有人</span>
              </div>
              <el-switch v-model="form.openIsAtAll" active-value="1" inactive-value="0" />
            </div>
          </div>
          <el-row :gutter="28" v-if="form.openFeishu == '1'" class="sip-task-row">
            <el-col :span="12">
              <el-form-item label="飞书类型" required>
                <el-select
                  v-model="form.feishuContentType"
                  placeholder="请选择飞书类型"
                  clearable
                  class="w-full"
                >
                  <el-option label="飞书1" value="28" />
                  <el-option label="飞书2" value="29" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="消息类型" required>
                <el-select
                  v-model="form.courseType"
                  placeholder="请选择消息类型"
                  clearable
                  class="w-full"
                >
                  <el-option
                    v-for="dict in sysFsSopWatchStatus"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="Number(dict.dictValue)"
                  />
                </el-select>
                <div class="form-section__hint" style="margin-top: 4px;">首条规则固定为普通消息，第2条及以后使用该类型</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="28" v-if="projectFrom === 'sxjz' && form.openSipCall == '1'" class="sip-task-row">
            <el-col :span="12">
              <el-form-item label="外呼任务" required>
                <el-select
                  v-model="form.aiCustomerRoleId"
                  placeholder="请选择 SIP 外呼任务"
                  filterable
                  clearable
                  class="w-full"
                  @visible-change="onSipSelectVisible"
                >
                  <el-option
                    v-for="task in aiSipCallTaskList"
                    :key="task.batchId"
                    :label="task.batchName"
                    :value="task.batchId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section form-section--content">
          <div class="form-section__title">内容与时间</div>
          <el-form-item label="文案内容" prop="modeContent">
            <el-input
              v-model="form.modeContent"
              type="textarea"
              :rows="4"
              placeholder="发课时附带的文字内容"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
          <el-row :gutter="28" v-if="form.sendType == 11 && !form.id">
            <el-col :span="12">
              <el-form-item label="发课时间" prop="time">
                <el-time-picker
                  v-model="form.time"
                  value-format="HH:mm"
                  format="HH:mm"
                  placeholder="选择时间"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="催课次数" prop="num">
                <el-input-number
                  v-model="form.num"
                  :min="0"
                  class="num-input"
                  @change="sendNumChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div v-if="form.sendType == 11 && !form.id && form.num > 0" class="remind-list">
            <div class="remind-list__label">催课安排</div>
            <div class="remind-grid">
              <div
                v-for="(item, index) in form.timeList"
                :key="index"
                class="remind-row"
              >
                <span class="remind-row__index">第 {{ index + 1 }} 次</span>
                <el-time-picker
                  v-model="item.value"
                  value-format="HH:mm"
                  format="HH:mm"
                  :picker-options="{ selectableRange: startTimeRange }"
                  placeholder="催课时间"
                  class="remind-row__time"
                />
                <el-input
                  v-model="item.desc"
                  type="textarea"
                  :rows="2"
                  placeholder="催课文案"
                  class="remind-row__desc"
                />
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="cancel">取 消</el-button>
        <el-button type="primary" size="medium" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="课程红包" :visible.sync="redData.open" width="900px" append-to-body>
      <el-table v-loading="redData.loading" border :data="redData.list" height="500px">
        <el-table-column label="小节" align="left" prop="videoName"/>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.redPacketMoney" :min="0.01" step="0.01" label="红包金额"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
        <el-button type="primary" @click="updateRedData" :disabled="redData.loading">保 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量编辑官方群发" :visible.sync="official.open" width="500px" append-to-body>
       <el-form :model="officialForm" ref="officialForm" :inline="true">
         <el-form-item  label="官方群发" prop="isOfficial">
            <el-radio-group v-model="officialForm.isOfficial">
              <el-radio :label="0">关</el-radio>
              <el-radio :label="1">开</el-radio>
            </el-radio-group>
         </el-form-item>
       </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
        <el-button type="primary" @click="updateOfficial" :loading="official.loading">保 存</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="shareOptions.title" :visible.sync="shareOptions.open" width="800px" append-to-body>

      <el-form :model="queryCompanyParams" ref="queryCompanyForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input
            style="width: 220px"
            v-model="queryCompanyParams.companyName"
            placeholder="请输入企业名称"
            clearable
            size="small"
            @keyup.enter.native="handleCompanyQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select style="width: 220px" v-model="queryCompanyParams.status" placeholder="请选择状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleCompanyQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetCompanyQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            plain
            type="primary"
            icon="el-icon-connection"
            size="mini"
            :disabled="multiple"
            @click="handleShareTemplate"
            v-hasPermi="['qw:sopTemp:share']"
          >分享模板</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="companysloading" border :data="companyList" @selection-change="handleSelectionCompany">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="公司编号" align="center" prop="companyId" />
                <el-table-column label="企业名" align="center" prop="companyName" />
        <!--        <el-table-column label="备注" align="center" prop="remark"/>-->
        <el-table-column label="状态" align="center" prop="status" >
          <template slot-scope="scope">
            <el-tag prop="status" v-for="(item, index) in statusOptions"  :type="scope.row.status==1?'success':'danger'"  v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="companyTotal>0"
        :total="companyTotal"
        :page.sync="queryCompanyParams.pageNum"
        :limit.sync="queryCompanyParams.pageSize"
        @pagination="getCompanyList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  addTemp,
  copyTemplate,
  delSopTemp,
  exportSopTemp,
  getSopTemp,
  listSopTemp,
  getSelectableRange,
  redList,
  shareSopTemp,
  updateRedPackage,
  updateTemp,
  batchOpenOrCloseOfficial,
  getConfigByKey
} from "@/api/qw/sopTemp";
import { getCompanyList, listCompany } from '@/api/company/company'
import {courseList, getRoles} from "@/api/qw/sop";
import {treeselect} from "../../../api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getCompanyUserListLikeName} from "../../../api/company/companyUser";
import { listAiSipCallTask } from "@/api/aiSipCall/aiSipCallTask";
export default {
  name: "SopTemp",
  components: {Treeselect},
  data() {
    return {
       projectFrom:process.env.VUE_APP_PROJECT_FROM,
       aiSipCallTaskList: [],

      officialForm:{
        tempId:null,
        isOfficial:null,
      },
      official:{
        open:false,
        loading:false,
      },
      // 遮罩层
      loading: true,
      companysloading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      courseList: [],
      roles: [],
      //选中的公司
      companys: [],
      deptOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      companyTotal: 0,
      total: 0,
      sendType: 0,
      // sop模板表格数据
      sopTempList: [],
      sysQwSopType: [],
      companyList: [],
      projectOptions: [],
      startTimeRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      command: 0,
      // 状态字典
      statusOptions: [],
      openOfficialOptions: [],
      // 控制“是否开启app看课”是否显示
      showAppCourseToggle: false,
      openIsAtAllOptions: [],
      sysFsSopWatchStatus: [],
      shareOptions: {
        title: '分享模板',
        open: false,
        templateId: null,
      },
      redData: {
        open: false,
        loading: true,
        list: [],
      },
      queryCompanyParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        status: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        setting: null,
        status: '1',
        sort: null,
        companyId: null,
        createBy: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: '名称不能为空', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '状态不能为空', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '排序不能为空', trigger: 'blur'}
        ],
        gap: [
          {required: true, message: '间隔天数不能为空', trigger: 'blur'}
        ],
        time:[{
          required: true, message: '发课时间不能为空', trigger: 'blur'
        }],
        courseId:[{
          required: true, message: '课程不能为空', trigger: 'blur'
        }],
        companyId:[{
          required: true, message: '销售公司不能为空', trigger: 'blur'
        }],
        project:[{
          required: true, message: '所属项目不能为空', trigger: 'blur'
        }],
        createByDept:[
          { required: true, message: '归属部门不能为空', trigger: 'blur' }
        ]
      },
      contentRules: {
        time: [{required: true, message: '时间不能为空', trigger: 'blur'}],
      },
      // 员工选项列表
      companyUserOptionsParams: {
        name: undefined,
        hasNextPage: false,
        pageNum: 1,
        pageSize: 10
      },
      companyUserOptionsByAll: [],
      companyUserOptions: [],
      companyUserOptionsLoading: false,
      companyUserFirstLoad: true, // 首次加载标志
      companyUserDropdownVisible: false, // 下拉框显示状态
    };
  },
  created() {
    this.getList();

    this.getDeptTreeSelect();

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

    this.getDicts("sys_company_or").then(response => {
      this.openOfficialOptions = response.data;
    });

    this.getDicts("sys_company_or").then(response => {
      this.openIsAtAllOptions = response.data;
    });

    getSelectableRange().then(e => {
      this.startTimeRange = e.data;
    })
    this.getDicts("sys_course_project").then(response => {
      this.projectOptions = response.data;
    });

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

    this.getDicts("sys_fs_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data || [];
    });

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

    this.getCompanyList();

    getCompanyList().then(response => {
      this.companys = response.data;
    });
    //获取 app 看课配置
    this.getOpenAppCourseStatus();
  },
  watch: {
    //监听 openOfficial 和 openAppCourse 的变化，实现选项互斥
    'form.openOfficial'(newVal) {
      if (this.showAppCourseToggle && newVal === '1') {
        this.$set(this.form, 'openAppCourse', '0');
      }
    },
    'form.openAppCourse'(newVal) {
      if (this.showAppCourseToggle && newVal === '1') {
        this.$set(this.form, 'openOfficial', '0');
      }
    },
    'form.openSipCall'(newVal) {
      if (newVal !== '1') {
        this.$set(this.form, 'aiCustomerRoleId', null);
      } else {
        this.loadSipTemplates();
      }
    },
    'form.openFeishu'(newVal) {
      if (newVal !== '1') {
        this.$set(this.form, 'courseType', null);
        this.$set(this.form, 'feishuContentType', null);
      }
    }
  },
  methods: {
    onSipSelectVisible(visible) {
      if (visible) {
        this.loadSipTemplates();
      }
    },
    loadSipTemplates() {
      if (this.aiSipCallTaskList.length > 0) {
        return;
      }
      listAiSipCallTask({ taskType: 1, status: 0, pageNum: 1, pageSize: 100 }).then(response => {
        this.aiSipCallTaskList = response.rows || response.data || [];
      }).catch(() => {
        this.$message.error('加载SIP外呼任务失败');
      });
    },

    handleCompanyUserChange(value) {
      // 当清空选择时，将空字符串转为 null
      this.queryParams.createBy = value === '' ? null : value;

    },

    /**
     * 处理所属销售下拉框显示状态变化
     */
    handleCompanyUserDropdownVisible(visible) {
      this.companyUserDropdownVisible = visible;
      if (visible && this.companyUserFirstLoad) {
        // 首次展开下拉框时加载数据
        this.companyUserFirstLoad = false;
        this.loadCompanyUserOptions('');
      } else if (visible && this.companyUserOptions.length === 0) {
        // 下拉框显示但无数据时重新加载
        this.loadCompanyUserOptions('');
      }
    },

    /**
     * 加载更多员工选项
     */
    loadMoreCompanyUserOptions() {
      if (!this.companyUserOptionsParams.hasNextPage) {
        return;
      }

      this.companyUserOptionsParams.pageNum += 1
      this.getCompanyUserListLikeName()
    },

    /**
     * 根据名称模糊查询用户列表
     * @param query 参数
     */
    loadCompanyUserOptions(query) {
      this.companyUserOptions = [];
      if (query === '') {
        return;
      }

      this.companyUserOptionsParams.pageNum = 1
      this.companyUserOptionsParams.name = query
      this.companyUserOptionsLoading = true;
      this.getCompanyUserListLikeName()
    },

    /**
     * 获取员工列表
     */
    getCompanyUserListLikeName(isAll) {

      if (isAll){
        this.companyUserOptionsParams.pageSize = 200;
        getCompanyUserListLikeName(this.companyUserOptionsParams).then(response => {
          this.companyUserOptionsByAll = [...this.companyUserOptions, ...response.data.list]
          this.companyUserOptionsParams.hasNextPage = response.data.hasNextPage
          this.companyUserOptionsLoading = false;
        });
      }else {
        this.companyUserOptionsParams.pageSize = 10;
        getCompanyUserListLikeName(this.companyUserOptionsParams).then(response => {
          this.companyUserOptions = [...this.companyUserOptions, ...response.data.list]
          this.companyUserOptionsParams.hasNextPage = response.data.hasNextPage
          this.companyUserOptionsLoading = false;
        });
      }

    },
    handleCompanyQuery() {
      this.queryCompanyParams.pageNum = 1;
    },
    resetCompanyQuery() {
      this.resetForm("queryCompanyForm");
      this.handleCompanyQuery();
    },

    getDeptTreeSelect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    /** 查询企业列表 */
    getCompanyList() {
      this.companysloading = true;
      listCompany(this.queryCompanyParams).then(response => {
        this.companyList = response.rows;
        this.companyTotal = response.total;
        this.companysloading = false;
      });
    },
    /** 查询sop模板列表 */
    getList() {
      this.loading = true;
      listSopTemp(this.queryParams).then(response => {
        this.sopTempList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gap: 1,
        sendType: this.sendType,
        sort: 0,
        openOfficial: "1",
        openMiniprogram: "0",
        openAppCourse: "0", //默认 app 看课为关
        openSipCall: "0",
        openFeishu: "0",
        feishuContentType: null,
        courseType: null,
        aiCustomerRoleId: null,
        openIsAtAll: "0",
        time: "",
        num: 1,
        timeList: [{value: "",desc:""}],
        status: "1",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleCommand(command) {
      // if (command==4) {
      //   this.$router.push('/qw/sopTemp/addAiChatTemp')
      // }else{
      this.sendType = command;
      this.title = "新增";
      this.reset();
      this.open = true;
      // this.$router.push('/qw/sopTemp/addTemp/'+command)
      // }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //销售公司多选
    handleSelectionCompany(selection) {
      this.companys = selection.map(item => item.companyId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.$router.push('/qw/sopTemp/addSopTemp')
    // },
    /**
     * 查看详情
     */
    handleQueryDetails(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/3`)
      // }else{
        if (this.projectFrom ==='sxjz'){
            this.$router.push(`/qw/sopTemp/updateSopTempSXJZ/${row.id}/3`)
        }else {
            this.$router.push(`/qw/sopTemp/updateSopTemp/${row.id}/3`)
        }

      // }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/1`)
      // }else{
      this.getInfo(row.id, 1);
      // this.$router.push(`/qw/sopTemp/updateTemp/${row.id}/1`)
      // }

    },
    /** 修改按钮操作 */
    handleUpdate2(row) {
      // if (row.sendType==4) {
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/1`)
      // }else{
        if (this.projectFrom ==='sxjz'){
            let url = `/qw/sopTemp/updateSopTempSXJZ/${row.id}/1`;
            this.$router.push(url)
        }else {
            let url = `/qw/sopTemp/updateSopTemp/${row.id}/1`;
            this.$router.push(url)
        }

      // }
    },
    /**
     * 批量编辑官方群发
     */
    handleBatchOfficial(row){
        this.officialForm={
           tempId:null,
           isOfficial:null
        }
        this.officialForm.tempId = row.id;
        this.official.open = true;
    },
    /** 修改按钮操作 */
    handleUpdateRed(row) {
      this.redData.open = true;
      redList(row.id).then(e => {
        this.redData.loading = false;
        this.redData.list = e.data;
      })
    },
    /** 修改按钮操作 */
    updateRedData() {
      this.redData.loading = true;
      updateRedPackage({list: this.redData.list}).then(e => {
        this.redData.open = false;
        this.getList();
      }).catch(() => {
        this.redData.loading = false;
      });
    },

    /** 分享模板 */
    shareTemplate(row) {
      this.shareOptions.open = true;
      this.shareOptions.templateId = row.id;
    },
    /**
     * 复制模板
     */
    copyTemplate(row) {
      // if(row.sendType==4){
      //   this.$router.push(`/qw/sopTemp/updateAiChatTemp/${row.id}/2`)
      // }else{
      this.getInfo(row.id, 2);
      // this.$router.push(`/qw/sopTemp/updateSopTemp/${row.id}/2`)
      // }
    },
    getInfo(id, command) {
      getSopTemp(id).then(response => {
        this.command = command;
        if (command == 2) {
          this.title = "复制";
        }
        if (command == 1) {
          this.title = "修改";
        }
        this.form = response.data;
        if(!!this.form && !!this.form.project){
          this.form.project = String(this.form.project);
        }
        if (!this.form.IsAtAll) {
        this.form.IsAtAll = "1"; // 默认值
    }
        if (this.showAppCourseToggle && this.form.sendType === 11) {
          // 如果两个都是 "1"，强制修正（理论上不会发生）
          if (this.form.openOfficial === '1' && this.form.openAppCourse === '1') {
            this.form.openAppCourse = '0';
          }
        }
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      delete this.form.rules
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 【新增校验】当 view_course_app=1 时，openOfficial 和 openAppCourse 必须二选一
          if (this.showAppCourseToggle && this.form.sendType === 11 && !this.form.id) {
            const official = this.form.openOfficial;
            const appCourse = this.form.openAppCourse;

            // 至少一个为 "1"
            if (official !== '1' && appCourse !== '1') {
              this.$message.error("请至少开启【官方群发】或【APP看课】中的一项！");
              return;
            }

            // 不能同时为 "1"（虽然 watch 已处理，但以防绕过）
            if (official === '1' && appCourse === '1') {
              this.$message.error("【官方群发】与【APP看课】不能同时开启，请选择其一！");
              return;
            }
          }
          if (this.form.sendType === 11 && !this.form.id) {
            if (this.form.openMiniprogram !== '1' && this.form.openAppCourse !== '1' && this.form.openFeishu !== '1') {
              this.$message.error("请至少开启【小程序看课】【APP看课】【飞书看课】中的一项！");
              return;
            }
            if (this.form.openFeishu === '1' && !this.form.feishuContentType) {
              this.$message.error("请选择飞书类型");
              return;
            }
            if (this.form.openFeishu === '1' && (this.form.courseType === null || this.form.courseType === undefined || this.form.courseType === '')) {
              this.$message.error("请选择消息类型");
              return;
            }
            if (this.projectFrom === 'sxjz' && this.form.openSipCall === '1' && !this.form.aiCustomerRoleId) {
              this.$message.error("请选择SIP外呼任务！");
              return;
            }
            if (this.projectFrom !== 'sxjz') {
              this.form.openSipCall = '0';
              this.form.aiCustomerRoleId = null;
            }
          }
          if (this.command != 2 && this.form.id == null && this.form.sendType == 11){

            const hasEmptyFields = this.form.timeList.some(item => {
              return !item.value || !item.desc;
            });

            if (hasEmptyFields) {
              this.$message.error("请填写【催课时间】和【催课内容】！");
              return; // 阻止提交
            }

          }

          let f = JSON.parse(JSON.stringify(this.form));
          if (f.timeList && f.timeList.length > 0) {
            f.timeDesc = f.timeList.map(item => item.desc);
            f.timeList = f.timeList.map(item => item.value);
          }

          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (this.command == 2) {
            copyTemplate(f).then(response => {
              this.msgSuccess("复制成功");
              this.open = false;
              loading.close();
              this.getList();
            });
          } else {
            if (f.id != null) {
              updateTemp(f).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                loading.close();
                this.getList();
              });
            } else {
              addTemp(f).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                loading.close();
                this.getList();
              });
            }
          }
        }
      });
    },

    handleShareTemplate() {
      const companyIds = this.companys;
      let templateId = this.shareOptions.templateId;
      this.$confirm("确定将模板分享给 公司编号为：" + companyIds + "的公司？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return shareSopTemp({companyIds: companyIds, templeId: templateId});
      }).then(() => {
        this.companys = [];
        this.shareOptions.open = false;
        this.getList();
        this.msgSuccess("分享成功");
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除当前所选模板?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSopTemp(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有sop模板数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSopTemp(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    sendNumChange(val, old) {
      if (val > old) {
        for (let i = 0; i < val - old; i++) {
          this.form.timeList.push({value: "",desc:""});
        }
      } else {
        let len = old - val;
        this.form.timeList.splice(Math.max(this.form.timeList.length - len, 0), len);
      }
    },
    updateOfficial(){
      if(!!this.officialForm){
        if(this.officialForm.tempId == null || this.officialForm.tempId == '' || this.officialForm.tempId == undefined){
            this.$message.error("参数错误");
            return;
        }
        if(this.officialForm.isOfficial === null || this.officialForm.isOfficial === undefined){
            this.$message.error("请选择官方群发操作结果");
            return;
        }
      }else{
          this.$message.error("参数错误");
      }
      this.official.loading = true;
      batchOpenOrCloseOfficial(this.officialForm).then(res=>{
         this.msgSuccess("保存成功");
      this.official.loading = false;
      this.official.open = false;
      }).catch(res=>{
      this.official.loading = false;
      });
    },
    getOpenAppCourseStatus(){
      getConfigByKey("courseAppConfig.config").then(res => {
        if (res.code === 200 && res.data?.configValue) {
          try {
            const config = JSON.parse(res.data.configValue);
            this.showAppCourseToggle = config.view_course_app === 1;
          } catch (e) {
            console.error("解析 courseAppConfig.config 失败", e);
            this.showAppCourseToggle = false;
          }
        } else {
          this.showAppCourseToggle = false;
        }
      }).catch(() => {
        this.showAppCourseToggle = false;
      });
    },
  }
};
</script>

<style scoped>
.sop-temp-form {
  max-height: 72vh;
  overflow-y: auto;
  padding-right: 6px;
}

.form-section {
  margin-bottom: 24px;
  padding: 28px 32px 16px;
  background: #fafbfc;
  border: 1px solid #ebeef5;
  border-radius: 12px;
}

.form-section:last-child {
  margin-bottom: 4px;
}

.form-section__title {
  display: flex;
  align-items: baseline;
  gap: 14px;
  margin: 0 0 24px;
  padding-left: 12px;
  border-left: 4px solid #409eff;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
  line-height: 1.3;
  letter-spacing: 0.02em;
}

.form-section__hint {
  font-size: 13px;
  font-weight: 400;
  color: #909399;
}

.w-full {
  width: 100%;
}

.num-input {
  width: 100%;
}

.num-input >>> .el-input__inner {
  text-align: left;
}

.dept-treeselect {
  width: 100%;
  line-height: 40px;
}

.capability-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 4px;
}

.capability-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  min-height: 88px;
  padding: 20px 18px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 10px;
}

.capability-item__meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 0;
}

.capability-item__name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.capability-item__desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.45;
}

.sip-task-row {
  margin-top: 18px;
}

.remind-list {
  margin: 4px 0 8px 100px;
}

.remind-list__label {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.remind-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 14px;
}

.remind-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 14px 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 10px;
}

.remind-row__index {
  flex: 0 0 58px;
  margin-top: 8px;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
}

.remind-row__time {
  flex: 0 0 130px;
}

.remind-row__desc {
  flex: 1;
  min-width: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

<style>
.sop-temp-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.sop-temp-dialog .el-dialog__header {
  padding: 24px 32px 18px;
  border-bottom: 1px solid #ebeef5;
}

.sop-temp-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
  letter-spacing: 0.02em;
}

.sop-temp-dialog .el-dialog__body {
  padding: 28px 32px 18px;
}

.sop-temp-dialog .el-dialog__footer {
  padding: 18px 32px 24px;
  border-top: 1px solid #ebeef5;
}

.sop-temp-dialog .el-form-item {
  margin-bottom: 22px;
}

.sop-temp-dialog .el-input__inner,
.sop-temp-dialog .el-textarea__inner {
  border-radius: 6px;
}

.sop-temp-dialog .el-button--medium {
  min-width: 104px;
  padding: 11px 24px;
}
</style>
