<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="企微公司" prop="corpId">
          <el-select v-model="queryParams.corpId" placeholder="企微公司"  size="small" @change="updateCorpId()">
            <el-option
              v-for="dict in myQwCompanyList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="使用的成员" >
        <el-select v-model="queryParams.qwUserIds" filterable  clearable placeholder="公司员工"   size="small">
          <el-option
             v-for="dict in companyUserList"
             :key="dict.id"
             :label="dict.qwUserName"
             :value="dict.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启分时段" prop="isDayparting">
        <el-select v-model="queryParams.isDayparting" placeholder="请选择" clearable size="small">
          <el-option v-for="dict in allowSelectOptions" :key="dict.dictValue" :label="dict.dictLabel"  :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTieme">
        <el-date-picker clearable size="small"
          v-model="queryParams.updateTieme"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否发送欢迎语" prop="isSendMsg">
        <el-select v-model="queryParams.isSendMsg" placeholder="请选择" clearable size="small" >
          <el-option v-for="dict in allowSelectOptions" :key="dict.dictValue" :label="dict.dictLabel"  :value="dict.dictValue"/>
        </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-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['qw:friendWelcome:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table v-loading="loading" :data="friendWelcomeList" @selection-change="handleSelectionChange" border>
      <el-table-column label="消息内容" align="left" prop="welcomeText"  width="400px" >
        <template slot-scope="scope">
          <span style="color:rgb(19, 154, 50);" v-if="scope.row.isDayparting==='1'">[共 {{JSON.parse(scope.row.daypartingItemlist).length+1}} 时段]</span>
          <span style="color:rgb(19, 154, 50);" v-else >[默认时段]</span>
          <el-tooltip class="item" effect="dark" :content="scope.row.welcomeText" placement="top">
            <div style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; text-overflow: ellipsis;">
              <span>{{ scope.row.welcomeText }}</span>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="使用成员" align="center" prop="qwUserIds">
      <template slot-scope="scope">
          <div v-for="id in JSON.parse(scope.row.qwUserIds)" :key="id" style="display: inline;" class="text-container">
            <el-tag type="success" v-for="list in companyUserList" :key="list.qwUserId" style="margin: 3px;" v-if="list.id==id">{{list.qwUserName}}</el-tag>
          </div>
      </template>
      </el-table-column>
      <el-table-column label="是否开启分时段" align="center" prop="isDayparting">
        <template slot-scope="scope">
          <dict-tag :options="allowSelectOptions" :value="scope.row.isDayparting"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否发送欢迎语" align="center" prop="isSendMsg" >
        <template slot-scope="scope">
          <dict-tag :options="allowSelectOptions" :value="scope.row.isSendMsg"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qw:friendWelcome:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qw:friendWelcome: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" v-loading="loading" width="1700px" append-to-body>
      <div style="width: 1130px" class="app-container">
        <div>
          <span style="font-size: 15px">基础信息</span>
          <el-divider></el-divider>
          <el-alert
            title="注意事项"
            type="warning"
            description="这是提示~根据特色还不知道写点啥"
            :closable="false"
            show-icon>
          </el-alert>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">

          <el-form-item label="选择使用成员：" prop="qwUserIds" style="margin-top: 2%">
            <div>
              <el-button
                size="medium"
                icon="el-icon-circle-plus-outline"
                plain
                @click="handlelistUser">请选择使用成员</el-button>
            </div>
            <div>
              <el-tag
                style="margin-left: 5px"
                size="medium"
                :key="list.id"
                v-for="list in userSelectList"
                closable
                :disable-transitions="false"
                @close="handleClosegroupUser(list)">
                {{list.qwUserName}}({{list.nickName}})
              </el-tag>
            </div>
          </el-form-item>
          <el-form-item label="是否发送欢迎语">
            <el-switch
              v-model="form.isSendMsg"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="2">
            </el-switch>
            <span v-if="form.isSendMsg == '1'" style="margin-left: 10px;color: #13ce66">允许</span>
            <span v-if="form.isSendMsg == '2'" style="margin-left: 10px;color: #ff4949">不允许</span>

          </el-form-item>
          <div>
            <span style="font-size: 15px">发送欢迎语</span>
            <el-divider></el-divider>
          </div>
          <el-form-item label="默认欢迎语：" prop="welcomeText">
              <el-input v-model="form.welcomeText" type="textarea"  :rows="12" maxlength="1300" show-word-limit placeholder="请输入消息内容"/>
            <!-- 附件和链接列表 -->
            <el-row>
              <el-col>
                <div v-for="(item, index) in form.attachments" :key="index" style="background-color: #f5f7fa;padding: 5px;border: 1px solid  #d9d9d9;">
                  <div slot="header" style="display: flex;justify-content: space-between;align-items: center; ">
                    <div style="flex: 1;">
                    <span v-if="item.msgtype === 'image'">【图片】: {{ item.image.pic_url }}</span>
                    <span v-if="item.msgtype === 'video'">【视频】: {{ item.video.url }}</span>
                    <span v-if="item.msgtype === 'link'">【链接】: {{ item.link.title }}-{{item.link.desc}}</span>
                    <span v-if="item.msgtype === 'miniprogram'">【小程序】: {{ item.miniprogram.title }}</span>
                    </div>
                    <div style="  display: flex;gap: 10px;">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        style="float: left;"
                        @click="editFileItem(item,index,-1)"
                      >修改</el-button>
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        style="float: right;"
                        @click="removeFileItem(item,index,-1)"
                      >删除</el-button>
                  </div>
                  </div>
                </div>
              </el-col>
            </el-row>

            <el-dropdown @command="(command) => handleCommand(command, -1)" trigger="click" placement="top-start">
              <el-dropdown-menu slot="dropdown" style="width: 120px;">
                <el-dropdown-item command="image">
                  <i class="el-icon-picture" style="margin-right: 10px;"></i>图片
                </el-dropdown-item>
                <el-dropdown-item command="video">
                  <i class="el-icon-video-camera" style="margin-right: 10px;"></i>视频
                </el-dropdown-item>
                <el-dropdown-item command="link">
                  <i class="el-icon-link" style="margin-right: 10px;"></i>链接
                </el-dropdown-item>
                <el-dropdown-item command="miniprogram">
                  <i class="el-icon-link" style="margin-right: 10px;"></i>小程序
                </el-dropdown-item>
              </el-dropdown-menu>

              <span class="el-dropdown-link">
                <el-link icon="el-icon-paperclip" type="text" style="color: rgb(24, 144, 255)">
                  添加附件(最多9个)
                </el-link>
              </span>
            </el-dropdown>

            </el-form-item>

          <el-form-item label="分时段欢迎语">
            <el-switch
              v-model="form.isDayparting"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="2">
            </el-switch>
            <span v-if="form.isDayparting == '1'" style="margin-left: 10px;color: #13ce66">已启用</span>
            <span v-if="form.isDayparting == '2'" style="margin-left: 10px;color: #ff4949">已禁用</span>
          </el-form-item>

          <el-form-item v-if="form.isDayparting == '1'" >
            <div style="background-color:#ecf8fe;width: 100%;border: 1px solid #dcdfe6">
              <span style="margin-left:20px;font-size: 15px;display: block" >注意：1、员工上下班不同时间段可设置不同欢迎语;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >2、分时段之外的时间将发送已允许的默认欢迎语。</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >3、不设置分时段欢迎语则使用已允许的默认欢迎语</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >4、若员工没有设置过欢迎语则不会发送</span>
            </div>
          </el-form-item>
          <el-form-item v-if="form.isDayparting == '2'">
            <div style="background-color:#ecf8fe;width: 100%;border: 1px solid #dcdfe6">
              <span style="margin-left:20px;font-size: 15px;display: block" >注意：1、新建欢迎语最多可发送1条文字消息和9个附件;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >2、文字消息和附件不能同时为空，当两者均填写时用户会收到多条消息;</span>
              <span style="margin-left:65px;font-size: 15px;display: block" >3、欢迎语将在客户加为好友后20秒内下发，因网络延迟可能造成发送不成功</span>
            </div>
          </el-form-item>
          <div  v-if="form.isDayparting == '1'"  v-for="(item, index) in form.daypartingItemlist"    :key="index" >
            <el-form-item :label="`时段 ${index + 1}：`">
                <el-row>
                  <el-col style="width: 965px">
                    <div style="background-color: #fbfbfb;padding: 10px;  border: 1px solid #e6e6e6; margin-bottom: 20px;">
                          <el-form ref="friendWelcomeItemForm"  :rules="itemRules" :model="item">
                          <div style="display: flex; gap: 10px;">
                            <el-form-item label="发起时间:" prop="week" style="flex: 8;">
                              <el-select v-model="item.week" remote multiple placeholder="请选择" filterable style="width: 580px">
                                <el-option
                                  v-for="dict in weekOptions"
                                  :key="dict.value"
                                  :label="dict.label"
                                  :value="dict.value">
                                </el-option>
                              </el-select>
                            </el-form-item>
                            <el-form-item prop="startTime" style="flex: 1;">
                              <el-time-select style="width: 120px;"
                                              placeholder="起始时间"
                                              v-model="item.startTime"
                                              :picker-options="{
                                            start: '00:00',
                                            step: '00:15',
                                            end: '24:00'
                                          }">
                              </el-time-select>
                            </el-form-item>
                            <el-form-item prop="endTime" style="flex: 1;">
                              <el-time-select style="width: 120px;"
                                              placeholder="结束时间"
                                              v-model="item.endTime"
                                              :picker-options="{
                                            start: '00:00',
                                            step: '00:15',
                                            end: '24:00',
                                            minTime: item.startTime
                                          }">
                              </el-time-select>
                            </el-form-item>
                          </div>

                        <el-form-item style="margin-top: 20px" prop="welcomeText">
                          <el-input v-model="item.welcomeText" type="textarea" :rows="12" maxlength="1300" show-word-limit placeholder="请输入消息内容"/>
                          <!-- 附件和链接列表 -->
                          <el-row>
                            <el-col>
                              <div v-for="(attachment, attachIndex) in item.attachments" :key="attachIndex" style="background-color: #f5f7fa;padding: 5px;border: 1px solid  #d9d9d9;">
                                <div slot="header" style="  display: flex;justify-content: space-between;align-items: center; ">
                                  <div style="flex: 1;">
                                    <span v-if="attachment.msgtype === 'image'">【图片】: {{ attachment.image.pic_url }}</span>
                                    <span v-if="attachment.msgtype === 'video'">【视频】: {{ attachment.video.url }}</span>
                                    <span v-if="attachment.msgtype === 'link'">【链接】: {{ attachment.link.title }}-{{attachment.link.desc}}</span>
                                    <span v-if="attachment.msgtype === 'miniprogram'">【小程序】: {{ attachment.miniprogram.title }}</span>
                                  </div>
                                  <div style="  display: flex;gap: 10px;">
                                    <el-button
                                      size="mini"
                                      type="text"
                                      icon="el-icon-edit"
                                      style="float: left;"
                                      @click="editFileItem(attachment,attachIndex,index)"
                                    >修改</el-button>
                                    <el-button
                                      size="mini"
                                      type="text"
                                      icon="el-icon-delete"
                                      style="float: right;"
                                      @click="removeFileItem(attachment,attachIndex,index)"
                                    >删除</el-button>
                                  </div>
                                </div>
                              </div>
                            </el-col>
                          </el-row>

                          <el-dropdown @command="(command) => handleCommand(command, index)" trigger="click" placement="top-start">
                            <el-dropdown-menu slot="dropdown" style="width: 120px;">
                              <el-dropdown-item command="image">
                                <i class="el-icon-picture" style="margin-right: 10px;"></i>图片
                              </el-dropdown-item>
                              <el-dropdown-item command="video">
                                <i class="el-icon-video-camera" style="margin-right: 10px;"></i>视频
                              </el-dropdown-item>
                              <el-dropdown-item command="link">
                                <i class="el-icon-link" style="margin-right: 10px;"></i>链接
                              </el-dropdown-item>
