<template>
    <div class="app-container">
        <el-row :gutter="24" class="baseInfo">
            <!-- 总记录 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>发送短信记录数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number total">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.recordCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 成功数 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>发送短信成功数</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number success">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.successRecordCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日发送 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日发送</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todayCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

            <!-- 今日成功 -->
            <el-col :xs="12" :sm="12" :lg="6" class="ivu-mb">
                <el-card shadow="hover" class="stat-card">
                    <div slot="header" class="card-header">
                        <span>今日成功</span>
                    </div>

                    <div class="content" v-loading="loadingCount">
                    <span class="card-number today-success">
                      <count-to
                          v-if="!loadingCount"
                          :start-val="0"
                          :end-val="count.todaySuccessCount || 0"
                          :duration="2000"
                      />
                    </span>
                    </div>
                </el-card>
            </el-col>

        </el-row>

        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="96px">
            <el-form-item prop="roboticId">
                <el-select
                    v-model="queryParams.roboticId"
                    filterable
                    clearable
                    placeholder="请选择任务"
                    @change="handleQuery"
                    class="task-select"
                >
                    <i slot="prefix" class="el-icon-s-operation"/>

                    <el-option label="所有任务" :value="null"/>
                    <el-option
                        v-for="item in roboticList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
<!--            <el-form-item>-->
<!--                <el-button type="cyan" 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
                    v-hasPermi="['company:addwxlog:list']"
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="handleQuery"/>
        </el-row>

        <el-table v-loading="loading" :data="companySendMsgList">
            <!--      <el-table-column label="记录 ID" align="center" prop="logId" width="90" />-->
            <el-table-column label="任务 ID" align="center" prop="roboticId" width="150"/>
            <el-table-column label="任务名称" align="center" prop="name" width="250"/>
            <el-table-column label="发送数量" align="center" prop="totalRecordCount" width="150"/>
            <el-table-column label="发送成功数量" align="center" prop="successCount" width="150"/>
            <el-table-column label="发送失败数量" align="center" prop="failCount" width="150"/>
            <el-table-column label="发送中数量" align="center" prop="runningCount" width="150"/>
            <!--      <el-table-column label="销售名称" align="center" prop="companyUserName" width="180" />-->
            <!--      <el-table-column label="花费金额" align="center" prop="cost" />-->
            <!--      <el-table-column label="手机号码" align="center" prop="phone" />-->
            <!--      <el-table-column label="短信模版名称" align="center" prop="smsTempName" />-->
            <!--      <el-table-column label="内容长度" align="center" prop="contentLen" />-->
            <!--      <el-table-column label="公司" align="center" prop="companyName" />-->
            <!--      <el-table-column label="添加时间" align="center" prop="addTime" />-->

            <!--      <el-table-column label="状态" align="center" prop="status" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <el-tag :type="getStatusType(scope.row.status)">-->
            <!--            {{ getStatusLabel(scope.row.status) }}-->
            <!--          </el-tag>-->
            <!--        </template>-->
            <!--      </el-table-column>-->
            <!--      <el-table-column label="执行时间" align="center" prop="runTime" width="180">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.runTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed ="right">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-view"
                        @click="handleViewDetail(scope.row)"
                    >
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
            :title="detailTitle"
            :visible.sync="detailDialogVisible"
            width="90%"
            append-to-body
            @close="handleDetailClose"
        >
            <!-- 筛选条件 -->
            <el-form
                :model="detailQueryParams"
                ref="detailQueryForm"
                :inline="true"
                size="small"
                label-width="70px"
                class="detail-query-form"
            >
<!--                <el-form-item label="调用时间">-->
<!--                    <el-date-picker-->
<!--                        v-model="detailTimeRange"-->
<!--                        type="daterange"-->
<!--                        range-separator="至"-->
<!--                        start-placeholder="开始日期"-->
<!--                        end-placeholder="结束日期"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        clearable-->
<!--                    />-->
<!--                </el-form-item>-->

                <el-form-item label="手机号码">
                    <el-input
                        v-model="detailQueryParams.phone"
                        placeholder="请输入手机号码"
                        clearable
                        @keyup.enter.native="handleDetailQuery"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleDetailQuery">
                        查询
                    </el-button>
                    <el-button icon="el-icon-refresh" @click="resetDetailQuery">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>

            <!-- 表格 -->
            <el-table
                v-loading="detailLoading"
                :data="detailList"
                border
                style="width: 100%"
            >
                <el-table-column label="日志ID" align="center" prop="logId" />
