<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="企微员工账号" prop="qwUserid" v-if="queryParams.type==2">
        <el-input
          v-model="queryParams.qwUserid"
          placeholder="请输入企微员工账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售昵称" prop="qwUserName" v-if="queryParams.type==1">
        <el-input
          v-model="queryParams.qwUserName"
          placeholder="请输入销售昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="客户昵称" prop="externalUserName">
        <el-input
          v-model="queryParams.externalUserName"
          placeholder="请输入客户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送类型" prop="sendType" label-width="100px" >
        <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="sendStatus">
        <el-select v-model="queryParams.sendStatus" placeholder="请选择发送(成员)状态" clearable size="small">
          <el-option
            v-for="dict in sysQwSopLogsStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预计发送时间" prop="scheduleTime">
<!--        <el-date-picker clearable size="small"-->
<!--          v-model="queryParams.sendTime"-->
<!--          type="datetime"-->
<!--          value-format="yyyy-MM-dd HH:mm:ss"-->
<!--          placeholder="选择预计发送时间">-->
<!--        </el-date-picker>-->
        <el-date-picker
          clearable size="small"
          v-model="scheduleTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          placeholder="选择预计发送时间"
          @change="handleScheduleTimeChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接收(客户)状态" prop="receivingStatus">
        <el-select v-model="queryParams.receivingStatus" placeholder="请选择接收(客户)状态" clearable size="small">
          <el-option
            v-for="dict in groupMsgSendStatusOptions"
            :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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['qw:sopLogs:export']"
        >导出</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qw:sopLogs:remove']"
        >批量删除</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleEditCourse"
          v-hasPermi="['qw:sopLogs:editCourse']"
        >再次发送记录</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qwSopLogsList"  @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" prop="sendType" width="80">
        <template slot-scope="scope">
          <dict-tag :options="sysQwSopType" :value="scope.row.sendType"/>
        </template>
      </el-table-column>
      <el-table-column label="企微成员账号" align="center" prop="qwUserid" />
      <el-table-column label="企微成员昵称" align="center" prop="qwUserName"  v-if="queryParams.type==2" />
<!--      <el-table-column label="系统后台昵称" align="center" prop="userName" />-->
      <el-table-column label="客户昵称" align="center" prop="externalUserName" />
      <el-table-column label="发送的消息" align="center" prop="contentJson" >
        <template slot-scope="scope">
          <el-button type="text" @click="showContentDialog(scope.row.contentJson)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="成员状态" align="center" prop="sendStatus" >
        <template slot-scope="scope">
          <dict-tag :options="sysQwSopLogsStatus" :value="scope.row.sendStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="预计发送时间" align="center" prop="sendTime" width="180"/>
      <el-table-column label="实际发送时间" align="center" prop="realSendTime" width="180"/>
