<template>
    <div v-loading="loading" element-loading-text="拼命加载中">
        <el-form :inline="true">
            <el-form-item>
                <el-select
                    v-model="search.msgType"
                    placeholder="请选择消息类型"
                >
                    <el-option
                        v-for="item in msgTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="search.dateRange"
                    type="daterange"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%"
                    :clearable="false"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button
                    @click="handleSearch"
                    type="primary"
                    icon="el-icon-search"
                >
                    搜 索
                </el-button>
            </el-form-item>
        </el-form>
        <el-table
            :data="search.resultList"
            border
            stripe
            style="width: 100%"
            :reserve-selection="true"
            max-height="450"
        >
            <el-table-column
                type="index"
                :index="pageIndex"
                align="center"
                label="序号"
                width="50"
            ></el-table-column>

            <el-table-column
                prop="msgTitle"
                label="消息标题"
                width="300"
                show-overflow-tooltip
            ></el-table-column>
            <el-table-column
                prop="msgBrief"
                label="消息简介"
                width="600"
                show-overflow-tooltip
            ></el-table-column>
            <!-- <el-table-column
                prop="msgContent"
                label="消息内容"
                width="800"
                show-overflow-tooltip
            ></el-table-column> -->
            <el-table-column
                prop="startTime"
                label="开始时间"
                width="140"
                fixed="right"
                align="center"
                show-overflow-tooltip
            ></el-table-column>
            <el-table-column
                prop="endTime"
                label="结束时间"
                width="140"
                fixed="right"
                align="center"
                show-overflow-tooltip
            ></el-table-column>
            <el-table-column
                prop="enable"
                label="有效性"
                fixed="right"
                align="center"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <el-checkbox :value="scope.row.enable"></el-checkbox>
                </template>
            </el-table-column>
            <el-table-column
                prop="msgType"
                label="消息类型"
                fixed="right"
                align="center"
                :formatter="fmtMsgType"
                width="150"
            ></el-table-column>
            <el-table-column
                label="操作"
                align="center"
                fixed="right"
                width="300"
            >
                <template slot-scope="scope">
                    <el-button type="primary" @click="handleMsgEidt(scope.row)">
                        消息编辑
                    </el-button>
                    <el-button
                        type="primary"
                        :disabled="handleDisabledMsgSend(scope.row)"
                        @click="handleMsgSend(scope.row)"
                    >
                        消息发送
                    </el-button>
                    <el-button
                        type="primary"
                        :disabled="handleDisabledMsgSend(scope.row)"
                        @click="handleMsgSendTarget(scope.row)"
                    >
                        推送对象
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <br />
        <el-row type="flex" :gutter="20">
            <el-col :span="12"></el-col>
            <el-col :span="12">
                <div style="text-align: right">
                    <el-pagination
                        @size-change="handleSearchResultSizeChange"
                        @current-change="handleSearchResultCurrentChange"
                        :current-page="search.resultPagination.currentPage"
                        :page-sizes="search.resultPagination.pageSizes"
                        :page-size="search.resultPagination.pageSize"
                        layout="total, sizes, prev, pager, next"
                        :total="search.resultPagination.total"
                    >
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
        <el-dialog
            :visible.sync="msgSendDialog.visible"
            title="消息发送 - 选择接收目标"
            width="60%"
            center
            append-to-body
            top="8vh"
        >
            <div
                v-loading="msgSendDialog.loading"
                element-loading-text="拼命加载中"
            >
                <div v-if="msgSendDialog.msgType === 4">
                    <select-enterprises
                        ref="refSelectEnterprises"
                    ></select-enterprises>
                </div>
                <div v-if="msgSendDialog.msgType === 6">
                    <select-users ref="refSelectUsers"></select-users>
                </div>
                <el-divider></el-divider>
                <div style="text-align: right">
                    <el-button @click="msgSendDialog.visible = false">
                        取 消
                    </el-button>
                    <el-button type="primary" @click="handleMsgSendTarget"
                        >确定并发送</el-button
                    >
                </div>
            </div>
        </el-dialog>
        <el-dialog
            :visible.sync="sendTargetDialog.visible"
            title="推送对象"
            width="60%"
            center
            append-to-body
            top="8vh"
        >
            <div>
                <el-table
                    :data="sendTargetDialog.resultList"
                    border
                    stripe
                    style="width: 100%"
                    :reserve-selection="true"
                    height="450"
                >
                    <el-table-column
                        type="index"
                        align="center"
                        label="序号"
                        width="50"
                    ></el-table-column>

                    <el-table-column
                        prop="entName"
                        label="企业名称"
                        align="center"
                        show-overflow-tooltip
                        v-if="sendTargetDialog.msgType === 4"
                    ></el-table-column>
                    <el-table-column
                        prop="entTaxId"
                        label="企业税号"
                        align="center"
                        show-overflow-tooltip
                        v-if="sendTargetDialog.msgType === 4"
                    ></el-table-column>

                    <el-table-column
                        prop="mobile"
                        label="用户手机号"
                        align="center"
                        show-overflow-tooltip
                        v-if="sendTargetDialog.msgType === 6"
                    ></el-table-column>
                    <el-table-column
                        prop="userName"
                        label="用户名"
                        align="center"
                        show-overflow-tooltip
                        v-if="sendTargetDialog.msgType === 6"
                    ></el-table-column>
                </el-table>
                <el-divider></el-divider>
                <div style="text-align: right">
                    <el-button
                        type="primary"
                        @click="sendTargetDialog.visible = false"
                    >
                        确 定
                    </el-button>
                </div>
            </div>
        </el-dialog>
        <el-dialog
            v-if="msgEditDialog.visible"
            :visible.sync="msgEditDialog.visible"
            title="消息编辑"
            width="60%"
            center
            append-to-body
            top="8vh"
        >
            <div
                v-loading="msgEditDialog.loading"
                element-loading-text="拼命加载中"
            >
                <message-form
                    :inputForm="msgEditDialog.rowData"
                    @submit="msgEditSubmit"
                ></message-form>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import MessageForm from "./components/MessageForm";