<!--                <el-table-column label="任务id" align="center" prop="roboticId" />-->
                <el-table-column label="任务名称" align="center" prop="roboticName" />
<!--                <el-table-column label="caller_id" align="center" prop="callerId" />-->
                <el-table-column label="记录调用时间" align="center" prop="runTime" width="160" />
                <el-table-column label="执行状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status === 1" type="warning">执行中</el-tag>
                        <el-tag v-else-if="scope.row.status === 2" type="success">执行成功</el-tag>
                        <el-tag v-else-if="scope.row.status === 3" type="danger">执行失败</el-tag>
                        <span v-else>--</span>
                    </template>
                </el-table-column>
                <el-table-column label="公司id" align="center" prop="companyId" />
                <el-table-column label="公司名称" align="center" prop="companyName" />
                <el-table-column label="销售id" align="center" prop="companyUserId" />
                <el-table-column label="销售名称" align="center" prop="companyUserName" />
<!--                <el-table-column label="发送短信模板id" align="center" prop="tempId" />-->
                <el-table-column label="花费金额" align="center" prop="cost" />
                <el-table-column label="内容长度" align="center" prop="contentLen" />
                <el-table-column label="短信模板名称" align="center" prop="smsTempName" />
                <el-table-column label="发送手机号" align="center" prop="phone" />
            </el-table>

            <!-- 分页 -->
            <pagination
                v-show="detailTotal > 0"
                :total="detailTotal"
                :page.sync="detailQueryParams.pageNum"
                :limit.sync="detailQueryParams.pageSize"
                @pagination="getDetailList"
            />

            <div slot="footer" class="dialog-footer">
                <el-button @click="detailDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

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

<script>
import {listSendmsg, listByCallerIdAndRoboticId, delSendmsg, getSendMsgLogCount, exportSendmsg} from '@/api/company/sendmsg'
import {listAll as roboticListAll} from '@/api/company/companyVoiceRobotic'
import {listAll as accountListAll} from '@/api/company/companyAccount'
import CountTo from 'vue-count-to'