<!--      <el-table-column label="获取记录" align="center" prop="takeRecords" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.takeRecords == 0" :style="{ color: 'red' }" >未获取</span>-->
<!--          <span v-else-if="scope.row.takeRecords == 1" :style="{ color: 'green' }" >已获取</span>-->
<!--          <span v-else :style="{ color: 'gray' }" >未知状态</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="客户" align="center" prop="receivingStatus" >
        <template slot-scope="scope">
          <dict-tag :options="groupMsgSendStatusOptions" :value="scope.row.receivingStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="createTime" prop="createTime" width="180" />
      <el-table-column label="消息ID" align="center" prop="msgId" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <el-dialog :visible.sync="contentDialog.isDialogVisible" title="消息详情" width="30%" append-to-body>
      <div>
        <div v-for="(item, index) in contentDialog.json || []" :key="index">
          <el-card class="box-card" style="margin-top: 2%">
            <div slot="header" class="clearfix" style="display: flex;justify-content: space-between;align-items: center;">
              <div>
                <span>类型：</span>
                <span v-if="item.contentType == 1">文本</span>
                <span v-if="item.contentType == 2">图片</span>
                <span v-if="item.contentType == 3">卡片</span>
                <span v-if="item.contentType == 4">小程序</span>
                <span v-if="item.contentType == 5">文件</span>
                <span v-if="item.contentType == 6">视频</span>
                <span v-if="item.contentType == 7">语音</span>
                <span v-if="item.contentType == 8">视频号</span>
                <span v-if="item.contentType == 9">APP</span>
                <span v-if="item.contentType == 10">自定义小程序</span>
                <span v-if="item.contentType == 4"><el-button size="mini" type="primary" @click="generateShortLink(item)" style="margin-left: 330px;">生成短链</el-button></span>
              </div>
              <div v-if="item.sendStatus">
                <span>发送状态：</span>
                <el-tag type="success" v-if="item.sendStatus == 1">发送成功</el-tag>
                <el-tag type="danger" v-if="item.sendStatus == 2">发送失败</el-tag>
              </div>
            </div>
            <div v-if="item.sendStatus && item.sendStatus == 2">发送失败原因：<span style="color: #ff4949">{{item.sendRemarks}}</span></div>
            <div v-if="item.contentType == 1" v-html="item.value"></div>
            <div v-if="item.contentType == 2">
              <el-image
                style="width: 100px; height: 100px"
                :src="item.imgUrl"
                fit="contain"
                @click.prevent="openImageViewer(item.imgUrl)" />
            </div>
            <div v-if="item.contentType == 3 || item.contentType == 9" class="message-style">
              <div
                style="background-color: white; padding: 10px; width: 100%"
                @click="openLink(item.linkUrl)">
                <span>{{ item.linkTitle }}</span>
                <div style="display: flex; justify-content: space-between; width: 100%">
                  <span style="font-size: 13px; flex: 1">{{ item.linkDescribe }}</span>
                  <!-- 点击图片时停止事件冒泡 -->
                  <el-image
                    style="width: 50px; height: 50px; flex-shrink: 0"
                    :src="item.linkImageUrl"
                    fit="contain"
                    @click.stop="openImageViewer(item.linkImageUrl)" />
                </div>
              </div>
            </div>
            <div v-if="item.contentType == 4 || item.contentType == 10" class="message-style">
                <div style="display: flex; justify-content: space-between; width: 100%">
                  <span style="font-size: 13px; flex: 1">{{ item.miniprogramTitle }}</span>
                  <el-image
                    style="width: 50px; height: 50px; flex-shrink: 0"
                    :src="item.miniprogramPicUrl"
                    fit="contain"
                    @click.stop="openImageViewer(item.miniprogramPicUrl)" />
                </div>
            </div>
            <div v-if="item.contentType == 5" class="message-style">
              <el-link type="primary" :href="item.fileUrl" download style="padding: 10px">
                {{ item.fileUrl }}
              </el-link>
            </div>
            <div v-if="item.contentType == 6" class="message-style">
              <video
                :src="item.videoUrl"
                controls
                style="width: 200px; height: 100px">
              </video>
            </div>
            <div v-if="item.contentType == 7">
              <span>
                {{ item.value }}
              </span>
              <div v-if="!item.voiceUrl" style="margin-top: 3px"  >
                <span style="color: red">无语音地址</span>
              </div>
            </div>

            <div v-if="item.contentType == 8" class="message-style">
              <el-card class="box-card" v-if="item.coverUrl">
                <el-form-item label="封面标题:"  label-width="100px">
                  <el-input v-model="item.nickname" style="width: 90%;margin-bottom: 1%" disabled/>
                </el-form-item>
                <el-form-item label="头像:"   label-width="100px" >
                  <el-image
                    v-if="item.avatar != null"
                    :src="item.avatar"
                    :preview-src-list="[item.avatar]"
                    :style="{ width: '50px', height: '50px' }"
                  ></el-image>
                </el-form-item>
                <el-form-item label="封面:"   label-width="100px" >
                  <el-image
                    v-if="item.coverUrl != null"
                    :src="item.coverUrl"
                    :preview-src-list="[item.coverUrl]"
                    :style="{ width: '200px', height: '200px' }"
                  ></el-image>
                </el-form-item>
                <el-form-item label="简介:"   label-width="100px" >
                  <el-input type="textarea" :rows="3" v-model="item.desc"  style="width: 90%;margin-top: 1%;" disabled />
                </el-form-item>
                <el-form-item label="视频地址:"  label-width="100px" style="margin-top: 1%" >
                  <el-input v-model="item.url" style="width: 90%;" disabled />
                </el-form-item >
              </el-card>
            </div>

          </el-card>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="contentDialog.isDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 大图预览对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :modal="false"
      width="500"
      append-to-body>
      <img
        :src="this.dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

    <el-dialog
      title="生成短链"
      :visible.sync="shortLinkDialogVisible"
      width="30%"
      v-loading="shortLoading"
      append-to-body>
        <el-tooltip placement="top" effect="dark" :content="copyText">
            <span class="ellipsis" style="max-width:100px;display:inline-block;">{{copyText}}</span>
        </el-tooltip>
        <i style="margin-left:120px;cursor: pointer" class="el-icon-document-copy" @click="onCopy"></i>
        <span slot="footer" class="dialog-footer">
        <el-button @click="shortLinkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="shortLinkDialogVisible = false">确 定</el-button>
        </span>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="videoNumOptions.title" :visible.sync="videoNumOptions.open" width="1500px" append-to-body>
      <userVideo ref="QwUserVideo" @videoResult="qwUserVideoResult"></userVideo>
    </el-dialog>
  </div>

