<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
            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="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <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="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属项目" prop="project" v-if="form.sendType != 5">
          <el-select v-model="form.project" placeholder="请选择项目" filterable clearable size="small">
            <el-option
              v-for="dict in projectOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="归属部门" prop="createByDept">
          <treeselect
            style="width: 220px"
            :clearable="false"
            v-model="form.createByDept"
            :options="deptOptions"
            clearable
            :show-count="true"
            placeholder="请选择归属部门"
          />
        </el-form-item>
        <el-form-item label="课程" prop="courseId" v-if="form.sendType == 11 && !form.id">
          <el-select v-model="form.courseId"placeholder="请选择课程" style=" margin-right: 10px;" size="mini" filterable>
            <el-option
              v-for="dict in courseList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="间隔天数" prop="gap">
          <el-input-number v-model="form.gap" :min="1" label="间隔天数"></el-input-number>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="是否开启官方群发" v-if="form.sendType == 11 && (form.id === null || form.id === undefined)">
          <el-radio-group v-model="form.openOfficial">
            <el-radio
              v-for="dict in openOfficialOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否开启@所有人" v-if="form.sendType == 11 && (form.id === null || form.id === undefined)">
          <el-radio-group v-model="form.openIsAtAll">
            <el-radio
              v-for="dict in openIsAtAllOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容" prop="modeContent">
          <el-input v-model="form.modeContent" placeholder="请输入文字内容"  type="textarea" :rows="3"/>
        </el-form-item>
        <el-form-item label="发课时间" prop="time" v-if="form.sendType == 11 && !form.id">
          <el-time-picker
            class="custom-input"
            v-model="form.time"
            value-format="HH:mm"
            format="HH:mm"
            placeholder="时间"
            style="width: 200px;height: 20px;margin-left: 10px;margin-top: 10px">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="每天催课次数" prop="num" v-if="form.sendType == 11 && !form.id">
          <el-input-number v-model="form.num" :min="0" label="每天催课次数" @change="sendNumChange"></el-input-number>
        </el-form-item>
        <el-form-item label="催课时间" v-if="form.sendType == 11 && !form.id && form.num > 0">
          <div v-for="(item, index) in form.timeList" :key="index" style="margin-bottom: 10px;">
            <el-time-picker
              class="custom-input"
              v-model="item.value"
              value-format="HH:mm"
              format="HH:mm"
              :picker-options="{ selectableRange: startTimeRange }"
              placeholder="时间"
              style="width: 150px; height: 20px; margin-left: 10px; margin-top: 10px">
            </el-time-picker>

            <el-input
              v-model="item.desc"
              placeholder="催课内容"
              type="textarea" :rows="2"
              style="width: 500px; margin-left: 10px; margin-top: 10px;">
            </el-input>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</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="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
} 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";
export default {
  name: "SopTemp",
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      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: [],
      openIsAtAllOptions: [],
      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;
    });

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

    this.getCompanyList();

    getCompanyList().then(response => {
      this.companys = response.data;
    });
  },
  methods: {

    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",
        openIsAtAll: "1",
        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{
      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{
      let url = `/qw/sopTemp/updateSopTemp/${row.id}/1`;
      console.info(url)
      this.$router.push(url)
      // }
    },
    /** 修改按钮操作 */
    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.IsAtAll) {
        this.form.IsAtAll = "1"; // 默认值
    }
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      delete this.form.rules
      this.$refs["form"].validate(valid => {
        if (valid) {

          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);
          }

          console.log("f-----------",f)
          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);
      }
    }
  }
};
</script>