import SelectEnterprises from "./components/SelectEnterprises";
import SelectUsers from "./components/SelectUsers";

import USER_MANAGEMENT from "@/api/user-management";
import DateHelper from "@/utils/date";

// 消息类型选项列表
const msgTypeOptions = [
    // 1235 服务商不能发布
    // {
    //     value: 1,
    //     label: "系统全局公告消息",
    // },
    // {
    //     value: 2,
    //     label: "全局的企业消息",
    // },
    // {
    //     value: 3,
    //     label: "全局的服务商消息",
    // },
    {
        value: 4,
        label: "企业个体消息",
    },
    // {
    //     value: 5,
    //     label: "服务商个体消息",
    // },
    {
        value: 6,
        label: "用户个人消息",
    },
    {
        value: 7,
        label: "服务商下企业消息",
    },
];

export default {
    name: "MessageHistory",
    components: {
        "message-form": MessageForm,
        "select-enterprises": SelectEnterprises,
        "select-users": SelectUsers,
    },
    data() {
        return {
            msgTypeOptions: msgTypeOptions,
            loading: false,
            search: {
                dateRange: [
                    DateHelper.LocalCurrentMonthStart(),
                    DateHelper.LocalCurrentMonthEnd(),
                ],
                msgType: null,
                enable: null,
                resultList: [],
                resultMultipleSelection: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            msgSendDialog: {
                visible: false,
                loading: false,
                rowData: null,
                msgType: null,
            },
            sendTargetDialog: {
                visible: false,
                rowData: null,
                msgType: null,
                resultList: [],
            },
            msgEditDialog: {
                visible: false,
                loading: false,
                rowData: null,
            },
        };
    },
    created() {
        this.callGetISPMsg(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        );
    },
    methods: {
        pageIndex(index) {
            let currentPage = this.search.resultPagination.currentPage; // 当前页码，具体看组件取值
            let pageSize = this.search.resultPagination.pageSize; // 每页条数，具体是组件取值
            return index + 1 + (currentPage - 1) * pageSize;
        },
        fmtMsgType(row, column, cellValue) {
            let result = cellValue;
            for (const item of msgTypeOptions) {
                if (item.value === cellValue) {
                    result = item.label;
                    break;
                }
            }
            return result;
        },
        handleSearch() {
            this.callGetISPMsg(1, this.search.resultPagination.pageSize);
        },
        handleSearchResultSizeChange(val) {
            this.callGetISPMsg(1, val);
        },
        handleSearchResultCurrentChange(val) {
            this.callGetISPMsg(val, this.search.resultPagination.pageSize);
        },
        handleDisabledMsgSend(row) {
            if (row && (row.msgType === 4 || row.msgType === 6)) {
                return false;
            } else {
                return true;
            }
        },
        // 消息转发
        handleMsgSend(row) {
            if (row) {
                this.msgSendDialog.rowData = row;
                this.msgSendDialog.msgType = row.msgType;
                this.msgSendDialog.visible = true;
            }
        },
        // 消息转发 确定发送
        handleMsgSendTarget() {
            const msgType = this.msgSendDialog.msgType;
            let args2 = {
                msgId: this.msgSendDialog.rowData.msgId,
                msgType: msgType,
            };

            if (msgType === 4) {
                let selectEnts = this.$refs.refSelectEnterprises.getSelectEnts();
                if (Array.isArray(selectEnts) && selectEnts.length > 0) {
                    let argsSelectEnts = [];
                    for (const item of selectEnts) {
                        argsSelectEnts.push(item.entTaxId);
                    }
                    args2.receiveKeys = argsSelectEnts;
                } else {
                    this.$message.error("没请选择至少一个接收消息企业！");
                    return false;
                }
            } else if (msgType === 6) {
                let selectUsers = this.$refs.refSelectUsers.getSelectUsers();
                if (Array.isArray(selectUsers) && selectUsers.length > 0) {
                    let argsSelectUsers = [];
                    for (const item of selectUsers) {
                        argsSelectUsers.push(item.id);
                    }
                    args2.receiveKeys = argsSelectUsers;
                } else {
                    this.$message.error("请选择至少一个接收消息用户！");
                    return false;
                }
            } else {
                this.$message.error("消息类型错误，不能进行消息转发！");
                return false;
            }

            let _this = this;
            _this.msgSendDialog.loading = true;
            USER_MANAGEMENT.msgSend(args2)
                .then((val2) => {
                    _this.$message.success(val2.msg);
                    _this.msgSendDialog.visible = false;
                })
                .catch((err2) => {
                    _this.$message.error(err2);
                })
                .finally(() => {
                    _this.msgSendDialog.loading = false;
                });
        },
        // 消息推送目标
        handleMsgSendTarget(row) {
            if (row) {
                let _this = this;
                _this.loading = true;
                USER_MANAGEMENT.getMsgSendTarget(row.msgId)
                    .then((val2) => {
                        _this.sendTargetDialog.resultList = val2.data.records;

                        _this.sendTargetDialog.rowData = row;
                        _this.sendTargetDialog.msgType = row.msgType;
                        _this.sendTargetDialog.visible = true;
                    })
                    .catch((err2) => {
                        _this.$message.error(err2);
                    })
                    .finally(() => {
                        _this.loading = false;
                    });
            }
        },
        // 消息编辑
        handleMsgEidt(row) {
            if (row) {
                this.msgEditDialog.rowData = row;
                this.msgEditDialog.visible = true;
            }
        },
        // 保存编辑消息
        msgEditSubmit(args) {
            let _this = this;
            this.msgEditDialog.loading = true;
            USER_MANAGEMENT.msgSaveOrUpdate(args)
                .then((val) => {
                    _this.$message.success(val.msg);
                    _this.msgEditDialog.visible = false;

                    _this.callGetISPMsg(
                        _this.search.resultPagination.currentPage,
                        _this.search.resultPagination.pageSize
                    );
                })
                .catch((err) => {
                    _this.$message.error(err);
                })
                .finally(() => {
                    _this.msgEditDialog.loading = false;
                });
        },
        /**
         * 用户手机号查询企业列表
         * @param {Number} pageNum : 当前页码
         * @param {Number} pageSize : 每页数量
         */
        callGetISPMsg(pageNum, pageSize) {
            let beginTime = "";
            let endTime = "";
            if (this.search.dateRange instanceof Array) {
                beginTime = this.search.dateRange[0];
                endTime = this.search.dateRange[1];
                beginTime = this.dateFormat(
                    new Date(beginTime),
                    "yyyy-MM-dd HH:mm:ss"
                );
                let endTimeObj = new Date(endTime);
                endTime = this.dateFormat(
                    new Date(
                        endTimeObj.getFullYear(),
                        endTimeObj.getMonth(),
                        endTimeObj.getDate(),
                        "23",
                        "59",
                        "59"
                    ),
                    "yyyy-MM-dd HH:mm:ss"
                );
            } else {
                this.$message.error(
                    "起始日期与结束日期为必输项，请确定后重试！"
                );
                return false;
            }

            let _this = this;
            this.loading = true;
            USER_MANAGEMENT.getISPMsg({
                createTimeBegin: beginTime,
                createTimeEnd: endTime,
                msgType: this.search.msgType,
                pageNum: pageNum,
                pageSize: pageSize,
            })
                .then((val) => {
                    _this.search.resultPagination.total = val.data.total;
                    _this.search.resultPagination.pageSize = val.data.size;
                    _this.search.resultPagination.currentPage =
                        val.data.current;
                    _this.search.resultList = val.data.records;
                })
                .catch((err) => {
                    _this.$message.error(err);
                })
                .finally(() => {
                    _this.loading = false;
                });
        },
        dateFormat(date, fmt) {
            // 小时只支持24小时制
            var o = {
                "M+": date.getMonth() + 1, // 月份
                "d+": date.getDate(), // 日
                "H+": date.getHours(), // 24小时,
                "m+": date.getMinutes(), // 分
                "s+": date.getSeconds(), // 秒
                "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
                S: date.getMilliseconds(), // 毫秒
            };
            if (/(y+)/.test(fmt))
                fmt = fmt.replace(
                    RegExp.$1,
                    (date.getFullYear() + "").substr(4 - RegExp.$1.length)
                );
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt))
                    fmt = fmt.replace(
                        RegExp.$1,
                        RegExp.$1.length == 1
                            ? o[k]
                            : ("00" + o[k]).substr(("" + o[k]).length)
                    );
            return fmt;
        },
    },
};
</script>

<style scoped>
</style>