<template>
  <div class="app-container">
    <div style="margin: 30px;"> 添加sop任务</div>
    <div style="margin-top: 10px;margin-left: 50px;margin-right: 100px;margin-bottom: 60px;">

      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称"/>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-radio-group v-model="form.type" @change="clearUser">
            <!--            <el-radio-->
            <!--              :label="1"-->
            <!--            >个微-->
            <!--            </el-radio>-->

            <el-radio
              :label="2"
            >企微
            </el-radio>
          </el-radio-group>
          <Tip title="针对于企业微信平台" />
        </el-form-item>


        <el-form-item label="筛选方式" prop="filterMode">
          <el-radio-group v-model="form.filterMode">
            <el-radio
              :label="1"
            >标签
            </el-radio>
            <el-radio
              :label="2"
            >群聊
            </el-radio>
          </el-radio-group>
          <Tip :title="'标签：根据企微客户的标签筛选客户进入SOP\r\n群聊：选择企微用户所属的群聊，并且只能选择课程模板，课程模板里面第一条规则是发送到群聊，其他规则催课会发送到群里面的个人'" />
        </el-form-item>
        <el-form-item label="小转天数" prop="minConversionDay" v-if="form.filterMode == 1">
          <!--          <el-input class="el-input" type="" v-model="form.minConversionDay" placeholder="请输入" />-->
          <el-input-number v-model="form.minConversionDay" :min="1" :max="100"></el-input-number>
          <Tip title="第一次提醒销售，去联系客户，在【催课看板】处显示，哪些需要联系的客户" />
        </el-form-item>
        <el-form-item label="大转天数" prop="maxConversionDay" v-if="form.filterMode == 1">
          <!--          <el-input class="el-input" v-model="form.maxConversionDay" placeholder="请输入" />-->
          <el-input-number v-model="form.maxConversionDay" :min="1" :max="100"></el-input-number>
          <Tip title="第二次提醒销售，去联系客户，在【催课看板】处显示，哪些需要联系的客户" />
        </el-form-item>
        <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%" v-if="form.filterMode == 2">
          <div>
            <el-button
              size="medium"
              icon="el-icon-circle-plus-outline"
              plain
              @click="handlelistUser(form.type,form.sendType, true)">请选择使用员工
            </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 companyQwUserList" :key="list.qwUserId"
                    v-if="list.id==id">{{ list.qwUserName }}</span>
            </el-tag>
          </div>
          <Tip title="企业微信员工账号" />
        </el-form-item>
        <el-form-item label="群聊" prop="chatIds" v-if="form.filterMode == 2">
          <el-select multiple filterable clearable v-model="form.chatIds">
            <el-option v-for="item in qwGroupList" :key="item.chatId" :label="item.name" :value="item.chatId"/>
          </el-select>
          <Tip title="选择的企业微信员工下面的群聊" />
        </el-form-item>
        <el-form-item label="客户评级" prop="isRating" style="margin-top: 2%">
          <el-switch
            v-model="form.isRating"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2">
          </el-switch>
          <span v-if="form.isRating == '1'" style="margin-left: 10px;color: #13ce66">已开启</span>
          <span v-if="form.isRating == '2'" style="margin-left: 10px;color: #ff4949">已关闭</span>
          <Tip title="根据客户的【看课记录】进行评级，新进客户前4天不评级，第5天开始 根据客户近7天的看课记录进行评级 ABCD级" />
        </el-form-item>
        <div v-if="form.type==2 && form.filterMode == 1">
          <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>
            <Tip title="选择模板类型" />
          </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, false)">请选择使用员工
              </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 companyQwUserList" :key="list.qwUserId"
                      v-if="list.id==id">{{ list.qwUserName }}</span>
              </el-tag>
            </div>
            <Tip title="选择的企业微信员工下面的群聊" />
          </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>
            <Tip :title="'含全部标签：客户要完全一对一匹配上选择标签，ps:多一个少一个都不行 \r\n含任意标签：客户只要有一个标签匹配上即可'" />
          </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>-->
            <div @click="hangleChangeTags()"
                 style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 390px">
              <div style="min-height: 35px; max-height: 200px; overflow-y: auto;">
                <el-tag type="success"
                        closable
                        :disable-transitions="false"
                        v-for="list in this.tagsIdsChangeSelectList"
                        :key="list.tagId"
                        @close="handleCloseTags(list)"
                        style="margin: 3px;"
                >{{ list.name }}
                </el-tag>
              </div>
            </div>
            <Tip title="选择进入SOP任务的标签" />
          </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>-->
            <div @click="hangleChangeOutTags()"
                 style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;width: 390px">
              <div style="min-height: 35px; max-height: 200px; overflow-y: auto;">
                <el-tag type="success"
                        closable
                        :disable-transitions="false"
                        v-for="list in this.outTagsIdsChangeSelectList"
                        :key="list.tagId"
                        @close="handleCloseOutTags(list)"
                        style="margin: 3px;"
                >{{ list.name }}
                </el-tag>
              </div>
            </div><Tip title="选择不想进入SOP的标签" />
          </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>
          <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%">
            <div>
              <el-button
                size="medium"
                icon="el-icon-circle-plus-outline"
                plain
                @click="handleCompanyUser(form.type,form.sendType)">请选择使用员工
              </el-button>
            </div>
            <div>
              <el-tag
                style="margin-left: 5px"
                size="medium"
                :key="userId"
                v-for="userId in userSelectList"
                closable
                :disable-transitions="false"
                @close="handleClosegroupUser(userId)">
                <span v-for="list in companyUserLists " :key="list.userId"
                      v-if="list.userId==userId">{{ list.nickName }}</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 wxUserGroupList"
                :label="dict.groupName"
                :value="dict.groupId">
              </el-option>
            </el-select>

          </el-form-item>
        </div>
        <el-form-item label="是否固定营期" prop="isFixed" v-if="form.type != 3">
          <el-radio-group v-model="form.isFixed">
            <el-radio
              :label="1"
            >是
            </el-radio>
            <el-radio
              :label="0"
            >否
            </el-radio>
          </el-radio-group>
          <Tip title="如果为固定营期，不管什么时候进入SOP的客户，营期时间都为SOP任务开始时间" />
        </el-form-item>

        <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>
          <Tip title="SOP开始发送时间" />
        </el-form-item>
        <el-form-item label="任务过期时间" prop="expiryTime">
          <el-row>
            <el-input-number v-model="form.expiryTime" :min="1" :max="100"></el-input-number>
            （小时）
          </el-row>
          <Tip title="任务生成的代发送消息，如果超过此设置的时间还未发送，自动作废" />
        </el-form-item>
        <el-form-item v-if="(form.sendType==2 || form.sendType==4) && form.type != 3 && form.isFixed == 0" label="自动添加SOP"
                      prop="autoSopTime.autoSopType">
          <el-radio-group v-model="form.autoSopTime.autoSopType">
            <el-radio
              :label="1"
            >当天开始
            </el-radio>
            <el-radio
              :label="2"
            >次日开始
            </el-radio>
          </el-radio-group>
          <Tip :title="'这个选项仅作用于【新客户】进线时或【给客户打标签时】，是进入当日的营期 还是 次日的营期'" />
        </el-form-item>
        <div style="display: flex; align-items: center; flex-wrap: nowrap;">
          <div v-if="form.autoSopTime.autoSopType==1 && form.isFixed == 0" 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"-->
