<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" class-name="sub-navbar draft">
        <CommentDropdown v-show="mailTypeVisible" v-model="postForm.mailtype" />
        <el-button style="margin-left: 10px;" type="success" @click="dialogStatus==='create'?submitForm():updateFrom()">
          发布
        </el-button>
      </sticky>
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="10">
            <el-form-item label-width="120px" label="unikey:" class="postInfo-container-item" prop="unikey" required>
              <el-input v-model="postForm.unikey" :maxlength="100" placeholder="max 100 char" required :readonly="isupdate" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label-width="120px" label="发送时间:" class="postInfo-container-item" prop="sendtime">
              <el-date-picker v-model.number="postForm.sendtime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" placeholder="Select date and time" required />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label-width="120px" label="过期时间:" class="postInfo-container-item" prop="expiretime">
              <el-date-picker v-model.number="postForm.expiretime" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" placeholder="Select date and time" required />
            </el-form-item>
          </el-col>
          <el-col v-show="userRegVisible" :span="10">
            <el-form-item label-width="120px" label="注册时间>=:" class="postInfo-container-item" prop="user_reg_start_time">
              <el-date-picker v-model.number="postForm.user_reg_start_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" placeholder="Select date and time" :required="userRegVisible" />
            </el-form-item>
          </el-col>
          <el-col v-show="userRegVisible" :span="10">
            <el-form-item label-width="120px" label="注册时间<=:" class="postInfo-container-item" prop="user_reg_end_time">
              <el-date-picker v-model.number="postForm.user_reg_end_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" placeholder="Select date and time" :required="userRegVisible" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="subject">
              <MDinput v-model="postForm.subject" :maxlength="100" name="subject" placeholder="max 100 chars" required>
                邮件标题
              </MDinput>
            </el-form-item>
            <el-form-item prop="content" style="margin-bottom: 30px;" label="邮件正文:">
              <el-input v-model="postForm.content" type="textarea" :maxlength="1024" placeholder="max 1024 chars" :rows="6" />
            </el-form-item>
            <el-form-item style="margin-bottom: 30px;" label="附件:">
              <el-input v-model="postForm.attachments" type="textarea" :maxlength="256" placeholder="max 256 chars" :rows="6" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item v-show="groupMailVisible" style="margin-bottom: 40px;" prop="to" label="收件人列表:">
              <el-input v-model="postForm.recipients" type="textarea" :rows="6" required />

            </el-form-item>
          </el-col>
        </el-row>

      </div>
    </el-form>
  </div>
</template>

<script>
import { CommentDropdown } from '@/views/example/components/Dropdown'
import Sticky from '@/components/Sticky/index.vue'
import MDinput from '@/components/MDinput/index.vue'
import { addMail, updateEmail } from '@/api/mail'
import { parseTime } from '@/utils'
import { MAIL_TYPE_GROUP, MAIL_TYPE_ALL } from '@/constant/constant'
import { ItemList } from '@/constant/itemids'

