<template>
  <div class="app-container">
    <div style="margin-bottom: 10px">
      <el-card>
        <span class="custom-style" style="display: block; margin-bottom: 10px">SOP规则名称：{{sopName}}</span>
        <span class="custom-style" style="display: block; margin-bottom: 10px">SOP规则编号：{{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="企微员工账号" prop="qwUserId">
        <el-input
          v-model="queryParams.qwUserId"
          placeholder="请输入企微员工账号"
          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 label="客户名称" prop="externalUserName">
        <el-input
          v-model="queryParams.externalUserName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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" v-if="filterMode == 1">
      <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="handleCampSendMsg"
            v-hasPermi="['qw:sopUserLogsInfo:msg']"
          >营期一键群发(或草稿)</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"
            v-hasPermi="['qw:sopUserLogs:remove']"
          >批量删除营期</el-button>

        </el-tooltip>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8" v-if="filterMode == 2">
      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="添加新群聊进入任务" placement="top">
          <el-button
            type="warning"
            icon="el-icon-plus"
            size="medium"
            @click="addGroup"
          >追加群聊</el-button>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5">
        <el-tooltip class="item" effect="dark" content="修改选择的群聊营期时间" placement="top">
          <el-button
            type="danger"
            icon="el-icon-edit"
            size="medium"
            :disabled="multiple"
            @click="updateGroupTime"
          >批量修改营期时间</el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <Tip v-if="filterMode == 1" :title="'【营期一键群发】：此功能用于给 选中的 营期 内【所有的】客户发送 消息【或者发送草稿-/-清楚草稿】'" />
    <Tip v-if="filterMode == 1" :title="'【批量删除营期】：此功能用于删除选中的【整个营期】,删除之后将不会在给原营期的客户发送消息，ps:删除之后不可恢复'" />
    <Tip v-if="filterMode == 1" :title="'【天数】：【列表：营期时间】对应列表中的天数是几 就代表着 插件助手 会发送【任务模板】里的第几天的消息'" />

    <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="模板编号" align="center" prop="sopTempId" />-->
      <el-table-column label="企微员工账号" align="center" prop="qwUserId" />
      <el-table-column label="企微员工名称" align="center" prop="qwUserName" />
      <el-table-column label="群聊" align="center" prop="chatName" v-if="filterMode == 2" />
      <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)"
            v-hasPermi="['qw:sop:list']"
          >营期详情</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)"
            v-hasPermi="['qw:sop:list']"
          >修复营期</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleTemp(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="logsInfoDetailsOpen.title" :visible.sync="logsInfoDetailsOpen.open" size="70%" style="font-weight: bolder">
      <sop-user-logs-info-details ref="SopUserLogsInfoDetails" :rowDetailFrom="logsInfoDetailsOpen.item" @flashNotify="flashNotify"></sop-user-logs-info-details>
    </el-drawer>

    <send-msg-open-tool ref="sendMsgOpenTool" ></send-msg-open-tool>
    <el-dialog title="修改营期时间" :visible.sync="updateTimeData.open"  width="800px" append-to-body>
      <p>
        <span>选择群聊：</span>
        <el-tag v-for="name in chatNames">{{name}}</el-tag>
      </p>
      <el-form ref="msgForm" :model="updateTimeData.form" label-width="100px">
        <el-form-item label="日期">
          <el-date-picker
            v-model="updateTimeData.form.date"
            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="submitUpdateTimeForm">确 定</el-button>
        <el-button @click="updateTimeData.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择企微" :visible.sync="addGroupData.userOpen" width="1300px"   append-to-body>
      <qwUserList ref="QwUserList" @selectUserList="selectUserList"></qwUserList>
    </el-dialog>

    <el-dialog title="追加群聊" :visible.sync="addGroupData.open"  width="800px" append-to-body>
      <el-form ref="msgForm" :model="addGroupData.form" label-width="100px">
        <el-form-item label="选择员工" prop="qwUserIds" style="margin-top: 2%">
          <div>
            <el-button
              size="medium"
              icon="el-icon-circle-plus-outline"
              plain
              @click="handleCompanyUser">请选择使用员工</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 companyUserLists " :key="list.userId" v-if="list.id == id">{{list.qwUserName}}</span>
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="群聊">
          <el-select multiple filterable clearable v-model="addGroupData.form.chatIds">
            <el-option v-for="item in addGroupData.selectChat" :key="item.chatId" :label="item.name" :value="item.chatId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="addGroupData.form.date"
            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="submitAddGroupForm">确 定</el-button>
        <el-button @click="addGroupData.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addGroupChat,
  delSopUserLogs,
  exportSopUserLogs,
  listSopUserLogs,
  repairSopUserLogs,
  updateLogDate
} from '@/api/qw/sopUserLogs'
import sopLogsDetails from '@/views/qw/sopLogs/sopLogsList.vue'
import SopUserLogsInfoDetails from '@/views/qw/sopUserLogsInfo/sopUserLogsInfoDetails.vue'
import SendMsgOpenTool from '@/views/qw/sopUserLogsInfo/sendMsgOpenTool.vue'
import Tip from '../../../components/Tip/index.vue'
import {listAll as chatListAll} from "@/api/qw/groupChat";
import companyUserList from "@/views/company/companyUser/companyUserList.vue";
import qwUserList from "@/views/qw/user/qwUserList.vue";
import {getQwAllUserList, listUser} from "@/api/company/companyUser";