<!--                      label-width="130px">-->
<!--          <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-form-item label="是否只发送注册用户" prop="isRegister" v-if="form.type != 3">
          <el-radio-group v-model="form.isRegister">
            <el-radio
              :label="1"
            >是
            </el-radio>
            <el-radio
              :label="0"
            >否
            </el-radio>
          </el-radio-group>
          <Tip title="是否只发送在平台注册了会员的客户" />
        </el-form-item>

        <el-form-item label="模板" prop="tempId">
          <div @click="selectListSopTemp(form.sendType)"
               style="cursor: pointer; border: 1px solid #e6e6e6; background-color: white; overflow: hidden; flex-grow: 1;">
            <el-tag v-if="form.tempId" type="success" style="margin: 3px;">
              {{ form.tempName }}
            </el-tag>
            <span v-else style="margin: 3px; color: #999;">请点我选择模板</span>
          </div>
          <Tip title="选择想要发送的模板规则" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="float: right;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog :title="listUser.title" :visible.sync="listUser.open" width="700px" append-to-body>
        <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
      </el-dialog>

      <el-dialog :title="companyUser.title" :visible.sync="companyUser.open" width="700px" append-to-body>
        <company-user-list ref="companyUserList" @selectCompanyUserList="selectCompanyUserList"></company-user-list>
      </el-dialog>

      <el-dialog title="选择模板" :visible.sync="tempOpen" append-to-body>
        <sop-temp ref="SopTempComments" @sopTemp="sopTemp"></sop-temp>
      </el-dialog>

      <!--  选择/排除标签   -->
      <el-dialog :title="changeTagDialog.title" :visible.sync="changeTagDialog.open" width="800px" append-to-body>

        <div>搜索标签：
          <el-input v-model="queryTagParams.tagName" placeholder="请输入标签名称" clearable size="small"
                    style="width: 200px;margin-right: 10px"/>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchTags">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="cancelSearchTags">重置</el-button>
        </div>
        <div v-for="item in tagGroupList" :key="item.id">
          <div style="font-size: 20px;margin-top: 20px;margin-bottom: 20px;">
            <span class="name-background">{{ item.name }}</span>
          </div>
          <div class="tag-container">
            <a
              v-for="tagItem in item.tag"
              class="tag-box"
              @click="tagSelection(tagItem)"
              :class="{ 'tag-selected': tagItem.isSelected }"
            >
              {{ tagItem.name }}
            </a>
          </div>
        </div>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryTagParams.pageNum"
          :limit.sync="queryTagParams.pageSize"
          @pagination="cancelSearchTags"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="tagSubmitForm(changeTagDialog.type)">确 定</el-button>
          <el-button @click="tagCancel(changeTagDialog.type)">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addSop, courseList, updateSop } from '@/api/qw/sop'
