<template>
  <div class="app-container">
    <div style="margin-bottom: 10px">
      <el-card>
        <span class="custom-style" style="display: block; margin-bottom: 10px">自动化规则名称：{{ sopName }}</span>
        <span class="custom-style" style="display: block; margin-bottom: 10px">自动化规则编号：{{ queryParams.sopId }}</span>
        <span class="custom-style" style="display: block;">模板编号：{{ tempId }}</span>
      </el-card>
    </div>

    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="客服id" prop="customerId">
        <el-input
          v-model="queryParams.customerId"
          @input="queryParams.customerId = queryParams.customerId.replace(/[^\d]/g, '')"
          placeholder="请输入客服id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客服名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客服名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="会员id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          @input="queryParams.userId = queryParams.userId.replace(/[^\d]/g, '')"
          placeholder="请输入会员id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="营期时间" prop="startTime">
        <el-date-picker clearable size="small" v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
          placeholder="选择营期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in sopUserLogsDelStatus" :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-tooltip class="item" effect="dark"
            content="此功能用于给 选中的 营期 内【所有的】客户发送消息" placement="top">
          <el-button
            type="warning"
            icon="el-icon-s-promotion"
            size="medium"
            :disabled="multiple"
            @click="openGroupSendMessagePage"
          >一键群发
          </el-button>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="删除营期之后,将不会在给原营期的客户发送消息，ps:删除之后不可恢复" placement="top">
          <el-button type="danger" icon="el-icon-s-promotion" size="medium" :disabled="multiple"
            @click="handleDeleteUserLogs">批量删除营期
          </el-button>

        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="批量修改营期之后,将不会在给原营期的客户发送消息，ps:修改日期之后原日期不可恢复" placement="top">
          <el-button type="info" icon="el-icon-s-promotion" size="medium" :disabled="multiple"
            @click="handleUpdateTimeUserLogs">批量修改营期时间
          </el-button>
        </el-tooltip>
      </el-col>
    </el-row>

    <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
      <i class="el-icon-info"></i>
      【营期一键群发】：此功能用于给 选中的 营期 内【所有的】客户发送 消息
    </div>

    <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
      <i class="el-icon-info"></i>
      【批量删除营期】：此功能用于删除选中的【整个营期】,删除之后将不会在给原营期的客户发送消息，ps:删除之后不可恢复
    </div>

    <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
      <i class="el-icon-info"></i>
      【批量修改营期时间】：此功能用于修改选中的【整个营期时间】,修改之后将不会在给原营期时间的客户发送消息，ps:修改之后不可恢复
    </div>

    <div style="color: #999;font-size: 14px;display: flex;align-items: center;margin-bottom: 5px">
      <i class="el-icon-info"></i>
      【天数】：【列表：营期时间】对应列表中的天数是几 就代表着 插件助手 会发送【任务模板】里的第几天的消息
    </div>
    
    <el-table border v-loading="loading" :data="sopUserLogsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="营期编号" align="center" prop="id" />
      <el-table-column label="客服id" align="center" prop="customerId" />
      <el-table-column label="客服名称" align="center" prop="customerName" />
      <el-table-column label="营期时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="待发天数" align="center" prop="countDays"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <div v-if="scope.row.userId && scope.row.userId.includes('null')">
            <span style="color: orange;">营期异常</span>
          </div>
          <div v-else>
            <dict-tag :options="sopUserLogsDelStatus" :value="scope.row.status" />
          </div>

        </template>
      </el-table-column>

      <!-- 过滤模式是根据标签 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == 1" size="mini" type="text" icon="el-icon-edit"
            @click="handleSelect(scope.row)">营期详情
          </el-button>
          <el-button v-if="scope.row.userId && scope.row.userId.includes('null')" size="mini" type="text"
            icon="el-icon-s-check" @click="handleRepairLogs(scope.row)">修复营期
          </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-drawer :title="sopUserLogsInfoDialog.title" :visible.sync="sopUserLogsInfoDialog.visible" size="88%"
      style="font-weight: bolder">
      <sop-user-logs-info-details
        :refreshCount="sopUserLogsInfoDialog.refreshCount"
        :params="sopUserLogsInfoDialog.params"
      />
    </el-drawer>
  
    <el-dialog title="批量修改客户营期" :visible.sync="updateLogsForm.visible" width="500px" append-to-body>
      <el-form ref="updateLogsForm" :model="updateLogsForm" :rules="updateLogsForm.rules" label-width="120px">
        <el-form-item label="选择营期时间" prop="paramTime">
          <el-date-picker clearable size="small"
            v-model="updateLogsForm.pTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择营期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="一键群发"
      :visible.sync="groupSendMessageForm.visible" width="1000px" append-to-body :close-on-click-modal="false">
      <group-send-message
        :visible="groupSendMessageForm.visible"
        :ids="groupSendMessageForm.ids"
        :sourceType="0"
        @changeGroupSendMessageVisible="changeGroupSendMessageVisible"
      />
    </el-dialog>

  </div>

