<template>
    <div class="event">
        <div ref="leftContainer" class="left">
            <el-form :inline="true">
                <el-form-item :label="$t('system:email:search:ToRecipientName')">
                    <el-input v-model="searchData.ToRecipientName" clearable />
                </el-form-item>
                <el-form-item :label="$t('system:email:search:CcRecipientName')">
                    <el-input v-model="searchData.CcRecipientName" clearable />
                </el-form-item>
                <el-form-item :label="$t('system:email:search:EmailStateEnum')">
                    <el-select v-model="searchData.EmailStateEnum" clearable filterable placeholder="">
                        <el-option v-for="item in $d.EmailState" :key="item.id" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <!-- <el-form-item :label="$t('system:email:search:EmailStateEnum')">
                    <el-select v-model="searchData.EmailStateEnum" clearable filterable placeholder="">
                        <el-option v-for="item in $d.EmailState" :key="item.id" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item> -->
                <el-form-item :label="$t('system:email:search:emailDate')">
                    <el-date-picker v-model="datetimerange" type="datetimerange"
                        :default-time="['00:00:00', '23:59:59']" :start-placeholder="$t('feedBack:search:beginTime')"
                        :end-placeholder="$t('feedBack:search:endTime')" value-format="yyyy-MM-dd HH:mm:ss"
                        @change="handleDatetimeChange" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small" @click="getList">
                        {{ $t('common:button:search') }}
                    </el-button>
                    <el-button icon="el-icon-refresh-left" size="small" @click="handleReset">
                        {{ $t('common:button:reset') }}
                    </el-button>
                    <el-button type="primary" size="small" @click="synchronizationEmail">
                        {{ $t('system:email:button:sync') }}
                    </el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="loading" v-adaptive="{ bottomOffset: 45 }" height="100" :data="list" class="table"
                @sort-change="handleSortByColumn">
                <el-table-column type="index" width="50" />
                <el-table-column :label="$t('system:email:table:messageId')" prop="MessageId" show-overflow-tooltip
                    sortable="custom" />
                <el-table-column :label="$t('system:email:table:emailSubject')" prop="EmailSubject"
                    show-overflow-tooltip />
                <el-table-column :label="$t('system:email:table:ToRecipientName')" prop="ToRecipientName"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.RecipientList.filter(item => item.RecipientTypeEnum === 0).map(item =>
                            `${item.RecipientName}: ${item.RecipientAddress}`).join('<br/>')" placement="top-start"
                            v-if="Array.isArray(scope.row.RecipientList) && scope.row.RecipientList.length > 0">
                            <span>{{Array.isArray(scope.row.RecipientList) && scope.row.RecipientList.length > 0
                                ? scope.row.RecipientList.filter(item => item.RecipientTypeEnum === 0).map(item =>
                                    item.RecipientName).join(", ") : ''
                            }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('system:email:table:CcRecipientName')" prop="CcRecipientName"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" :content="scope.row.RecipientList.filter(item => item.RecipientTypeEnum === 1).map(item =>
                            `${item.RecipientName}: ${item.RecipientAddress}`).join('<br/>')" placement="top-start"
                            v-if="Array.isArray(scope.row.RecipientList) && scope.row.RecipientList.length > 0">
                            <span>{{Array.isArray(scope.row.RecipientList) && scope.row.RecipientList.length > 0
                                ? scope.row.RecipientList.filter(item => item.RecipientTypeEnum === 1).map(item =>
                                    item.RecipientName).join(", ") : ''
                            }}</span>
                        </el-tooltip>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('system:email:table:emailDate')" prop="EmailDate" show-overflow-tooltip
                    sortable="custom" />
                <el-table-column :label="$t('system:email:table:emailStateEnum')" prop="EmailStateEnum"
                    show-overflow-tooltip sortable="custom">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.EmailStateEnum === 1 ? 'danger' : ''">{{ $fd("EmailState",
                            scope.row.EmailStateEnum) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('system:email:table:errorInfo')" prop="ErrorInfo" show-overflow-tooltip />
                <el-table-column :label="$t('common:action:action')" fixed="right" prop="" show-overflow-tooltip
                    min-width="120px">
                    <template slot-scope="scope">
                        <el-button type="text" @click="view(scope.row)">
                            {{ $t('common:button:view') }}
                        </el-button>
                        <el-button type="text" @click="resendEmail(scope.row)">
                            {{ $t('system:email:button:resendEmail') }}
                        </el-button>
                        <el-button type="text" @click="openResendEmailList(scope.row)">
                            {{ $t('system:email:button:resendEmailList') }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination" style="text-align: right; margin-top: 5px">
                <pagination :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
                    @pagination="getList" />
            </div>
        </div>
        <base-model v-if="model_cfg.visible" :config="model_cfg">
            <template slot="dialog-body">
                <emailDetail :info="info" />
            </template>
        </base-model>
        <el-dialog title="" :visible.sync="resendVisible" width="30%" :fullscreen='true'>
            <resendList :rowData="info" :isSystem="isSystem" />
        </el-dialog>
    </div>
</template>
<script>
import { getEmailLogList, resendEmail, getEmailInfo, synchronizationEmail } from '@/api/admin'
import Pagination from '@/components/Pagination'
import BaseModel from '@/components/BaseModel'
import emailDetail from "./components/detail"
import resendList from "./components/resendList"
const searchDataDefault = () => {
    return {
        TrialId: null,
        EmailStartDate: null,
        EmailEndDate: null,
        EmailStateEnum: null,
        ToRecipientName: null,
        CcRecipientName: null,
        Asc: false,
        SortField: 'CreateTime',
        PageIndex: 1,
        PageSize: 20,
    }
}
export default {
    name: 'emailLog',
    components: { Pagination, BaseModel, emailDetail, resendList },
    props: {
        isSystem: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            searchData: searchDataDefault(),
            list: [],
            total: 0,
            loading: false,
            datetimerange: [],
            model_cfg: { visible: false, title: '', width: '500px', fullscreen: true },
            info: null,
            resendVisible: false
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        openResendEmailList(row) {
            this.info = row
            this.resendVisible = true
        },
        getList() {
            this.loading = true
            if (!this.isSystem) this.searchData.TrialId = this.$route.query.trialId
            getEmailLogList(this.searchData)
                .then((res) => {
                    this.loading = false
                    this.list = res.Result.CurrentPageData
                    this.total = res.Result.TotalCount
                })
                .catch(() => {
                    this.loading = false
                })
        },
        // 查看详情
        async view(row) {
            try {
                let data = {
                    Id: row.Id,
                    TrialId: this.$route.query.trialId
                    // Id: "EC660000-BA37-5C60-8680-08DE1CD6931B"
                }
                let res = await getEmailInfo(data)
                if (res.IsSuccess) {
                    this.info = res.Result
                    if (Array.isArray(this.info.AttachmentList) && this.info.AttachmentList.length > 0) {
                        this.info.AttachmentList.forEach(item => {
                            var type = item.AttachmentName
                                .substring(item.AttachmentName.lastIndexOf('.'))
                                .toLocaleLowerCase().split('.')[1];
                            item.type = type
                        })
                    }
                    this.model_cfg.visible = true
                }
            } catch (err) {
                console.log(err)
            }
        },
        // 同步邮件
        async synchronizationEmail() {
            try {
                let data = {
                    TrialId: this.$route.query.trialId
                }
                this.loading = true
                let res = await synchronizationEmail(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                    this.$message.success(this.$t("system:email:message:syncSuccessfully"))
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        // 重发邮件
        async resendEmail(row) {
            try {
                let data = {
                    Id: row.Id,
                    TrialId: this.$route.query.trialId
                }
                this.loading = true
                let res = await resendEmail(data)
                this.loading = false
                if (res.IsSuccess) {
                    this.getList()
                    this.$message.success(this.$t("system:email:message:resendSuccessfully"))
                }
            } catch (err) {
                this.loading = false
                console.log(err)
            }
        },
        // 重置列表查询
        handleReset() {
            this.searchData = searchDataDefault()
            this.datetimerange = []
            this.getList()
        },
        // 排序
        handleSortByColumn(column) {
            if (column.order === 'ascending') {
                this.searchData.Asc = true
            } else {
                this.searchData.Asc = false
            }
            this.searchData.SortField = column.prop
            this.searchData.PageIndex = 1
            this.getList()
        },
        handleDatetimeChange(val) {
            if (val) {
                this.searchData.EmailStartDate = val[0]
                this.searchData.EmailEndDate = val[1]
            } else {
                this.searchData.EmailStartDate = ''
                this.searchData.EmailEndDate = ''
            }
        },
    },
}
</script>
<style lang="scss" scoped>
.event {
    height: 100%;
    box-sizing: border-box;
    display: flex;
    padding: 10px;
    border-radius: 5px;

    .left {
        display: flex;
        flex-direction: column;
        width: 0;
        flex-grow: 4;

        // border-right: 1px solid #ccc;
        .filter-container {
            display: flex;
            align-items: center;
            margin: 5px;
        }

        .data-table {
            flex: 1;
            padding: 5px 0px;
        }

        .pagination-container {
            text-align: right;
        }
    }
}
</style>