import { getQwAllUserList, listUser } from '@/api/company/companyUser'
import qwUserList from '@/views/qw/user/qwUserList.vue'
import companyUserList from '@/views/company/companyUser/companyUserList.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 { sopListWxUserGroup } from '@/api/wxUser/wxUserGroup'
import { listAll as chatListAll } from '@/api/qw/groupChat'
import SopTemp from '@/views/qw/sopTemp/sopTemp.vue'
import { allListTagGroup } from '@/api/qw/tagGroup'
import Tip from '@/components/Tip'

export default {
  name: "addSop",
  components: {SopTemp, CustomerGroupDetails, qwUserList, companyUserList, ImageUpload, sopLogsDetails, Tip},
  data() {
    return {
      //模板查询
      myQwCompanyList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      //模板遮罩
      tempOpen: false,
      // 选中数组
      ids: [],
      courseList: [],
      qwGroupList: [],
      // videoList:[],
      tags: null,
      excludeTags: null,
      // 非单个禁用
      single: true,
      setting: [],

      //标签组
      tagGroupList: [],

      tagList: [],

      //标签
      changeTagDialog: {
        title: "",
        open: false,
        type: null,
      },
      //选择的标签
      tagsIdsChangeSelectList: null,
      //排除的标签
      outTagsIdsChangeSelectList: null,
      //添加的标签
      addTagsIdsChangeSelectList: null,
      //标签弹窗选择
      tagChange: {
        open: false,
        index: null,
      },

      queryTagParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        name: null,
        corpId: null,
      },


      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企微sop表格数据
      sopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //企业微信员工列表
      companyQwUserList: [],

      //销售员工列表
      companyUserLists: [],
      // 状态字典
      statusOptions: [],

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

      sopLogsDialog: {
        title: '',
        open: false,
        sopLogsForm: [],
      },
      // 表单参数
      form: {
        status: 1,
        filterMode: 1,
        sendType: 2,
        isFixed: 0,
        isRegister: 0,
        type: 2,
        filterType: 2,
        expiryTime: 4,
        isAutoSop: 1,
        autoSopTime: {autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2},
      },
      userSelectList: [],
      qwUserIds: [],
      //企业微信员工
      listUser: {
        title: "",
        open: false
      },
      //销售员工
      companyUser: {
        title: "",
        open: false
      },
      //个微客户的分组
      wxUserGroupList: [],
      // 表单校验
      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"}],
      }
    };
  },
  created() {

    this.form.corpId = this.$route.params && this.$route.params.corpId;

    this.queryTagParams.corpId = this.$route.params && this.$route.params.corpId;

    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_course_project").then(response => {
      this.projectOptions = response.data;
    });
    listUser().then(res => {
        this.companyUserLists = res.rows;
      }
    );
    this.refreshData(this.form.corpId);

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

    //个微客户的分组
    sopListWxUserGroup().then(response => {
      this.wxUserGroupList = response.rows;
    });
  },
  watch: {
    userSelectList(newList) {
      this.form.qwUserIds = newList.map(item => item.id);
    }
  },
  methods: {

    //刷新部分数据
    refreshData(row) {

      getQwAllUserList(row).then(response => {
        this.companyQwUserList = response.data;
      });

      this.cancelSearchTags();

    },

    handleSearchTags() {

      searchTags(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.total = response.total;
      });

    },
    cancelSearchTags() {
      allListTagGroup(this.queryTagParams).then(response => {
        this.tagGroupList = response.rows;
        this.total = response.total;
      });

      listTag(this.queryTagParams).then(response => {
        this.tagList = response.rows;
      });
    },
    //标签的选择
    tagSelection(row) {
      row.isSelected = !row.isSelected;
      this.$forceUpdate();
    },

    //确定选择标签
    tagSubmitForm(type) {

      if (type == 1) {
        for (let i = 0; i < this.tagGroupList.length; i++) {
          for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
            if (this.tagGroupList[i].tag[x].isSelected === true) {

              if (!this.tagsIdsChangeSelectList) {
                this.tagsIdsChangeSelectList = [];
              }

              // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
              let tagExists = this.tagsIdsChangeSelectList.some(
                tag => tag.id === this.tagGroupList[i].tag[x].id
              );

              // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
              if (!tagExists) {
                this.tagsIdsChangeSelectList.push(this.tagGroupList[i].tag[x]);
              }
            }
          }
        }
        if (!this.tagsIdsChangeSelectList || this.tagsIdsChangeSelectList.length === 0) {
          return this.$message('请选择标签');
        }

      } else if (type == 2) {

        for (let i = 0; i < this.tagGroupList.length; i++) {
          for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
            if (this.tagGroupList[i].tag[x].isSelected === true) {

              if (!this.outTagsIdsChangeSelectList) {
                this.outTagsIdsChangeSelectList = [];
              }

              // 检查当前 tag 是否已经存在于 tagListFormIndex[index] 中
              let tagExists = this.outTagsIdsChangeSelectList.some(
                tag => tag.id === this.tagGroupList[i].tag[x].id
              );

              // 如果 tag 不存在于 tagListFormIndex[index] 中，则新增
              if (!tagExists) {
                this.outTagsIdsChangeSelectList.push(this.tagGroupList[i].tag[x]);
              }
            }
          }
        }
        if (!this.outTagsIdsChangeSelectList || this.outTagsIdsChangeSelectList.length === 0) {
          return this.$message('请选择标签');
        }

      }
      this.changeTagDialog.open = false;
    },

    //取消选择标签
    tagCancel() {
      this.changeTagDialog.open = false;
    },

    //选择标签
    hangleChangeTags() {

      this.changeTagDialog.title = "选择标签"
      this.changeTagDialog.open = true;
      this.changeTagDialog.type = 1;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(
        (this.tagsIdsChangeSelectList || []).map(tagItem => tagItem?.tagId)
      );
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          this.tagGroupList[i].tag[x].isSelected = selectedTagIds.has(this.tagGroupList[i].tag[x].tagId);
        }
      }

    },


    //选择排除标签
    hangleChangeOutTags() {
      this.changeTagDialog.title = "选择排除的标签"
      this.changeTagDialog.open = true;
      this.changeTagDialog.type = 2;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(
        (this.outTagsIdsChangeSelectList || []).map(tagItem => tagItem?.tagId)
      );
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          this.tagGroupList[i].tag[x].isSelected = selectedTagIds.has(this.tagGroupList[i].tag[x].tagId);
        }
      }
    },

    //选择排除标签
    hangleChangeAddTags() {
      this.changeTagDialog.title = "选择排除的标签"
      this.changeTagDialog.open = true;
      this.changeTagDialog.type = 2;

      // 获取 tagListFormIndex 中的所有 tagId，用于快速查找
      const selectedTagIds = new Set(
        (this.outTagsIdsChangeSelectList || []).map(tagItem => tagItem?.tagId)
      );
      for (let i = 0; i < this.tagGroupList.length; i++) {
        for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
          this.tagGroupList[i].tag[x].isSelected = selectedTagIds.has(this.tagGroupList[i].tag[x].tagId);
        }
      }
    },

    //删除一些选择的标签
    handleCloseTags(list) {
      const ls = this.tagsIdsChangeSelectList.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.tagsIdsChangeSelectList.splice(ls, 1);
        this.tagsIdsChangeSelectList = [...this.tagsIdsChangeSelectList];
      }
    },

    //删除一些排除的标签
    handleCloseOutTags(list) {
      const ls = this.outTagsIdsChangeSelectList.findIndex(t => t.tagId === list.tagId);
      if (ls !== -1) {
        this.outTagsIdsChangeSelectList.splice(ls, 1);
        this.outTagsIdsChangeSelectList = [...this.outTagsIdsChangeSelectList];
      }
    },
    //查询模板
    selectListSopTemp(type) {
      if(this.form.filterMode == 2){
        type = 5;
      }
      this.tempOpen = true;
      setTimeout(() => {
        this.$refs.SopTempComments.getList(type, undefined, this.form.type == 3);
      }, 200);

    },
    sopTemp(val) {
      this.form.tempId = val.id
      this.form.tempName = val.name
      this.tempOpen = false;
    },
    //选择企微员工时
    handlelistUser(type, sendType, selectOne) {
      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.form.corpId, type, sendType, selectOne);
      }, 1);

      this.listUser.title = "选择企微员工"
      this.listUser.open = true;

    },
    //切换类别时 ，清除选择的成员
    clearUser() {
      this.userSelectList = [];
      this.tags = null;
    },

    //选择销售员工时
    handleCompanyUser(type, sendType) {

      this.companyUser.title = "选择销售"
      this.companyUser.open = true;

    },
    //企业微信员工
    selectUserList(list) {
      this.listUser.open = false;
      list.forEach(obj => {
        if (!this.userSelectList.some(item => item == obj.id)) {
          this.userSelectList.push(obj.id);
          this.qwUserIds.push(obj.qwUserId);
        }
      });
      this.loadChatList()
    },

    //销售员工
    selectCompanyUserList(list) {

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

    //选择变动时的变动
    handleSendTypeChange(val) {
      this.userSelectList = [];
      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 个元素
          }
        });
      }
    },
    handleClosegroupUser(list) {
      const index = this.userSelectList.findIndex(t => t === list);
      if (index !== -1) {
        this.userSelectList.splice(index, 1);
        this.qwUserIds.splice(index, 1);
        this.loadChatList()
      }
    },
    // 取消按钮
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.replace('/qw/conversion/sop')
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 1,
        filterMode: 1,
        isFixed: 0,
        sendType: 2,
        type: 2,
        filterType: 2,
        expiryTime: 4,
        qwUserIds: null,
        corpId: null,
        setting: null,
        createBy: null,
        createTime: null,
        isRating: null,
        autoSopTime: {autoSopType: 2, autoStartTime: '00:00', autoEndTime: '24:00', autoSopSend: 2},
      };
      this.resetForm("form");
      this.tags = null;
      this.excludeTags = null;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.setting = []
      this.userSelectList = []
      this.title = "添加企微sop";
    },

    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}`;
    },
    loadChatList() {
      chatListAll(this.qwUserIds.join()).then(e => {
        this.qwGroupList = e.data;
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.type == 2 && this.form.filterMode == 2) {
            this.form.sendType = 5;
            if (this.form.chatIds.length <= 0) {
              return this.$message.error("请选择群聊")
            }
            this.form.chatId = this.form.chatIds.join();
          } else {
            if (this.userSelectList.length <= 0) {
              return this.$message.error("请选择员工")
            }


            if (this.tagsIdsChangeSelectList != null && this.tagsIdsChangeSelectList.length > 0) {

              // 确保 this.form.tags 是数组
              if (!this.form.tags) {
                this.form.tags = []; // 如果未定义，初始化
              } else {
                this.form.tags = []; // 清空已有数据
              }

              // 遍历并添加 tagId
              this.tagsIdsChangeSelectList.forEach(tag => {
                if (tag.tagId) { // 确保 tagId 存在
                  this.form.tags.push(tag.tagId);
                }
              });
              this.form.tags = this.form.tags.join(",");
            } else {
              return this.$message.error("选择的标签不能为空！！请选择筛选的标签")
            }
            if (this.outTagsIdsChangeSelectList != null && this.outTagsIdsChangeSelectList.length > 0) {
              // 确保 this.form.tags 是数组
              if (!this.form.excludeTags) {
                this.form.excludeTags = []; // 如果未定义，初始化
              } else {
                this.form.excludeTags = []; // 清空已有数据
              }

              // 遍历并添加 tagId
              this.outTagsIdsChangeSelectList.forEach(tag => {
                if (tag.tagId) { // 确保 tagId 存在
                  this.form.excludeTags.push(tag.tagId);
                }
              });
              this.form.excludeTags = this.form.excludeTags.join(",");
            }

          }
          this.form.qwUserIds = this.userSelectList.join(",");
          this.form.setting = JSON.stringify(this.setting)
          this.form.autoSopTime.createTime = this.formatDateTo24HourString(new Date());

          this.form.autoSopTime = JSON.stringify(this.form.autoSopTime)

          if (this.form.id != null) {
            updateSop(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sop')
              window.location.replace('/qw/conversion/sop')
              this.reset();
            });
          } else {
            addSop(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.$store.dispatch("tagsView/delView", this.$route);
              // this.$router.replace('/qw/conversion/sop')
              window.location.replace('/qw/conversion/sop')
              this.reset();
            });
          }
        }
      });
    },

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

.user-box {
  width: 50px; /* 盒子宽度 */
  height: 30px; /* 盒子高度 */
  padding: 5px 10px; /* 内边距 */
  border: 1px solid #d5d1d1; /* 边框 */
  margin: 3px; /* 外边距 */
  background-color: #f9f9f9; /* 背景颜色 */
  color: #333; /* 文本颜色 */
  font-size: 14px; /* 字体大小 */
  text-align: center; /* 文本居中 */
}

.elFormItemClass {
  margin: 20px 0px

}

.message-stayle {
  display: flex;
  justify-content: normal;
  align-items: center;
  margin-top: 10px;
}

.message-stayle .el-link {
  white-space: normal; /* 允许换行 */
  word-break: break-all; /* 单词中间断行 */
  overflow-wrap: break-word; /* 允许在单词内换行 */
}

.message-stayle span {
  word-break: break-all;
}

.container {
  position: relative; /* 使 phone div 的 absolute 定位基于这个容器 */
  width: 100%;
  height: 100%;
}

.phone {
  position: absolute; /* 定位到容器内 */
  top: 5%;
  left: 50%;
  transform: translateX(-50%);
  width: 100%;
  max-width: 375px;
  height: 100%;
  max-height: 90%;
  border: 8px solid #ccc;
  border-radius: 36px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  overflow: hidden;
}

.phone::before {
  content: '';
  position: absolute;
  top: 0;
  left: 50%;
  width: 60px;
  height: 5px;
  background-color: #ccc;
  border-radius: 10px;
  transform: translateX(-50%);
}

.chat-interface {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.header .back,
.header .menu {
  height: 25px;
  width: 25px;
}

.header .title {
  font-size: 16px;
  margin: auto;
}

.message-area {
  flex: 1;
  background-color: rgb(240, 242, 245);
  padding: 10px;
  overflow-y: auto;
}

.footer {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
}

.footer .voice-button,
.footer .emoji-button,
.footer .add-button {
  width: 25px;
  height: 25px;
  border: none;
  cursor: pointer;
  flex-shrink: 0; /* 不允许缩小 */
}

.footer .emoji-button,
.footer .add-button {
  margin: 0px 5px;
}


.footer .input-box {
  flex: 1;
  border: 1px solid #e0e0e0;
  margin-left: 5px;
}

.text-container {
  max-height: 7.5em; /* 设置最大高度为6行，根据字体大小调整 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  line-height: 1.5em; /* 行高设置，确保每行高度一致 */
}

.el-form-item {
  margin-bottom: 30px;
}

.custom-span {
  display: block; /* 确保元素是块级元素 */
  height: 110px; /* 设置固定高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
  word-wrap: break-word; /* 自动换行 */
  word-break: break-all; /* 在必要时进行换行 */
}

.custom-span-description {
  display: block; /* 确保元素是块级元素 */
  height: 110px; /* 设置固定高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
  word-wrap: break-word; /* 自动换行 */
  word-break: break-all; /* 在必要时进行换行 */
}

.custom-span-title {
  display: block; /* 确保元素是块级元素 */
  height: 45px; /* 设置固定高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
  word-wrap: break-word; /* 自动换行 */
  word-break: break-all; /* 在必要时进行换行 */
}

/* CSS 样式 */
.tag-container {
  display: flex;
  flex-wrap: wrap; /* 超出宽度时自动换行 */
  gap: 8px; /* 设置标签之间的间距 */
}

.name-background {
  display: inline-block;
  background-color: #abece6; /* 背景颜色 */
  padding: 4px 8px; /* 调整内边距，让背景包裹文字 */
  border-radius: 4px; /* 可选：设置圆角 */
}

.tag-box {
  padding: 8px 12px;
  border: 1px solid #989797;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.tag-selected {
  background-color: #00bc98;
  color: #fff;
  border-color: #00bc98;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.text-container {
  max-height: 5em; /* 设置最大高度为6行，根据字体大小调整 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  line-height: 1.5em; /* 行高设置，确保每行高度一致 */
}
</style>
