<template>
  <div class="mail-edit">
    <div class="email-form">
      <el-form :model="mailForm" label-width="80px">
        <el-form-item label="发件人：">
          <el-select v-model="mailForm.senderAddress">
            <el-option
              v-for="account in accountList"
              :key="account.id"
              :label="account.mail"
              :value="account.mail"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="收件人：" required>
          <el-select
            v-model="receiverEmail"
            remote
            multiple
            filterable
            allow-create
            default-first-option
            :remote-method="remoteMethod1"
            placeholder="请选择收件人或输入关键字搜索：姓名或邮箱地址"
            style="width: 100%"
          >
            <el-option
              v-for="item in queryList1"
              :key="item.id"
              :label="item.linkName + '<' + item.mailId + '>'"
              :value="item.mailId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="showCopyTo == 2" label="抄送：">
          <el-select
            v-model="copyToMailList"
            remote
            multiple
            filterable
            allow-create
            default-first-option
            :remote-method="remoteMethod2"
            placeholder="请选择抄送人或输入关键字搜索：姓名或邮箱地址"
            style="width: 100%"
          >
            <el-option
              v-for="item in queryList2"
              :key="item.id"
              :label="item.linkName + '<' + item.mailId + '>'"
              :value="item.mailId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-show="showSCopyTo == 2" label="密送：">
          <el-select
            v-model="scopyToMailList"
            remote
            multiple
            filterable
            allow-create
            default-first-option
            :remote-method="remoteMethod3"
            placeholder="请选择密送人或输入关键字搜索：姓名或邮箱地址"
            style="width: 100%"
          >
            <el-option
              v-for="item in queryList3"
              :key="item.id"
              :label="item.linkName + '<' + item.mailId + '>'"
              :value="item.mailId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label=" ">
          <el-button v-if="showCopyTo" type="text" @click="handleCopyTo">
            {{ copyToText }}
          </el-button>

          <el-button v-if="showSCopyTo" type="text" @click="handleSCopyTo">
            {{ sCopyToText }}
          </el-button>
        </el-form-item>

        <el-form-item label="主题：" required>
          <el-input
            v-model="mailForm.subject"
            placeholder="请输入主题"
          ></el-input>
        </el-form-item>

        <el-form-item label="附件：">
          <ht-file
            v-model="fileList"
            type="card"
            display-style="block"
            :uploading.sync="fileUploading"
            :header="header"
            :action-url="actionUrl"
            @remove="remove"
            @download="download"
          ></ht-file>
        </el-form-item>

        <el-form-item label="正文：" style="height: 450px" required>
          <quill-editor
            v-model="mailForm.content"
            :options="editorOption"
            :editor-option="editorOption"
          ></quill-editor>
        </el-form-item>

        <el-form-item label=" ">
          <el-button
            type="primary"
            :disabled="loading || fileUploading"
            @click="_saveOrSendMail(2)"
          >
            发送邮件
          </el-button>

          <el-button :disabled="loading" @click="_saveOrSendMail(3)">
            保存草稿
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  import { quillEditor } from 'vue-quill-editor'
  import {
    getMailUserList,
    getContactList,
    saveOrSendMail,
    delMaliItemById,
  } from '@/api/personal'
  export default {
    name: 'MailEdit',
    components: {
      quillEditor,
    },
    props: {
      currentMail: {
        type: Object,
        default: null,
      },
      accountList: {
        type: Array,
        default: () => [],
      },
      replyMailDetail: {
        type: Object,
        default: null,
      },
    },
    data() {
      return {
        loading: false,
        showCopyTo: 1, // 抄送
        showSCopyTo: 1, // 密送

        queryList1: [],
        queryList2: [],
        queryList3: [],
        copyToMailList: [], // 抄送人邮箱列表
        scopyToMailList: [], // 密送人邮箱列表

        fileList: '',

        receiverEmail: [],
        mailForm: {
          senderAddress: '',
          receiverAddresses: '',
          copyToAddresses: '',
          bcCAddresses: '',
          content: '',
          type: '',
          isReply: 0,
          subject: '',
        },
        editorOption: {
          placeholder: '请输入内容......',
        },

        rules: {},
        contactsList: [],
        fileUploading: false,
      }
    },
    computed: {
      header() {
        return {
          Authorization: `Bearer ${this.$store.state.user.accessToken}`,
        }
      },
      actionUrl() {
        return `${window.context.portal}/system/file/v1/upload`
      },
      copyToText() {
        return this.showCopyTo == 1 ? '添加抄送' : '删除抄送'
      },
      sCopyToText() {
        return this.showSCopyTo == 1 ? '添加密送' : '删除密送'
      },
    },
    watch: {
      currentMail: {
        handler(val) {
          if (val) {
            this.mailForm.senderAddress = val.mailAddress
          }
        },
        immediate: true,
      },
    },
    created() {
      if (this.replyMailDetail) {
        this.setReplyMailForm()
      }
      this._getContactList()
    },
    methods: {
      handleCopyTo() {
        if (this.showCopyTo == 2) {
          this.copyToMailList = []
        }
        this.showCopyTo = this.showCopyTo == 1 ? 2 : 1
      },
      handleSCopyTo() {
        if (this.showSCopyTo == 2) {
          this.scopyToMailList = []
        }
        this.showSCopyTo = this.showSCopyTo == 1 ? 2 : 1
      },
      setReplyMailForm() {
        this.mailForm.isReply = 1
        const {
          type,
          subject,
          content,
          bcCAddresses,
          senderAddress,
          copyToAddresses,
          receiverAddresses,
        } = this.replyMailDetail
        if (type == 3) {
          this.mailForm.subject = subject
          this.mailForm.content = content
          this.mailForm.senderAddress = senderAddress
        } else if (type == 1) {
          this.mailForm.subject = `回复：${subject}`
          this.mailForm.content = ''
          this.mailForm.senderAddress = receiverAddresses
        }

        if (receiverAddresses) {
          if (type == 3) {
            this.receiverEmail.push(receiverAddresses)
          } else {
            this.receiverEmail.push(senderAddress)
          }
        }

        if (bcCAddresses) {
          this.showSCopyTo = 2
          this.scopyToMailList.push(bcCAddresses)
        }
        if (copyToAddresses) {
          this.showCopyTo = 2
          this.copyToMailList.push(copyToAddresses)
        }
      },
      _saveOrSendMail(type) {
        const { length } = this.receiverEmail
        const { subject, content } = this.mailForm
        if (!length && type != 3) {
          this.$message.error('请选择收件人！')
          return
        }
        if (subject === '' && type != 3) {
          this.$message.error('请填写主题！')
          return
        }
        if (content === '' && type != 3) {
          this.$message.error('请填写正文！')
          return
        }
        this.loading = true
        let warningTip = this.$message.warning('正在保存邮件，请稍候...')
        this.mailForm.type = type
        this.mailForm.bcCAddresses = this.scopyToMailList.join(';')
        this.mailForm.copyToAddresses = this.copyToMailList.join(';')
        this.mailForm.receiverAddresses = this.receiverEmail.join(';')
        if (this.fileList !== '') {
          const files = []
          const fileInfo = JSON.parse(this.fileList)
          if (fileInfo && fileInfo.length) {
            fileInfo.forEach((item) => {
              files.push({
                id: item.response.fileId,
                name: item.name,
                size: item.size,
                uid: item.uid,
                status: item.status,
              })
            })
            this.mailForm.fileIds = JSON.stringify(files)
          }
        } else {
          this.mailForm.fileIds = ''
        }
        saveOrSendMail(this.mailForm).then(async (res) => {
          this.loading = false
          if (res.code == 200) {
            // 如果是草稿发送成功，需删除草稿中对应数据
            if (this.replyMailDetail && this.replyMailDetail.type === 3) {
              await this.deleteMail(this.replyMailDetail.id)
            }
            this.$emit('update-mail', 'mailEdit')
            warningTip.close()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      },
      // 删除草稿中的数据
      deleteMail(id) {
        return new Promise((resolve) => {
          delMaliItemById({
            ids: [id],
            type: 2,
          }).then(() => {
            resolve()
          })
        })
      },
      remove(file, fileList) {
        this.$message(`删除${file.name}成功`)
      },
      download(file, fileList) {
        this.$message(`下载${file.name}成功`)
      },
      remoteMethod1(query) {
        this.getSelectData(this.queryList1, query)
      },
      remoteMethod2(query) {
        this.getSelectData(this.queryList2, query)
      },
      remoteMethod3(query) {
        this.getSelectData(this.queryList3, query)
      },
      getSelectData(list, query) {
        if (query !== '') {
          getMailUserList(query).then((data) => {
            if (data) {
              setTimeout(() => {
                list = data
              }, 200)
            }
          })
        } else {
          list = this.contactsList
        }
      },
      _getContactList() {
        const queryFilter = {
          pageBean: {
            page: 1,
            pageSize: 100,
          },
        }
        getContactList(queryFilter).then((data) => {
          if (data) {
            this.contactsList = data.rows ? data.rows : []
            this.queryList1 = this.contactsList
            this.queryList2 = this.contactsList
            this.queryList3 = this.contactsList
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .mail-edit {
    height: 100%;
    overflow-y: auto;
    .quill-editor {
      height: 400px;
    }
    ::v-deep .el-form-item {
      margin-bottom: 10px;
    }
  }
</style>
