<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="个微账号昵称" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入个微账号昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户昵称" prop="wxContactName">
        <el-input
          v-model="queryParams.wxContactName"
          placeholder="请输入客户昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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 sendStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送类型" prop="sendType">
        <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="type">
        <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable size="small">
          <el-option label="个人" :value="0" />
          <el-option label="群" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="预计发送时间" prop="scheduleTime">
        <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>
        <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="['wx:wxSopLogs:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="wxSopLogsList">
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="个微账号昵称" align="center" prop="accountName" />
      <el-table-column label="客户昵称" align="center" prop="wxContactName" />
      <el-table-column label="客户标签" align="center" prop="tagNames" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.tagNames">{{ scope.row.tagNames }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="发送状态" align="center" prop="sendStatus" width="100">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.sendStatus === 0">待发送</el-tag>
          <el-tag type="success" v-else-if="scope.row.sendStatus === 1">发送成功</el-tag>
          <el-tag type="danger" v-else-if="scope.row.sendStatus === 2">发送失败</el-tag>
          <el-tag type="warning" v-else-if="scope.row.sendStatus === 3">消息作废</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发送类型" align="center" prop="sendType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="sysQwSopType" :value="scope.row.sendType"/>
        </template>
      </el-table-column>
      <el-table-column label="生成类型" align="center" prop="generateType" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.generateType === 0">自动</el-tag>
          <el-tag type="primary" v-else-if="scope.row.generateType === 1">手动</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" prop="createTime" width="165" />
      <el-table-column label="实际发送时间" align="center" prop="realSendTime" width="165">
        <template slot-scope="scope">
          <span v-if="scope.row.realSendTime">{{ scope.row.realSendTime }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="消息过期时间" align="center" prop="expirationTime" width="165">
        <template slot-scope="scope">
          <span v-if="scope.row.expirationTime">{{ scope.row.expirationTime }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="发送备注" align="center" prop="sendRemark" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.sendRemark">{{ scope.row.sendRemark }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listWxSopLogsCVO, exportWxSopLogsCVO } from "@/api/wx/wxSopLogs";

export default {
  name: "WxSopLogsList",
  props: {
    rowDetailFrom: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    rowDetailFrom: {
      handler(newVal) {
        // 当formData变化时重新查询
        this.getList(newVal);
      },
      deep: true
    }
  },
  data() {
    return {
      // 时间选择
      scheduleTime: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 个微SOP执行详情表格数据
      wxSopLogsList: [],
      // 发送状态字典
      sendStatusOptions: [
        { dictValue: '0', dictLabel: '待发送', listClass: 'default' },
        { dictValue: '1', dictLabel: '发送成功', listClass: 'success' },
        { dictValue: '2', dictLabel: '发送失败', listClass: 'danger' },
        { dictValue: '3', dictLabel: '消息作废', listClass: 'warning' }
      ],
      // 企微SOP发送类型
      sysQwSopType: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sopId: null,
        accountName: null,
        wxContactName: null,
        sendStatus: null,
        sendType: null,
        type: null,
        scheduleStartTime: null,
        scheduleEndTime: null
      }
    };
  },
  created() {
    this.getList(this.rowDetailFrom);
    
    // 发送消息类型
    this.getDicts("sys_qw_sop_course_type").then(response => {
      this.sysQwSopType = response.data;
    });
  },
  methods: {
    /** 查询个微SOP执行详情列表 */
    getList(val) {
      this.queryParams.sopId = val?.id || this.rowDetailFrom?.id;
      this.loading = true;

      listWxSopLogsCVO(this.queryParams).then(response => {
        console.log('个微SOP执行详情接口返回数据:', response);
        this.wxSopLogsList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('查询个微SOP执行详情失败:', error);
        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;

      const options = {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      };

      const formattedDate = new Intl.DateTimeFormat('zh-CN', options).format(new Date(date));
      const [datePart, timePart] = formattedDate.replace(',', '').split(' ');
      return `${datePart} ${timePart}`;
    },

    /** 搜索按钮操作 */
    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();
    },

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

<style scoped>
</style>