<!--                              <el-dropdown-item command="miniprogram">-->
<!--                                <i class="el-icon-link" style="margin-right: 10px;"></i>小程序-->
<!--                              </el-dropdown-item>-->
                            </el-dropdown-menu>

                            <span class="el-dropdown-link">
                            <el-link icon="el-icon-paperclip" type="text" style="color: rgb(24, 144, 255)">
                              添加附件(最多9个)
                            </el-link>
                            </span>
                          </el-dropdown>
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-col>
                  <el-col style="width: 15px;">
                    <el-link v-if="form.daypartingItemlist.length>1" icon="el-icon-delete-solid" @click="delItemList(index)" type="text" style="color: rgb(24, 144, 255);margin-top: 350px" ></el-link>
                  </el-col>
                </el-row>
            </el-form-item>
          </div>
          <div  v-if="form.isDayparting == '1'" style="margin-left: 10%">
            <el-link type="primary" class="el-icon-plus" :underline="false" @click='addItemList()'>添加其他分时段欢迎语</el-link>
          </div>

        </el-form>
      </div>

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

    <!-- 选择成员账号弹窗   -->
    <el-dialog :title="listUser.title" :visible.sync="listUser.open" style="width: 1600px;height: 100%" append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    <el-dialog :title="welcomeItem.title" :visible.sync="welcomeItem.open" style="width: 1300px;height: 100%" append-to-body>
      <el-form ref="fileFrom" :model="fileFrom" :rules="fuleRules" label-width="110px">
        <div v-if="welcomeItem.type==='image'">
          <el-form-item label="图片：" prop="imagePicUrl">
            <ImageUpload v-model="fileFrom.imagePicUrl"  type="image" :num="10" :width="150" :height="150"  disabled/>
          </el-form-item>
        </div>
        <div v-if="welcomeItem.type==='video'">
          <el-form-item label="视频：" prop="videoUrl">

            <el-upload
              v-model="fileFrom.videoUrl"
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="(res, file) => handleAvatarSuccessVideo(res, file, fileFrom)"
              :before-upload="beforeAvatarUploadVideo">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            {{fileFrom.videoUrl}}
            <video v-if="fileFrom.videoUrl"
                   :src="fileFrom.videoUrl"
                   controls style="width: 200px;height: 100px">
            </video>
          </el-form-item>
        </div>
        <div v-if="welcomeItem.type==='link'">

          <el-form-item label="选择课程">
            <el-select  v-model="fileFrom.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChange(fileFrom,welcomeItem.index,welcomeItem.itemIndex)">
              <el-option
                v-for="dict in courseList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
            <el-select  v-model="fileFrom.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange(fileFrom, welcomeItem.index, welcomeItem.itemIndex,welcomeItem.type)" >
              <el-option
                v-for="dict in videoList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="图文标题：" prop="linkTitle">
            <el-input v-model="fileFrom.linkTitle" :rows="2" maxlength="42"  show-word-limit placeholder="请输入图文消息标题，最长为42字" />
          </el-form-item>
          <el-form-item label="图文封面：" prop="linkPicUrl">
            <ImageUpload v-model="fileFrom.linkPicUrl"  type="image" :num="10" :width="150" :height="150" />
          </el-form-item>
          <el-form-item label="图文的描述：" prop="linkDesc">
            <el-input v-model="fileFrom.linkDesc" :rows="4" maxlength="170" show-word-limit type="textarea" placeholder="请输入内容,，最长为170字" />
          </el-form-item>
          <div v-if="fileFrom.videoId==null" style="margin-top: 1%">
            <el-form-item label="图文链接:"  label-width="100px" >
              <el-input v-model="fileFrom.linkUrl" placeholder="请输入链接地址" style="width: 90%;"/>
            </el-form-item>
          </div>
          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="图文链接:"  label-width="100px" >
              <el-tag type="warning" v-model="fileFrom.linkUrl='待生成'">选择的课程小节 即为卡片链接地址</el-tag>
            </el-form-item>
          </div>
          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="课节过期时间" style="margin-top: 1%" required label-width="110px">
              <el-row>
                <el-input-number  v-model="fileFrom.expiresDays"  :min="1" :max="9999" ></el-input-number>
                （天）
              </el-row>
              <el-row>
                <span class="tip">默认为30天</span>
              </el-row>
            </el-form-item>
          </div>
