<template>
  <div class="mail-content">
    <div v-show="!showMailDetail" class="mail-data">
      <div class="search">
        <el-button
          v-if="mailItem"
          type="danger"
          icon="el-icon-delete"
          :disabled="!selectedRows.length"
          @click="delMailItem('mlutiple')"
        >
          删除
        </el-button>
        <el-input
          v-model="searchKey"
          clearable=""
          placeholder="输入标题、发信人或发信人邮箱地址搜索邮件"
          @keyup.enter.native="search"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button type="primary" @click="search">搜索</el-button>
      </div>

      <el-table
        v-loading="tableLoading"
        :data="mailData"
        :height="tableHeight"
        :header-cell-style="headerStyle"
        @selection-change="selectionChange"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50"
        ></el-table-column>

        <el-table-column
          label="发件人"
          width="250"
          align="left"
          prop="senderName"
          sortable
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div class="flex">
              <div style="margin-right: 10px">
                <i
                  v-if="row.isRead == 1"
                  class="iconfont icon-yiduyoujian"
                  title="已读"
                ></i>
                <i v-else class="iconfont icon-shoujianxiang" title="未读"></i>
              </div>
              <el-popover trigger="hover" placement="right-end">
                <div>发件人: {{ row.senderName }}</div>
                <div style="margin: 10px 0">邮箱: {{ row.senderAddress }}</div>
                <el-button
                  v-show="row.isExitedMan == 1"
                  size="mini"
                  type="primary"
                  icon="el-icon-edit-outline"
                  @click="saveMailContact(row)"
                >
                  添加邮箱联系人
                </el-button>
                <div slot="reference" class="sender-name">
                  {{ row.senderName }}
                </div>
              </el-popover>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="subject"
          label="主題"
          align="left"
          sortable
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <div style="min-height: 24px" @click="checkMailDetail(row)">
              {{ row.subject }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="sendDate"
          sortable
          label="发信时间"
          width="200"
        ></el-table-column>
      </el-table>

      <el-row type="flex" justify="end" class="my-pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="pageSizes"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </el-row>
    </div>

    <div v-show="showMailDetail" class="mail-detail">
      <div v-if="mailDetail" v-loading="loading">
        <div class="fixed-top">
          <el-button
            size="mini"
            icon="el-icon-d-arrow-left"
            @click.stop="backToMailList"
          >
            返回
          </el-button>
          <el-button
            v-if="mailDetail.type == 1"
            size="mini"
            @click="replyMail(mailDetail)"
          >
            回复
          </el-button>

          <el-button size="mini" @click.stop="delMailItem('single')">
            删除
          </el-button>
        </div>

        <div class="detail">
          <div class="top">
            <div class="mail-title">{{ mailDetail.subject }}</div>
            <div>
              <label>发件人：</label>
              {{
                mailDetail.senderName +
                '&lt;' +
                mailDetail.senderAddress +
                '&gt;'
              }}
            </div>
            <div style="margin: 10px 0">
              <label>时　间：</label>
              {{ mailDetail.sendDate }}
            </div>
            <div>
              <label>收件人：</label>
              <span v-if="mailDetail.receiverName"></span>
              <span>{{ '&lt;' + mailDetail.receiverAddresses + '&gt;' }}</span>
            </div>
          </div>

          <div class="content" v-html="mailDetail.content"></div>

          <div v-if="mailAttachments.length" class="file-attachment">
            <el-card>
              <div slot="header">
                <i class="el-icon-document"></i>
                <span>共有{{ mailAttachments.length }}个附件</span>
              </div>
              <div
                v-for="item in mailAttachments"
                :key="item.id"
                class="file-container"
              >
                <span class="file-name" :title="item.fileName">
                  {{ item.fileName }}
                </span>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="downloadAttachments(item)"
                >
                  下载
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import tableCommon from '@/mixins/tableCommon'
  import {
    getMailList,
    getMailDetail,
    delMaliItemById,
    setMailIsRead,
    saveContact,
  } from '@/api/personal'
  import { downloadFile } from '@/api/appCenter'
  export default {
    name: 'MainContent',
    mixins: [tableCommon],
    props: {
      mailItem: {
        type: Object,
        default: null,
      },
      currentMail: {
        type: Object,
        default: null,
      },
    },
    data() {
      return {
        loading: false,
        tableLoading: false,
        showMailDetail: false,
        currentAccountId: '',
        searchKey: '',
        mailData: [],
        mailDetail: null,
        mailAttachments: [], // 附件
      }
    },
    watch: {
      mailItem: {
        handler() {
          this.showMailDetail = false
          this.pagination.page = 1
          this.search()
        },
        immediate: true,
      },
      currentMail: {
        handler(val) {
          if (val) {
            this.search()
          }
        },
        immediate: true,
      },
    },
    methods: {
      downloadAttachments(item) {
        downloadFile(item.id)
      },
      backToMailList() {
        this.mailDetail = null
        this.showMailDetail = false
      },
      // 邮件回复
      replyMail(mailDetail) {
        this.$emit('reply-mail', mailDetail)
      },
      saveMailContact(row) {
        const jsonData = {
          linkName: row.senderName,
          mailId: row.senderAddress,
        }
        this.$prompt('请输入邮箱联系人电话', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
        }).then(({ value }) => {
          jsonData.phone = value
          saveContact(jsonData)
            .then((res) => {
              if (res.state) {
                this.$message.success(res.message)
                this.search()
              }
            })
            .catch(() => {})
        })
      },
      delMailItem(type) {
        let tips = ''
        let types = ''
        const ids = []
        if (type == 'mlutiple') {
          tips = '是否删除选中邮件？'
          types = this.mailItem.types
          this.selectedRows.forEach((item) => {
            ids.push(item.id)
          })
        } else {
          tips = '是否删除该邮件？'
          ids.push(this.mailDetail.id)
          types = this.mailDetail.type
        }
        const data = {
          ids: ids.join(','),
          type: types,
        }
        this.$confirm(tips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          delMaliItemById(data)
            .then((res) => {
              if (res.state) {
                this.$message.success(res.message)
                this.search()
                this.showMailDetail = false
                this.$emit('update-mail')
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(() => {})
        })
      },
      checkMailDetail(row) {
        row.isRead = 1
        this.loading = true
        getMailDetail(row.id).then((data) => {
          if (data) {
            setMailIsRead(row.id)
            const Base64 = require('js-base64').Base64
            data.content = Base64.decode(data.content)
            this.mailDetail = data
            this.mailAttachments = data.mailAttachments
            // 如果是草稿箱时 跳转到编辑页面
            if (this.mailItem && this.mailItem.types === 3) {
              this.replyMail(this.mailDetail)
              return
            }
          }
          setTimeout(() => {
            this.loading = false
          }, 300)
        })
        this.showMailDetail = true
      },
      search() {
        this.tableLoading = true
        let id, types, parentId
        if (this.mailItem) {
          id = this.mailItem.id
          types = this.mailItem.types
          parentId = this.mailItem.parentId
        } else {
          id = this.currentMail.id
        }
        let querys = []
        const queryFilter = {
          pageBean: this.pagination,
        }
        if (!types) {
          if (this.searchKey != '') {
            querys = [...this.setQuerySearch(), ...this.setQueryIdAndType(id)]
          } else {
            querys = [...this.setQueryIdAndType(id)]
          }
          queryFilter.querys = querys
        } else {
          if (this.searchKey != '') {
            querys = [
              ...this.setQuerySearch(),
              ...this.setQueryIdAndType(parentId, types),
            ]
          } else {
            querys = [...this.setQueryIdAndType(parentId, types)]
          }
          queryFilter.querys = querys
        }
        getMailList(queryFilter).then((data) => {
          if (data) {
            this.pagination = {
              page: data.page,
              pageSize: data.pageSize,
              total: data.total,
            }
            this.mailData = data.rows ? data.rows : []
            setTimeout(() => {
              this.tableLoading = false
            }, 300)
          }
        })
      },
      setQuerySearch() {
        const query = [
          {
            property: 'subject',
            value: '',
            group: 'main',
            operation: 'LIKE',
            relation: 'OR',
          },
          {
            property: 'senderAddress',
            value: '',
            group: 'main',
            operation: 'LIKE',
            relation: 'OR',
          },
          {
            property: 'senderName',
            value: '',
            group: 'main',
            operation: 'LIKE',
            relation: 'OR',
          },
        ]
        query.forEach((item) => {
          item.value = this.searchKey
        })
        return query
      },
      setQueryIdAndType(id, type) {
        const querys = [
          {
            property: 'setId',
            value: id,
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          },
        ]
        if (type) {
          querys[1] = {
            property: 'type',
            value: type,
            group: 'main',
            operation: 'EQUAL',
            relation: 'AND',
          }
        }
        return querys
      },
    },
  }
</script>

<style lang="scss" scoped>
  .mail-content {
    height: 100%;
    .search {
      padding-bottom: 20px;
      .el-input {
        width: 400px;
        margin: 0 10px;
      }
    }
    .mail-detail {
      height: 100%;
      min-height: 100%;
      overflow-y: auto;
      .fixed-top {
        position: sticky;
        top: 0;
        right: 0;
        padding: 5px 10px;
        background: rgba(47, 97, 235, 0.38);
      }
      .top {
        padding: 15px;
        margin: 10px 0;
        background: #f4f7fe;
        .mail-title {
          color: $base-color-light-black;
          font-size: $base-font-size-default;
          font-weight: bold;
          margin-bottom: 15px;
        }
        label {
          display: inline-block;
          width: 60px;
        }
        .mb10 {
          margin-bottom: 10px;
        }
      }
      .content {
        padding: 15px;
      }
      .file-attachment {
        margin-top: 50px;
        .el-card {
          width: 500px;
          .file-container {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .file-name {
              display: inline-block;
              width: 350px;
              color: #4ec1c3;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
    }
    ::v-deep .el-table__row {
      cursor: pointer;
    }
  }
</style>