</template>

<script>
import {
  delSopUserLogs,
  exportSopUserLogs,
  listSopUserLogs,
  repairSopUserLogs,
  addGroupChat,
  updateLogDate,
  updateTimeSopUserLogs
} from "@/api/app/userLogs";
import SopUserLogsInfoDetails from "@/views/app/sop/userLogsInfo/sopUserLogsInfoDetails.vue";
import groupSendMessage from "@/views/app/sop/userLogsInfo/groupSendMessage.vue";

export default {
  name: "sopUserLogsSchedule",
  components: {
    SopUserLogsInfoDetails,
    groupSendMessage,
  },
  props: {
    rowDetailFrom: {},
  },
  data() {
    return {
      groupSendMessageForm: {
        ids: [],
        visible: false,
      },
      qwUserIds: [],
      sopUserLogId: null,
      companyUserLists: [],
      sopName: '',
      tempId: '',
      listUser: {
        title: '选择发送人',
        open: false
      },
      updateLogsForm: {
        visible: false,
        pTime: null,
        rules: {
          pTime: { required: true, message: '选择的时间不能为空', trigger: 'blur' }
        }
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      filterMode: 1,
      // 选中数组
      ids: [],
      chatNames: [],
      statusOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      sysQwSopAiContentType: [],
      userSelectList: [],
      // sopUserLogs表格数据
      sopUserLogsList: [],
      sopUserLogsDelStatus: [],
      // 弹出层标题
      title: "",
      mini: {
        open: false,
        loading: false,
        row: {},
      },
      // 是否显示弹出层
      open: false,
      // 一键发群相关数据
      uploadUrl: process.env.VUE_APP_BASE_API + "/app/common/uploadOSS",
      uploadUrlByVoice: process.env.VUE_APP_BASE_API + "/app/common/uploadOSSByHOOKVoice",
      msgForm: {
        videoId: null,
        courseId: null,
        courseType: null,
        userIdParam: null,
        sendType: 1,
        setting: null,
        ids: null,
        sopId: null,
        startTime: null,
        chatIds: [],
        filterMode: 2,
        sendTime: null,
        sendTimeType: 1, // 添加字段：1-当天发送，2-次日发送
      },
      sendMsgOpen: {
        title: '一键批量群发',
        open: false,
        row: {},
        ids: null,
        chatIds: [],
      },
      msgRules: {},
      videoList: [],
      chatList: [],
      setting: [],
      // SOP科普观看状态
      sysFsSopWatchStatus: [],
      // 查询参数
      addGroupData: {
        open: false,
        userOpen: false,
        selectChat: [],
        form: {
          chatIds: [],
        },
      },
      updateTimeData: {
        open: false,
        form: {
          date: null,
        },
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sopId: null,
        userLogsId: null,
        sopTempId: null,
        useId: null,
        customerId: null,
        customerName: null,
        startTime: null,
        status: null,
        type: null,
        chatName: null,
      },
      // 表单参数
      form: {},
      tempForm: {
        setting: null,
        videoIdSet: null,
        courseIdSet: null,
      },
      // 表单校验
      rules: {},
      sopUserLogsInfoDialog: {
        title: null,
        visible: false,
        refreshCount: 1,
        params: null,
      },
    };
  },
  created() {
    this.queryParams.sopId = this.$route.params.id;
    this.sopName = this.$route.query.name;
    this.filterMode = this.$route.query.filterMode;
    this.tempId = this.$route.query.tempId;
    this.queryParams.type = this.$route.query.type;
    this.getDicts("app_normal_disabled_status").then(response => {
      this.statusOptions = response.data;
    });

    this.getDicts("app_normal_del_status").then(response => {
      this.sopUserLogsDelStatus = response.data;
    });
    this.getDicts("app_sop_plugin_settingType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });
    this.getDicts("app_sop_watch_status").then(response => {
      this.sysFsSopWatchStatus = response.data;
    });

    this.queryParams.sopId = this.$route.params.id;
    this.sopName = this.$route.query.name;
    this.filterMode = this.$route.query.filterMode;
    this.tempId = this.$route.query.tempId;
    this.queryParams.type = this.$route.query.type;
    this.getList()
  },
  methods: {

    /** 查询sopUserLogs列表 */
    getList() {
      this.loading = true;
      listSopUserLogs(this.queryParams).then(response => {
        this.sopUserLogsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

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

    addSetList() {
      const newSetting = {
        contentType: '1',
        value: '',
        sendTimeType: 1, // 为每个规则项添加发送时间类型
      };
      this.setting.push(newSetting);
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        sopId: null,
        sopTempId: null,
        qwUserId: null,
        externalId: null,
        corpId: null,
        startTime: null,
        status: 0,
        userId: null
      };
      this.resetForm("form");
    },

    /**
     * 营期一键群发
     */
    openGroupSendMessagePage() {
      if (this.ids.length === 0) {
        return this.$message.error('请勾选具体群发记录！');
      }
      this.groupSendMessageForm.ids = this.ids;
      this.groupSendMessageForm.visible = true;
    },
    changeGroupSendMessageVisible(visible) {
      this.groupSendMessageForm.visible = visible;
    },
    /**
     *  批量修改营期
     */
    handleUpdateTimeUserLogs() {
      this.updateLogsForm.visible = true;
    },

    /**
     *  删除营期
     */
    handleDeleteUserLogs() {
      const ids = this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项【注意！！删除后不可恢复，请谨慎操作】?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSopUserLogs(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    flashNotify() {
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      if (this.filterMode == 2) {
        this.chatNames = selection.map(item => item.chatName);
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleSelect(val) {
      val.filterMode = this.filterMode;
      this.sopUserLogsInfoDialog.title = '【客服id/名称】：' + val.customerId + '/' + val.customerName + ',  ' + '【营期时间】：' + val.startTime + '  ' + '【天数】：' + val.countDays;
      this.sopUserLogsInfoDialog.params = val;
      this.sopUserLogsInfoDialog.refreshCount = this.sopUserLogsInfoDialog.refreshCount + 1;
      this.sopUserLogsInfoDialog.visible = true;
    },

    handleRepairLogs(val) {
      this.loading = true;
      let loadingRock = this.$loading({
        lock: true,
        text: '正在修复中请稍后~~！！',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      repairSopUserLogs(val).then(res => {
        this.msgSuccess("修复成功成功");
      }).catch(res => {
      }).finally(res => {
        loadingRock.close();
        this.loading = false;
        this.getList();
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有sopUserLogs数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportSopUserLogs(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },

    updateGroupTime() {
      this.updateTimeData.open = true;
      this.updateTimeData.form = { date: new Date() };
    },

    submitUpdateTimeForm() {
      let form = {
        date: this.updateTimeData.form.date,
        ids: this.ids,
      }
      updateLogDate(form).then(e => {
        this.updateTimeData.open = false;
        this.getList();
      });
    },

    submitAddGroupForm() {
      let form = {
        id: this.queryParams.sopId,
        qwUserIds: this.userSelectList.join(),
        chatIds: this.addGroupData.form.chatIds.join(),
        date: this.addGroupData.form.date,
      }
      addGroupChat(form).then(e => {
        this.addGroupData.open = false;
        this.getList();
      });
    },

    handleCompanyUser() {
      setTimeout(() => {
        this.$refs.QwUserList.getDetails(this.queryParams.corpId, this.queryParams.type, 2);
      }, 1);
      this.addGroupData.userOpen = true;
    },

    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()
      }
    },

    loadChatList() {
      // chatListAll(this.qwUserIds.join(), this.queryParams.corpId, this.queryParams.sopId).then(e => {
      //   this.addGroupData.selectChat = e.data;
      // })
    },

    selectUserList(list) {
      this.addGroupData.userOpen = false;
      list.forEach(obj => {
        if (!this.userSelectList.some(item => item == obj.id)) {
          this.userSelectList.push(obj.id);
          this.qwUserIds.push(obj.qwUserId);
        }
      });
      this.loadChatList()
    },
    submitForm() {
      this.$refs["updateLogsForm"].validate(valid => {
        if (valid) {

          this.updateLogsForm.ids = this.ids;
          this.updateLogsForm.sopId= this.queryParams.sopId;

          let loadingRock = this.$loading({
            lock: true,
            text: '正在执行中请稍后~~请不要刷新页面！！',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          updateTimeSopUserLogs(this.updateLogsForm).then(response => {
            this.msgSuccess("修改成功");
            loadingRock.close();
          }).finally(res=>{
            loadingRock.close();
          })
        }
      });
    },
    cancel() {
      this.resetBatch();
    },
    resetBatch() {
      this.updateLogsForm.visible = false;
      this.updateLogsForm.pTime = null;
    },
  }
};
</script>

<style>
.custom-style {
  font-weight: bold; /* 加粗 */
}
</style>