</template>

<script>
import {
  listQwSopLogs,
  exportQwSopLogs,
  listQwSopLogsList,
  delQwSopLogs,
  editCourseQwSopLogs,
  generateShortLink
} from '../../../api/qw/sopLogs'
import {delSopUserLogsInfo} from "@/api/qw/sopUserLogsInfo";
import userVideo from "@/views/qw/userVideo/userVideo";

export default {
  name: "sopLogsList",
  props:{
    rowDetailFrom:{userVideo},
  },

  watch:{
    rowDetailFrom:{
      handler(newVal){
        // 当formData变化时重新查询
        this.getList(newVal);
      },
      deep: true
    }
  },
  data() {
    return {
      videoNumOptions: {
        title: '选择视频号',
        open: false,
        content: null,
        contentIndex: null,
      },
      copyText:"",
      shortLoading:false,
      shortLinkDialogVisible:false,
      //图片放大
      dialogVisible: false,
      dialogImageUrl:null,
      //时间选择
      scheduleTime: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业微信SOP  定时任务表格数据
      qwSopLogsList: [],

      //成员状态
      sysQwSopLogsStatus:[],

      //客户接收状态
      groupMsgSendStatusOptions:[],

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

      //发送的消息
      contentDialog:{
        isDialogVisible:false,
        json: [],
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qwUserName: null,
        qwUserid: null,
        externalUserName: null,
        sendStatus: null,
        sendTime: null,
        corpId:null,
        receivingStatus: null,
        sendType: null,
        type:null,
        scheduleEndTime:null,
        scheduleStartTime:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList(this.rowDetailFrom);

    //成员状态
    this.getDicts("sys_qw_sopLogs_status").then(response => {
      this.sysQwSopLogsStatus = response.data;
    });

    //客户接收状态
    this.getDicts("sys_qw_groupMsg_SendStatus").then(response => {
      this.groupMsgSendStatusOptions = response.data;
    });

    //发送消息类型
    this.getDicts("sys_qw_sop_course_type").then(response => {
      this.sysQwSopType = response.data;
    });


  },
  methods: {

    qwUserVideoResult(val) {

      // 根据选中的内容，将返回的数据更新到相应的表单项
      const content = this.videoNumOptions.content;
      const setList = content[this.videoNumOptions.contentIndex];
      setList.nickname = val.nickname;
      setList.avatar = val.avatar;
      setList.coverUrl = val.coverUrl;
      setList.thumbUrl = val.thumbUrl;
      setList.desc = val.desc;
      setList.url = val.url;
      setList.extras = val.extras;
      setList.videoId = val.id;
      console.info(setList)

      this.videoNumOptions.open = false;

    },
    /** 查询企业微信SOP  定时任务列表 */
    getList(val) {
      this.queryParams.sopId = val.id || this.rowDetailFrom.id;
      this.queryParams.corpId= val.corpId || this.rowDetailFrom.corpId;
      this.queryParams.type= val.type || this.rowDetailFrom.type;
      this.queryParams.filterSopType=val.filterSopType || this.rowDetailFrom.filterSopType;
      this.loading = true;

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

        // console.log("response.rows",response.rows)
        this.qwSopLogsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    handleScheduleTimeChange(val) {
      if (val) {
        this.queryParams.scheduleStartTime = this.formatDateTime(val[0]);
        this.queryParams.scheduleEndTime = this.formatDateTime(val[1]);
      } else {
        this.queryParams.scheduleStartTime = null;
        this.queryParams.scheduleEndTime = null;
      }
    },

    // 格式化日期为 yyyy-MM-dd HH:mm:ss 的北京时间
    formatDateTime(date) {
      if (!date) return null;

      // 创建国际化时间格式，指定为 Asia/Shanghai 时区
      const options = {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 24小时制
      };

      // 获取格式化的日期字符串（如 2025-01-23, 16:00:00）
      const formattedDate = new Intl.DateTimeFormat('zh-CN', options).format(new Date(date));

      // 转换为 yyyy-MM-dd HH:mm:ss 格式
      const [datePart, timePart] = formattedDate.replace(',', '').split(' ');
      return `${datePart} ${timePart}`;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        qwUserName: null,
        externalUserName: null,
        logType: null,
        contentJson: null,
        sendStatus: null,
        sendTime: null,
        companyId: null,
        receivingStatus: null,
        msgId: null,
        sendType: null,
        sopId: null
      };
      this.resetForm("form");
    },

    openImageViewer(url) {
      // 打开大图预览对话框
      this.dialogImageUrl=url
      this.dialogVisible = true;
    },
    openLink(url){
      // 使用 window.open 打开链接
      window.open(url, '_blank');
    },
    //查看发送的消息体
    showContentDialog(contentJson) {

      // 解析 JSON 字符串为 JavaScript 对象
      // 替换非法换行符等控制字符
      const sanitizedJson = contentJson.replace(/[\u0000-\u001F\u007F]/g, '');
      const parsedData = JSON.parse(sanitizedJson);

      this.contentDialog.json = parsedData.setting;

      this.contentDialog.isDialogVisible = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList(this.rowDetailFrom);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.scheduleStartTime=null;
      this.queryParams.scheduleEndTime=null;
      this.scheduleTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除【执行详情】编号为"【' + ids + '】"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delQwSopLogs(ids);
      }).then(() => {
        this.getList(this.rowDetailFrom);
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /**
     * 批量修改发送记录
     */
    handleEditCourse(row){
      const ids = row.id || this.ids;
      this.$confirm('确认要再次发送【执行详情】编号为"【' + ids + '】"的记录?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return editCourseQwSopLogs(ids);
      }).then(() => {
        this.getList(this.rowDetailFrom);
        this.msgSuccess("已经 修改记录为 待发送~");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企业微信SOP  定时任务数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportQwSopLogs(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },

    //生成短链
    generateShortLink(val){
      const param = {
        linkStr:val.miniprogramPage,
        appId:val.miniprogramAppid
      };
      generateShortLink(param).then(res=>{
        this.copyText = res.urlLink;
      });
      this.shortLinkDialogVisible = true;
    },
    onCopy(){
      navigator.clipboard.writeText(this.copyText).then(() => {
        this.$message.success('复制成功')
    })
    }

  }
};
</script>
<style scoped>
.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;
}
.ellipsis {
        max-width:100px;
        white-space: nowrap;
        text-overflow: ellipsis;
        display: inline-block;
}
</style>
