<template>
    <!-- 发送邮件 -->
    <dialog-edit :visible.sync="dialogVisible" :title="$t('effectDealFeedBackMain.sendEmail')" width="60%" :api="api" :formRules="sendRules" :appendToBody="true"
                 :form="preForm" :editModel="editModel" @onSaved="onSaved" ref="form"
                 :autoClose="false" :saveLabel="$t('coordManageMain.send')" :autoSave="false" :loading="loadingSubmit">
          <!-- 发送表单 -->
          <external-transition  :title="$t('coordManageMain.createEmail')"></external-transition>
          <el-form ref="preView" :rules="formRules" :model="formData" labelWidth="130px">
            <dym-form class="msgClass" :formValue.sync="formData" :componentList="componentList">
            </dym-form>
            <div align="center">
              <auth-button size="medium" type="primary"
                              :label="$t('common.preview')"  icon="iconfont iconziliaoshenhe" @click="handlePreview" :loading="loadingOne"></auth-button>
            </div>
          </el-form>
          <!-- 预览 -->
          <el-collapse-transition>
            <div v-if="isShow">
                <external-transition  :title="$t('common.preview')"></external-transition>
                <dym-form ref="preForm" class="msgClass" :formValue.sync="preForm" :componentList="PreComponent" @uploadSuccess="uploadSuccess" @fileRemove="fileRemove">
                </dym-form>
              </div>
          </el-collapse-transition>
    </dialog-edit>
</template>

<script>
// 消息发送预览
import BaseEdit from '@/pages/baseEditPage'
import { dymForm, authButton, validate, DialogEdit, btnUpload } from 'newepoch-components'
import externalTransition from '@/components/element/assetoutfeedback/externalTransition'
import EditorElem from '@/components/element/assetoutfeedback/editorElem'

// import SelectCoreEnterprise from '@/components/element/SelectCoreEnterprise'
import coordManageApi from '@/api/assetoutfeedback/coordManage/coordManageApi.js'
import outsideManageApi from '@/api/assetoutfeedback/outsideManage/outsideManageApi.js'
import { UPLOAD_API } from '@/constant.js'