export default {
  name: 'Email',
  components: { MDinput, CommentDropdown, Sticky },
  data() {
    return {
      postForm: {
        mailtype: MAIL_TYPE_GROUP,
        unikey: '',
        sendtime: '',
        expiretime: '',
        user_reg_start_time: '',
        user_reg_end_time: '',
        subject: '',
        content: '',
        attachments: '',
        recipients: ''
      },
      rules: {
        sendtime: [{ required: true, message: '请选择发送时间', trigger: 'blur' }],
        expiretime: [{ required: true, message: '请选择过期时间', trigger: 'blur' }],
        subject: [{ required: true, message: 'subject is required', trigger: 'blur' }],
        content: [{ required: true, message: 'content is required', trigger: 'blur' }],
        user_reg_start_time: [
          { required: true, message: '用户注册开始时间', trigger: 'blur' },
          {
            validator: (rule, value, cb, source, options) => {
              const errors = []
              console.log(this.postForm.mailtype)
              cb()
              return errors
            },
            trigger: 'blur'
          }
        ],
        user_reg_end_time: [
          { required: true, message: '用户注册结束时间', trigger: 'blur' },
          {
            validator: (rule, value, cb, source, options) => {
              const errors = []
              console.log(this.postForm.mailtype)
              cb()
              return errors
            }
          }
        ]
      },
      userRegVisible: false,
      groupMailVisible: true,
      mailTypeVisible: true,
      dialogStatus: 'create',
      isupdate: false
    }
  },
  watch: {
    'postForm.mailtype'(val) {
      switch (val) {
        case MAIL_TYPE_GROUP:
          this.userRegVisible = false
          this.groupMailVisible = true
          break
        case MAIL_TYPE_ALL:
          this.userRegVisible = true
          this.groupMailVisible = false
          break
      }
      /*
        if (this.dialogStatus === 'create' && val === 2) {
        }*/
    }
  },
  created() {
    const mailid = this.$route.params.mailid
    if (mailid) {
      this.mailTypeVisible = false
      this.dialogStatus = 'update'
      this.isupdate = true
      const editEmail = JSON.parse(sessionStorage.getItem('editEmail' + mailid))
      this.postForm = editEmail

      let str = ''
      if (editEmail.attachments != null) {
        editEmail.attachments.forEach((item) => {
          str += item['itemid'] + ':' + item['itemnum'] + '\n'
        })
      }
      this.postForm.attachments = str.slice(0, -1)
      this.postForm.sendtime = editEmail.sendtime * 1000
      this.postForm.expiretime = editEmail.expiretime * 1000
      this.postForm.user_reg_start_time = editEmail.user_reg_start_time * 1000
      this.postForm.user_reg_end_time = editEmail.user_reg_end_time * 1000
      this.postForm.recipients = editEmail.recipients.join('\n')
      this.postForm.unikey = editEmail.unikey
    } else {
      this.dialogStatus = 'create'
      this.isupdate = false
      sessionStorage.removeItem('editEmail' + mailid)
    }
  },
  methods: {
    parseTime,
    submitForm() {
      const data = JSON.parse(JSON.stringify(this.postForm))
      data.sendtime = data.sendtime / 1000
      data.expiretime = data.expiretime / 1000
      if (data.mailtype === MAIL_TYPE_GROUP) {
        data.user_reg_start_time = 0
        data.user_reg_end_time = 0x7FFFFFFF
        this.postForm.user_reg_start_time = 0
        this.postForm.user_reg_end_time = 0x7FFFFFFF * 1000
      } else {
        data.user_reg_start_time = data.user_reg_start_time / 1000
        data.user_reg_end_time = data.user_reg_end_time / 1000
      }
      console.log('valid begin')
      var list = []
      if (data.recipients != null && data.recipients !== '') {
        var j = 0
        data.recipients.split('\n').forEach((item, index) => {
          if (item != null && item !== '') {
            list[j] = item
            j++
          }
        })
      }
      data.recipients = list

      var arr = []
      if (data.attachments != null && data.attachments !== '') {
        j = 0
        var itemerr = false
        data.attachments.split('\n').some(item => {
          var itemArr = item.split(':')
          if (itemArr[0] != null && itemArr[0] !== '' && itemArr[1] != null && itemArr[1] !== '') {
            if (!this.checkItem(itemArr[0])) {
              this.$message({
                message: 'unknown item id ' + itemArr[0],
                type: 'error',
                duration: 2000
              })
              itemerr = true
              return true
            }
            var recipientsArr = {}
            recipientsArr['itemid'] = parseInt(itemArr[0])
            recipientsArr['itemnum'] = parseInt(itemArr[1])
            arr[j] = recipientsArr
            j++
          }
        })

        if (itemerr) {
          return
        }
      }
      data.attachments = arr
      try {
        this.$refs['postForm'].validate((valid) => {
          console.log('valid end', valid)
          if (this.postForm.mailtype === MAIL_TYPE_GROUP) {
            this.postForm.user_reg_start_time = ''
            this.postForm.user_reg_end_time = ''
          }
          if (valid) {
            addMail(data).then(response => {
              if (response.code === 0) {
                this.$message({
                  message: '发布成功',
                  type: 'success',
                  duration: 1200,
                  onClose: () => {
                    this.$router.push('index')
                  }
                })
              }
            })
          }
        })
      } catch (e) {
        console.log(e)
      }
    },
    updateFrom() {
      const data = JSON.parse(JSON.stringify(this.postForm))
      data.sendtime = data.sendtime / 1000
      data.expiretime = data.expiretime / 1000
      data.user_reg_start_time = data.user_reg_start_time / 1000
      data.user_reg_end_time = data.user_reg_end_time / 1000
      if (data.mailtype === MAIL_TYPE_GROUP) {
        data.user_reg_start_time = 0
        data.user_reg_end_time = 0xFFFFFFFF
      }
      var list = []
      if (data.recipients != null && data.recipients !== '') {
        var j = 0
        data.recipients.split('\n').forEach((item, index) => {
          if (item != null && item !== '') {
            list[j] = item
            j++
          }
        })
      }
      data.recipients = list

      var arr = []
      if (data.attachments != null && data.attachments !== '') {
        j = 0
        var itemerr = false
        data.attachments.split('\n').some(item => {
          var itemArr = item.split(':')
          if (itemArr[0] != null && itemArr[0] !== '' && itemArr[1] != null && itemArr[1] !== '') {
            if (!this.checkItem(itemArr[0])) {
              this.$message({
                message: 'unknown item id ' + itemArr[0],
                type: 'error',
                duration: 2000
              })
              itemerr = true
              return
            }
            var recipientsArr = {}
            recipientsArr['itemid'] = parseInt(itemArr[0])
            recipientsArr['itemnum'] = parseInt(itemArr[1])
            arr[j] = recipientsArr
            j++
          }
        })

        if (itemerr) {
          return
        }
      }
      data.attachments = arr
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          updateEmail(data).then(response => {
            if (response.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1200,
                onClose: () => {
                  sessionStorage.removeItem('editEmail' + data.mailid)
                  this.$router.replace('/email/index')
                }
              })
            }
          })
        }
      })
    },
    checkItem(itemid) {
      var found = false
      ItemList.some(item => {
        if (item === itemid) {
          found = true
          return true
        }
      })
      return found
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

</style>