<!--          <el-form-item label="图文链接：" prop="linkUrl">-->
<!--            <el-input v-model="fileFrom.linkUrl" :rows="2"  placeholder="选择了课程小节会自动设置地址" />-->
<!--          </el-form-item>-->
        </div>
        <div v-if="welcomeItem.type==='miniprogram'">

          <el-form-item label="选择课程">
            <el-select  v-model="fileFrom.courseId" placeholder="请选择课程" style=" margin-right: 10px;" size="mini"  @change="courseChange(fileFrom,welcomeItem.index,welcomeItem.itemIndex)">
              <el-option
                v-for="dict in courseList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
            <el-select  v-model="fileFrom.videoId" placeholder="请选择小节" size="mini" style=" margin-right: 10px;" @change="videoIdChange(fileFrom, welcomeItem.index, welcomeItem.itemIndex,welcomeItem.type)" >
              <el-option
                v-for="dict in videoList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="小程序标题：" prop="miniprogramTitle">
            <el-input v-model="fileFrom.miniprogramTitle" :rows="2" maxlength="64" placeholder="请输入小程序消息标题，最长为64字节" @input="checkByteLength(fileFrom)" />
          </el-form-item>
          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="小程序链接:"  label-width="100px" >
              <el-tag type="warning" v-model="fileFrom.miniprogramPage='待生成'">选择的课程小节 即为卡片小程序链接地址</el-tag>
            </el-form-item>
          </div>
          <el-form-item label="appid" prop="miniprogramAppid" v-show="false" >
            <el-input v-model="fileFrom.miniprogramAppid='wx73f85f8d62769119' " disabled />
          </el-form-item>

          <div v-if="fileFrom.videoId!=null">
            <el-form-item label="课节过期时间" style="margin-top: 1%" required label-width="110px">
              <el-row>
                <el-input-number  v-model="fileFrom.expiresDays"  :min="1" :max="9999" ></el-input-number>
                （天）
              </el-row>
              <el-row>
                <span class="tip">默认为30天</span>
              </el-row>
            </el-form-item>
          </div>
          <!--          <el-form-item label="图文链接：" prop="linkUrl">-->
          <!--            <el-input v-model="fileFrom.linkUrl" :rows="2"  placeholder="选择了课程小节会自动设置地址" />-->
          <!--          </el-form-item>-->
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="confirmUpload">确定</el-button>
        <el-button type="primary" @click="cancelUpload">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listFriendWelcome, getFriendWelcome, delFriendWelcome, addFriendWelcome, updateFriendWelcome, exportFriendWelcome } from "@/api/qw/friendWelcome";