export default {
  name: "sopUserLogsSchedule",
  components: {qwUserList, companyUserList, Tip, SendMsgOpenTool, SopUserLogsInfoDetails, sopLogsDetails},
  props:{
    rowDetailFrom:{},
  },

  data() {
    return {
      qwUserIds: [],
      companyUserLists:[],
      chatNames: [],
      userSelectList:[],
      sopUserLogId:null,
      sopName:'',
      tempId:'',
      // 遮罩层
      loading: true,
      // 查询参数
      addGroupData: {
        open: false,
        userOpen: false,
        selectChat: [],
        form: {
          chatIds: [],
        },
      },
      updateTimeData: {
        open: false,
        form: {
          date: null,
        },
      },
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      statusOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      logsInfoDetailsOpen:{
        title:"",
        open:false,
      },
      sysQwSopAiContentType:[],
      // sopUserLogs表格数据
      sopUserLogsList: [],
      sopUserLogsDelStatus:[],
      // 弹出层标题
      title: "",
      filterMode: 1,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sopId: null,
        userLogsId:null,
        externalUserName:null,
        sopTempId: null,
        qwUserId: null,
        corpId: null,
        startTime: null,
        status: null,
        type:null,
        userId: null
      },
      setting:[],
      // 表单参数
      form: {},
      tempForm: {
        setting:null,
        videoIdSet:null,
        courseIdSet:null,
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {

    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });

    this.getDicts("sop_user_logs_del_status").then(response => {
      this.sopUserLogsDelStatus = response.data;
    });
    this.getDicts("sys_qwSopAi_contentType").then(response => {
      this.sysQwSopAiContentType = response.data;
    });
    this.queryParams.sopId = this.$route.params.id;
    this.filterMode = this.$route.query.filterMode;
    this.sopName = this.$route.query.name;
    this.tempId = this.$route.query.tempId;
    this.queryParams.corpId= this.$route.query.corpId;
    this.queryParams.type= this.$route.query.type;
    getQwAllUserList(this.queryParams.corpId).then(response => {
      this.companyUserLists = response.data;
    });
    this.getList()

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


    /**
     * 营期一键群发
     */
    handleCampSendMsg(){

      setTimeout(() => {
        this.$refs.sendMsgOpenTool.oneClickGroupSending(this.ids,2,this.queryParams.corpId);
      }, 500);

    },

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

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    addSetList(){
        const newSetting = {
          contentType:'1',
          value: '',
        };
        // 将新设置项添加到 content.setting 数组中
        this.setting.push(newSetting);

    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sopId: null,
        sopTempId: null,
        qwUserId: null,
        corpId: null,
        startTime: null,
        status: 0,
        userId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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.logsInfoDetailsOpen.title='企微账号：'+val.qwUserId+'  '+'营期时间：'+val.startTime+'  '+'天数：' + val.countDays;
      this.logsInfoDetailsOpen.open=true;
      const externalUserName = this.queryParams.externalUserName;
      setTimeout(() => {
        this.$refs.SopUserLogsInfoDetails.selectSopUserLogsInfo(val,externalUserName);
      }, 500);

    },

    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(() => {});
    },
    addGroup(){
      this.addGroupData.open = true;
      this.addGroupData.form = {date: new Date(), chatIds: []};
    },
    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)) {
          console.info(this.userSelectList)
          this.userSelectList.push(obj.id);
          this.qwUserIds.push(obj.qwUserId);
        }
      });
      this.loadChatList()

    },
  }
};
</script>

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