export default {
  extends: new BaseEdit('msgProjectSendMsg'),
  name: 'sendEmail',
  components: {
    dymForm,
    DialogEdit,
    authButton,
    externalTransition
  },
  props: {
    // 邮件类型：0 发送邮件 1 生成邮件
    emailType: {
      type: [String, Number],
      default () {
        return '0'
      }
    }
  },
  computed: {
    api () {
      return coordManageApi.sendMail
    }
  },
  data () {
    return {
      formData: {},
      preForm: {},
      formRules: {
        recipientName: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientName,
          trigger: 'blur'
        }],
        recipientCompany: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientCompany,
          trigger: 'blur'
        }],
        recipientEmail: [{
          required: true,
          validator: validate.emailValidate,
          trigger: 'blur'
        }, {
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientEmail,
          trigger: 'blur'
        }]
      },
      sendRules: {
        receivers: [{
          required: true,
          validator: validate.emailValidate,
          trigger: 'change'
        }, {
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.receivers,
          trigger: 'change'
        }],
        userAddress: [{
          required: true,
          validator: validate.emailValidate,
          trigger: 'change'
        }, {
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.userAddress,
          trigger: 'change'
        }],
        subject: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].coordManageMain.subject,
          trigger: 'change'
        }]
      },
      PreComponent: [
        // 收件人名称
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.receivers,
          value: 'receivers',
          prop: 'receivers',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [24, 12, 12, 12],
          componentName: 'el-input',
          maxlength: 250
        },
        // 发件人
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.userAddress,
          value: 'userAddress',
          prop: 'userAddress',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [24, 12, 12, 12],
          componentName: 'el-input',
          maxlength: 250
        },
        // 标题
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.subject,
          value: 'subject',
          prop: 'subject',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [24, 24, 24, 24],
          componentName: 'el-input',
          maxlength: 250
        },
        // 正文
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.content,
          value: 'content',
          prop: 'content',
          cols: [24, 24, 24, 24],
          componentName: EditorElem,
          minHeight: 50
        },
        // 附件
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.annexes,
          prop: 'annexes',
          value: 'annexes',
          cols: [24, 24, 24, 24],
          drag: true,
          attrs: {
            ref: 'upload',
            uploadApi: UPLOAD_API
          },
          componentName: btnUpload,
          showFiles: true
        }
      ],
      componentList: [
        // 收件人名称
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientName,
          value: 'recipientName',
          prop: 'recipientName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [12, 12, 12, 8],
          componentName: 'el-input',
          maxlength: 250
        },
        // 收件人公司名称
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientCompany,
          value: 'recipientCompany',
          prop: 'recipientCompany',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [12, 12, 12, 8],
          componentName: 'el-input',
          // componentName: EditorElem,'el-input'
          minHeight: 50
        },
        // 收件人邮箱
        {
          label: this.$i18n.messages[this.$i18n.locale].coordManageMain.recipientEmail,
          prop: 'recipientEmail',
          value: 'recipientEmail',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          cols: [12, 12, 12, 8],
          drag: true,
          componentName: 'el-input',
          // componentName: btnUpload,
          showFiles: true
        }
      ],
      isShow: false,
      loadingOne: false,
      loadingSubmit: false
    }
  },
  watch: {
    visible (val) {
      let $this = this
      if (!val) {
        $this.clearForm()
      }
    }
  },
  methods: {
    // 清除表单
    clearForm () {
      this.formData = {}
      this.preForm = {}
      this.isShow = false
    },
    // 邮件预览
    handlePreview () {
      this.$refs['preView'].validate((valid) => {
        if (valid) {
          this.loadingOne = true
          let args = Object.assign(this.form, this.formData)
          let api = [coordManageApi.preMail, outsideManageApi.generateMail][this.emailType]
          api.getDefault(args).then(res => {
            this.loadingOne = false
            if (res.success && res.data) {
              this.isShow = true
              this.$nextTick(() => {
                res.data.content = res.data.content.replace(/\n/g, '<br/>')
                res.data.annexes = res.data.annexes && res.data.annexes.length > 0 ? res.data.annexes.map(item => {
                  return {
                    name: item.fileName,
                    url: item.fileKeyId
                  }
                }) : []
                this.preForm = res.data
                // this.$set(this.preForm, 'content', content.replace(/\n/g, '<br/>'))
                // this.$set(this.preForm, 'receivers', receivers)
                // this.$set(this.preForm, 'userAddress', userAddress)
                // this.$set(this.preForm, 'subject', subject)
                // this.$set(this.preForm, 'annexes', annexes)
                this.$refs.preForm.$refs.upload.fileLists = res.data.annexes || []
              })
            }
          }).catch(res => {
            this.loadingOne = false
          })
        }
      })
    },
    send () {
      this.$refs.form.save()
    },
    // 发送邮件
    onSaved (val) {
      if (!this.isShow) {
        this.warning(this.$t('coordManageMain.sendMailPrompty'))
        return
      }
      if (this.preForm.annexes && this.preForm.annexes.length > 0 && !this.preForm.annexes[0].fileName) {
        this.setFilesData(this.preForm.annexes)
      }
      if (!val.content || val.content === '<p><br></p>') {
        this.warning(this.$t('coordManageMain.contentPrompt'))
        return
      }
      this.loadingSubmit = true
      this.api.postQuery(val).then(res => {
        this.loadingSubmit = false
        if (res.success && res.data) {
          // 显示成功 并关闭窗口
          this.success(this.$t('coordManageMain.sendSuccess'))
          this.dialogVisible = false
        }
      }).catch(() => {
        this.loadingSubmit = false
      })
    },
    checkData (value) {
      this.form.receivers = value
    },
    fileRemove (val) {
      this.setFilesData(val)
    },
    uploadSuccess (value, list) {
      this.setFilesData(list)
    },
    // 组织文件列表数据
    setFilesData (list) {
      let fileData = []
      list && list.length > 0 && list.forEach(item => {
        let datas = item.response ? item.response.data : item
        fileData.push({
          fileName: datas.fileName || datas.name,
          fileKeyId: datas.keyId || datas.url
        })
      })
      this.preForm.annexes = fileData
    }
  }
}
</script>
<style lang="scss" scope="scope">
  .el-upload{
    width: 100%
  }
  .el-upload-dragger {
    width: 100%
  }
  .msgClass {
    .el-form-item {
      height: 100%;
    }
  }
</style>