import qwUserList from '@/views/qw/user/qwUserList.vue'
import ImageUploadWeclome from '@/views/qw/friendWelcome/ImageUploadWeclome.vue'
import ImageUpload from '@/views/qw/material/ImageUpload.vue'
import { getQwAllUserList } from '@/api/company/companyUser'
import { getMyQwUserList,getMyQwCompanyList } from "@/api/qw/user";
import {courseList, videoList} from "@/api/qw/sop";
export default {
  name: "FriendWelcome",
  components: { ImageUpload, qwUserList,ImageUploadWeclome},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      myQwCompanyList:[],
      //选择成员列表
      listUser:{
        title:"",
        open:false
      },
      //选择成员列表
      userSelectList:[],
      fileFrom:{
        imagePicUrl:null,
        linkTitle:null,
        linkPicUrl:null,
        linkDesc:null,
        linkUrl:null,
        videoId:null,
        courseId:null,
        expiresDays:30,
        miniprogramTitle:null,
        miniprogramPage:null,
        miniprogramPicUrl:null,
        miniprogramAppid:null,
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadOSS2",
      courseList:[],
      videoList:[],
      fuleRules:{
        imagePicUrl:[ { required: true, message: "图片不能为空", trigger: "submit" }],
        linkTitle:[ { required: true, message: "图文标题不能为空", trigger: "submit" }],
        linkUrl:[ { required: true, message: "图文链接不能为空", trigger: "submit" }],
        miniprogramTitle:[ { required: true, message: "图文链接不能为空", trigger: "submit" }],
      },


      weekOptions: [{
        value: 1,
        label: '星期一'
      }, {
        value: 2,
        label: '星期二'
      }, {
        value: 3,
        label: '星期三'
      }, {
        value: 4,
        label: '星期四'
      }, {
        value: 5,
        label: '星期五'
      }
        , {
          value: 6,
          label: '星期六'
        }
        , {
          value: 7,
          label: '星期天'
        }],

      welcomeItem:{
        open: false,
        title: '',
        type: '',
        index: -1,
        itemIndex: -1
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否
      allowSelectOptions:[],
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 好友欢迎语表格数据
      friendWelcomeList: [],
      //账号列表
      companyUserList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qwUserIds: [],
        companyId: null,
        welcomeText: null,
        isDayparting: null,
        createTime: null,
        updateTime: null,
        isSendMsg: null,
        corpId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        qwUserIds: [
          { required: true, message: "发送企业群发消息的成员账号不能为空", trigger: "submit" }
        ],
        welcomeText:[
          { required: true, message: "消息内容不能为空噢", trigger: "submit" }
        ],

      },
      itemRules: {
        week: [
          { required: true, message: '请选择发起时间的星期', trigger: 'submit' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'submit' },
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'submit' },

        ],
        welcomeText: [
          { required: true, message: '消息内容不能为空噢', trigger: 'submit' }
        ]
      }

    };
  },
  created() {
    //账号列表


    //是否允许发送
    this.getDicts("sys_qw_allow_select").then(response => {
      this.allowSelectOptions = response.data;
    });
    courseList().then(response => {
      this.courseList = response.list;
    });
    getMyQwCompanyList().then(response => {

            this.myQwCompanyList = response.data;
            if(this.myQwCompanyList!=null){
              this.queryParams.corpId=this.myQwCompanyList[0].dictValue
              getQwAllUserList(this.myQwCompanyList[0].dictValue).then(response => {
                this.companyUserList = response.data;
              });
              this.getList();
            }
    });
  },
  watch:{
    userSelectList(newList) {
      this.form.qwUserIds =newList.map(item =>item.id);
    }
  },
  methods: {
    updateCorpId(){
        this.getList();
        getQwAllUserList(this.queryParams.corpId).then(response => {
        this.companyUserList = response.data;
      });
     },
    /** 查询好友欢迎语列表 */
    getList() {
      this.loading = true;

      listFriendWelcome(this.queryParams).then(response => {

        // 将处理后的数据赋值给 friendWelcomeList
        this.friendWelcomeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // // 检查字节长度
    checkByteLength(fileFrom) {
      const text = fileFrom.miniprogramTitle;
      const byteLength = this.getByteLength(text); // 获取当前字节数

      // 如果字节数超过64，截断输入内容
      if (byteLength > 64) {
        this.$set(fileFrom, 'miniprogramTitle', this.truncateTextByByteLength(text,64));
      }
    },

    // 计算字符串的字节数
    getByteLength(text) {
      return new Blob([text]).size; // 使用 Blob 计算字节数
    },

    // 根据字节数截断字符串
    truncateTextByByteLength(text, maxByteLength) {
      let byteLength = 0;
      let result = "";

      for (let i = 0; i < text.length; i++) {
        const char = text[i];
        const charByteLength = this.getByteLength(char); // 获取当前字符的字节数

        // 如果加上当前字符的字节数后不超过限制，则添加到结果中
        if (byteLength + charByteLength <= maxByteLength) {
          result += char;
          byteLength += charByteLength;
        } else {
          break; // 超过限制时停止
        }
      }

      return result;
    },

    //选择群发的企业成员账号
    handlelistUser(){
      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.queryParams.corpId);
      }, 1);
      this.listUser.title="选择企业成员"
      this.listUser.open=true;
    },
    //选择的成员账号列表
    selectUserList(list){

      this.listUser.open=false;

      // 3. 遍历要添加的 list，逐条判断是否存在重复
      list.forEach(newItem => {
        // some() 判断是否存在相同 id
        const isExist = this.userSelectList.some(oldItem => oldItem.id === newItem.id);
        if (!isExist) {
          // 不存在重复的，才添加
          this.userSelectList.push(newItem);
        }
      });
      // //用于显示
      // this.userSelectList=list;

    },
    //删除一些选择了的账号
    handleClosegroupUser(list){

      // 假设 list 对象具有一个 id 属性
      const index = this.userSelectList.findIndex(t => t.id === list.id);
      if (index !== -1) {
        this.userSelectList.splice(index,1);
      }
    },
    //附件选择
    handleCommand(command,itemIndex){

      if (this.form.attachments.length >=9 && itemIndex===-1) {
        return this.$message.error('附件数量已达上限，无法添加更多附件');
      }

      if (this.isDayparting==='1' && this.form.daypartingItemlist[itemIndex].attachments.length>=9){
        return this.$message.error('附件数量已达上限，无法添加更多附件');
      }

      this.welcomeItem = {
        open: true,
        title: this.getTitleByCommand(command),
        type: command,
        index: itemIndex === -1 ? this.form.attachments.length : this.form.daypartingItemlist[itemIndex].attachments.length,
        itemIndex
      };
    },

    getTitleByCommand(command) {
      switch (command) {
        case 'image':
          return '添加图片';
        case 'link':
          return '添加链接';
        case 'miniprogram':
          return '添加小程序';
      }
    },


    courseChange(fileFrom,index,itemIndex){

      // 清空 videoId 选择
      this.$set(fileFrom, 'videoId', null);
      // 清空 videoList
      this.videoList = [];

      if (fileFrom.courseId != null) {
        // 查找选中的课程对应的 label 和 dictImgUrl
        const selectedCourse = this.courseList.find(course => parseInt(course.dictValue) === fileFrom.courseId);

        if (selectedCourse) {
          // 设置 linkTitle 和 linkImageUrl
          this.$set(fileFrom, 'linkTitle', selectedCourse.dictLabel);
          this.$set(fileFrom, 'linkPicUrl', selectedCourse.dictImgUrl);
        }


        // 获取新的 videoList
        videoList(fileFrom.courseId).then(response => {
          this.videoList = response.list;
        });

      }
      //
      // // 更新对应的数据层级
      // if (itemIndex === -1) {
      //   // 更新 form.attachments
      //   this.$set(this.form.attachments, index, {
      //     ...this.form.attachments[index],
      //     courseId: fileFrom.courseId,
      //     videoId: null, // 因为已清空
      //     title: fileFrom.linkTitle,
      //     picurl: fileFrom.linkPicUrl
      //   });
      // } else {
      //
      //   this.$set(this.form.daypartingItemlist[itemIndex].attachments, index, {
      //     ...this.form.daypartingItemlist[itemIndex].attachments[index],
      //     courseId: fileFrom.courseId,
      //     videoId: null, // 因为已清空
      //     title: fileFrom.linkTitle,
      //     picurl: fileFrom.linkPicUrl
      //   });
      // }
    },
    videoIdChange(fileFrom,index, itemIndex,type){
      //选择了课程小节则 默认绑上
      if (fileFrom.videoId != null) {
        // 根据 videoId 获取相关信息（假设有相关的 API 调用）
        let  selectedVideo = this.videoList.find(course => parseInt(course.dictValue) === fileFrom.videoId);
        if (selectedVideo && type==='link') {
          this.$set(fileFrom, 'linkDesc', selectedVideo.dictLabel);
          this.$set(fileFrom, 'expiresDays', 30);
        }
        if (selectedVideo && type==='miniprogram') {
          this.$set(fileFrom, 'miniprogramTitle', this.truncateTextByByteLength(selectedVideo.dictLabel,64));
          this.$set(fileFrom, 'expiresDays', 30);
        }

      }

      // // 更新对应的数据层级
      // if (itemIndex === -1) {
      //   // 更新 form.attachments
      //   this.$set(this.form.attachments, index, {
      //     ...this.form.attachments[index],
      //     videoId: fileFrom.videoId,
      //     desc: fileFrom.linkDesc,
      //   });
      // } else {
      //   // 更新 form.daypartingItemlist[itemIndex].attachments
      //   this.$set(this.form.daypartingItemlist[itemIndex].attachments, index, {
      //     ...this.form.daypartingItemlist[itemIndex].attachments[index],
      //     videoId: fileFrom.videoId,
      //     desc: fileFrom.linkDesc,
      //   });
      //
      // }

    },
    //修改附件
    editFileItem(item, index, itemIndex){

      this.welcomeItem = {
        open: true,
        title: this.getEditTitleByMsgType(item.msgtype),
        type: item.msgtype,
        index,
        itemIndex
      };
      if (item.msgtype === 'image') {
        this.fileFrom.imagePicUrl = item.image.pic_url;
      }else if (item.msgtype === 'video') {
        this.fileFrom.videoUrl = item.video.url;
      } else if (item.msgtype === 'link') {
        this.fileFrom.linkTitle = item.link.title;
        this.fileFrom.linkPicUrl = item.link.picurl;
        this.fileFrom.linkDesc = item.link.desc;
        this.fileFrom.linkUrl = item.link.url;
        this.fileFrom.videoId = item.link.videoId;
        this.fileFrom.courseId = item.link.courseId;
        this.fileFrom.expiresDays = item.link.expiresDays;

        videoList(item.link.courseId).then(response => {
          this.videoList = response.list;
        });


      }else if (item.msgtype === 'miniprogram') {
        this.fileFrom.miniprogramAppid = 'wx73f85f8d62769119';
        this.fileFrom.miniprogramTitle = item.miniprogram.title;
        this.fileFrom.miniprogramPicUrl = "待生成";
        this.fileFrom.miniprogramPage = "待生成";
        this.fileFrom.videoId = item.miniprogram.videoId;
        this.fileFrom.courseId = item.miniprogram.courseId;
        this.fileFrom.expiresDays = item.miniprogram.expiresDays;

        videoList(item.miniprogram.courseId).then(response => {
          this.videoList = response.list;
        });

      }


    },



    getEditTitleByMsgType(msgType) {
      switch (msgType) {
        case 'image':
          return '编辑图片';
        case 'link':
          return '编辑链接';
        case 'miniprogram':
          return '编辑小程序';
      }
    },

    //删除附件
    removeFileItem(data,index, itemIndex) {

      if (itemIndex === -1) {
        this.form.attachments.splice(index, 1);
      } else {
        this.form.daypartingItemlist[itemIndex].attachments.splice(index, 1);
      }
    },

    //添加分时段欢迎语
    addItemList(){
      this.form.daypartingItemlist.push({welcomeText:null,attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null})
    },


    //删除某一个分时段欢迎语
    delItemList(index){
      this.form.daypartingItemlist.splice(index,1)
    },

    //提交附件
    confirmUpload(fileFrom) {
      const { type, index, itemIndex } = this.welcomeItem;
      let attachment = {};
      if (type === 'image') {
        attachment = {
          msgtype: 'image',
          image: {
            pic_url: this.fileFrom.imagePicUrl
          }
        };
      } else if (type === 'video') {
        attachment = {
          msgtype: 'video',
          video: {
            url:this.fileFrom.videoUrl,
          }
        };
      } else if (type === 'link') {
        attachment = {
          msgtype: 'link',
          link: {
            title: this.fileFrom.linkTitle,
            picurl: this.fileFrom.linkPicUrl,
            desc: this.fileFrom.linkDesc,
            url: this.fileFrom.linkUrl,
            courseId:this.fileFrom.courseId,
            videoId:this.fileFrom.videoId,
            expiresDays:this.fileFrom.expiresDays,
          }
        };
      }else if (type==='miniprogram'){
        attachment = {
          msgtype: 'miniprogram',
          miniprogram: {
            title: this.fileFrom.miniprogramTitle,
            pic_media_id: "待查询",
            appid: "wx73f85f8d62769119",
            page: this.fileFrom.miniprogramPage,
            courseId:this.fileFrom.courseId,
            videoId:this.fileFrom.videoId,
            expiresDays:this.fileFrom.expiresDays,
          }
        };
      }

      if (itemIndex === -1) {
        // 默认欢迎语附件处理
        if (index < this.form.attachments.length) {
          // 存在附件则更新
          this.form.attachments.splice(index, 1, attachment);
        } else {
          // 不存在附件则插入
          this.form.attachments.push(attachment);
        }

      } else {
        // 分时段欢迎语附件处理
        if (index < this.form.daypartingItemlist[itemIndex].attachments.length) {
          // 存在附件则更新
          this.form.daypartingItemlist[itemIndex].attachments.splice(index, 1, attachment);
        } else {
          // 不存在附件则插入
          this.form.daypartingItemlist[itemIndex].attachments.push(attachment);
        }
      }

      this.resetFileFrom();
    },

    //取消附件
    cancelUpload() {
      this.resetFileFrom();
      this.welcomeItem.open = false;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    //重置附件表单
    resetFileFrom() {
      this.fileFrom = {
        imagePicUrl: null,
        linkTitle: null,
        linkPicUrl: null,
        linkDesc: null,
        linkUrl: null,
        videoId:null,
        courseId:null,
        miniprogramTitle:null,
        miniprogramPage:null,
        miniprogramPicUrl:null,
        miniprogramAppid:null,
      };

      this.welcomeItem={
        open: false,
        title: '',
        type: '',
        index: -1,
        itemIndex: -1
      } // 重置编辑索引

      this.videoList=[];
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        qwUserIds: [],
        companyId: null,
        //默认欢迎语附件
        attachments: [],
        createdTime: null,
        updateTieme: null,
        isSendMsg:'1',
        welcomeText: '',
        isDayparting: '2',
        //分时段欢迎语
        daypartingItemlist:[{welcomeText:null,attachments:[],week:[1,2,3,4,5,6,7],startTime:null,endTime:null}],
      };
      this.userSelectList=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.corpId= this.myQwCompanyList[0].dictValue
      getQwAllUserList(this.queryParams.corpId).then(response => {
        this.companyUserList = response.data;
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建好友欢迎语";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFriendWelcome(id).then(response => {


        let data = response.row;

        // 转换 attachments
        if (typeof data.attachments === 'string') {
          data.attachments = JSON.parse(data.attachments);
        }

        // 转换 daypartingItemlist
        if (typeof data.daypartingItemlist === 'string') {
          data.daypartingItemlist = JSON.parse(data.daypartingItemlist);
        }

        // 转换 daypartingItemlist 中的每个项目的 attachments 和 week
        if (Array.isArray(data.daypartingItemlist)) {
          data.daypartingItemlist = data.daypartingItemlist.map(item => {
            return {
              ...item,
              attachments: typeof item.attachments === 'string' ? JSON.parse(item.attachments) : item.attachments,
              week: typeof item.week === 'string' ? JSON.parse(item.week) : item.week
            };
          });
        }

        // 赋值给表单
        this.form = data;
        this.userSelectList=this.form.userSelectList

        this.open = true;
        this.title = "修改好友欢迎语";
      });
    },
    /** 提交按钮 验证 from表单*/
    submitForm() {

      this.loading=true;

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.corpId=this.queryParams.corpId;
          //有分时段欢迎语 验证分时段表单
          if (this.form.isDayparting==='1'){
            const itemForms = this.$refs.friendWelcomeItemForm;
            if (Array.isArray(itemForms)) {
              let allValid = true;

              itemForms.forEach((itemFormRef, index) => {
                itemFormRef.validate((itemValid) => {
                  if (!itemValid) {
                    this.loading=false;
                    allValid = false;
                  } else {
                    const { startTime, endTime } = itemFormRef.model;
                    if (startTime && endTime && startTime > endTime) {
                      this.$message.error(`时段 ${index + 1} 的开始时间不能大于结束时间`);
                      allValid = false;
                      this.loading=false;

                    }
                  }

                  if (index === itemForms.length - 1 && allValid) {
                    //全表单验证通过
                    this.commitForm();
                  }
                });
              });
            }
          }else {
            //只有默认的
            this.commitForm();

          }

        }
        this.loading = false;
      });
    },

    //提交form表单
    commitForm(){

      // 深拷贝表单数据
      const requestData = { ...this.form };
      // 将 `form.attachments` 转为 JSON 字符串
      requestData.attachments = JSON.stringify(this.form.attachments);
      requestData.qwUserIds = JSON.stringify(this.form.qwUserIds);

      // 遍历 `daypartingItemlist`，将其中的 `attachments` 和 `week` 转为 JSON 字符串
      requestData.daypartingItemlist = JSON.stringify(requestData.daypartingItemlist.map(item => ({
          ...item,
        }))
      );


      if (this.form.id != null) {
        updateFriendWelcome(requestData).then(response => {
          this.msgSuccess("修改成功");
          this.loading=false;
          this.open = false;
          this.getList();
        }).catch(error => {
          this.open=false;
          this.loading = false;
        });
      } else {
        addFriendWelcome(requestData).then(response => {
          this.msgSuccess("新增成功");
          this.loading=false;
          this.open = false;
          this.getList();
        }).catch(error => {
          this.open=false;
          this.loading = false;
        });
      }


      // 重置表单 无论成功还是失败-都重置表单
      this.reset();
    },

    //处理时间
    // formatTime(date) {
    //   const hours = date.getHours().toString().padStart(2, '0');
    //   const minutes = date.getMinutes().toString().padStart(2, '0');
    //   const seconds = date.getSeconds().toString().padStart(2, '0');
    //   return `${hours}:${minutes}:${seconds}`;
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除好友欢迎语编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFriendWelcome(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有好友欢迎语数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportFriendWelcome(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },

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

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

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

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

      return true;
    },
  }
};
</script>

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