export default {
    name: 'WxClientStatistics',
    components: {CountTo},
    data() {
        return {
            loading: false,
            showSearch: true,
            total: 0,
            companySendMsgList: [],
            roboticList: [],
            accountList: [],
            count: {},
            totalRecordCount: 0,
            successRecordCount: 0,
            detailDialogVisible: false,
            detailLoading: false,
            detailList: [],
            detailTitle: "查看详情",
            detailTimeRange: [],
            detailTotal: 0,
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                roboticId: null,
                wxAccountId: null,
                customerIdId: null,
                status: null,
                time: []
            },
            detailQueryParams: {
                pageNum: 1,
                pageSize: 10,
                roboticId: null,
                phone: null,
                beginRunTime: null,
                endRunTime: null
            },
            loadingCount: false
        }
    },
    created() {
        this.initOptions()
        this.handleQuery()
        this.getCount()
    },
    methods: {
        initOptions() {
            roboticListAll().then((res) => {
                this.roboticList = res.data || []
            })
            accountListAll().then((res) => {
                this.accountList = res.data || []
            })
        },
        getQueryData() {
            const params = JSON.parse(JSON.stringify(this.queryParams))
            if (params.time && params.time.length === 2) {
                params.beginTime = params.time[0]
                params.endTime = params.time[1]
            }
            delete params.time
            return params
        },
        getList() {
            this.loading = true
            listSendmsg(this.getQueryData())
                .then((response) => {
                    this.companySendMsgList = response.rows || []
                    this.total = response.total || 0
                    this.successRecordCount = response.successRecordCount || 0
                    this.totalRecordCount = response.totalRecordCount || 0
                })
                .finally(() => {
                    this.loading = false
                })
        },
        // statis() {
        //   addWxStatistics(this.getQueryData()).then((res) => {
        //     this.count = res || {}
        //   })
        // },
        getStatusLabel(value) {
            if (value === 1) return '执行中'
            if (value === 2) return '成功'
            if (value === 3) return '失败'
            return '-'
        },
        getStatusType(value) {
            if (value === 1) return 'warning'
            if (value === 2) return 'success'
            if (value === 3) return 'danger'
            return 'info'
        },
        handleQuery() {
            this.queryParams.pageNum = 1
            // this.statis()
            this.getList()
        },
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        handleExport() {
            const queryParams = this.getQueryData()
            this.$confirm('是否确认导出查询出的短链课程看课记录数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.exportLoading = true;
                return exportSendmsg(queryParams)
            }).then((response) => {
                this.download(response.msg)
                this.exportLoading = false;
            }).catch(() => {
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.logId || this.ids;
            this.$confirm('是否确认删除编号为 "' + ids + '" 的加微信日志数据项？', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delSendmsg(ids);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () {
            });
        },
        /** 点击查看详情 */
        handleViewDetail(row) {
            this.detailTitle = `查看详情 - ${row.roboticName || ""}`;
            this.detailDialogVisible = true;

            this.detailQueryParams.pageNum = 1;
            this.detailQueryParams.pageSize = 10;
            this.detailQueryParams.callerId = row.callerId;
            this.detailQueryParams.roboticId = row.roboticId;
            this.detailQueryParams.phone = null;
            this.detailQueryParams.beginRunTime = null;
            this.detailQueryParams.endRunTime = null;
            this.detailTimeRange = [];

            this.getDetailList();
        },

        /** 查询详情分页列表 */
        getDetailList() {
            this.detailLoading = true;
            listByCallerIdAndRoboticId(this.detailQueryParams).then(response => {
                this.detailList = response.rows || [];
                this.detailTotal = response.total || 0;
                this.detailLoading = false;
            }).catch(() => {
                this.detailLoading = false;
            });
        },
        handleDetailQuery() {
            this.detailQueryParams.pageNum = 1;

            if (this.detailTimeRange && this.detailTimeRange.length === 2) {
                this.detailQueryParams.beginRunTime = this.detailTimeRange[0];
                this.detailQueryParams.endRunTime = this.detailTimeRange[1];
            } else {
                this.detailQueryParams.beginRunTime = null;
                this.detailQueryParams.endRunTime = null;
            }

            this.getDetailList();
        },
        resetDetailQuery() {
            this.detailTimeRange = [];
            this.detailQueryParams.pageNum = 1;
            this.detailQueryParams.pageSize = 10;
            this.detailQueryParams.phone = null;
            this.detailQueryParams.beginRunTime = null;
            this.detailQueryParams.endRunTime = null;
            this.getDetailList();
        },
        /** 获取统计数据 */
        getCount() {
            this.loadingCount = true;
            getSendMsgLogCount().then(res => {
                this.count = res.data || {};
                this.loadingCount = false;
            }).catch(() => {
                this.loadingCount = false;
            });
        },
        handleDetailClose() {
            this.detailList = [];
            this.detailTotal = 0;
            this.detailTimeRange = [];
            this.detailQueryParams = {
                pageNum: 1,
                pageSize: 10,
                callerId: null,
                roboticId: null,
                phone: null,
                beginRunTime: null,
                endRunTime: null
            };
        },
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.baseInfo {
    margin-bottom: 30px;
}

.content {
    .card-panel-num {
        display: inline-block;
        font-size: 30px;
    }

    &-time {
        font-size: 14px;
    }
}

.task-select .el-input__inner {
    background-color: #ecf5ff;
    border: 1px solid #409EFF;
    border-radius: 20px;
    height: 36px;
    padding-left: 15px;
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.1);
    transition: all 0.2s;
}

.task-select .el-input__inner:hover {
    border-color: #66b1ff;
}

.task-select .el-input.is-focus .el-input__inner {
    border-color: #409EFF;
    box-shadow: 0 0 8px rgba(64, 158, 255, 0.3);
    background-color: #ffffff;
}
/* 卡片整体 */
.stat-card {
    border-radius: 10px;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
}

/* 标题 */
.card-header {
    font-size: 14px;
    color: #666;
}

/* 内容区域 */
.content {
    height: 60px;
    display: flex;
    align-items: center;
}

/* 数字基础样式 */
.card-number {
    font-size: 28px;
    font-weight: bold;
}

/* 🎨 颜色区分 */
.card-number.total {
    color: #409EFF; /* 蓝色 */
}

.card-number.success {
    color: #67C23A; /* 绿色 */
}

.card-number.today {
    color: #E6A23C; /* 橙色 */
}

.card-number.today-success {
    color: #F56C6C; /* 红色 */
}
</style>
