<template>
  <div class="app-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="5">
            <el-form-item label-width="120px" label="游戏" class="postInfo-container-item" prop="gameid">
              <el-select v-model="gameid">
                <el-option label="2004" value="2004" />
                <el-option label="2006" value="2006" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="邮件标题" class="postInfo-container-item" prop="subject">
              <el-input v-model="postForm.subject" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="创建邮件账号" class="postInfo-container-item" prop="content">
              <el-input v-model="postForm.create_address" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="更新邮件账号" class="postInfo-container-item" prop="content">
              <el-input v-model="postForm.update_address" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label-width="120px" label="创建时间>=" class="postInfo-container-item" prop="createtime.start">
              <el-date-picker v-model.number="postForm.createtime.start" type="datetime" :format="formattedUTCCreateStartDate" value-format="timestamp" placeholder="Select date and time" style="width:105%" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="创建时间<=" class="postInfo-container-item" prop="createtime.end">
              <el-date-picker v-model.number="postForm.createtime.end" type="datetime" :format="formattedUTCCreateEndDate" value-format="timestamp" placeholder="Select date and time" style="width:105%" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="发送时间>=" class="postInfo-container-item" prop="sendtime.start">
              <el-date-picker v-model.number="postForm.sendtime.start" type="datetime" :format="formattedUTCSendStartDate" value-format="timestamp" placeholder="Select date and time" style="width:105%" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label-width="120px" label="发送时间<=" class="postInfo-container-item" prop="sendtime.end">
              <el-date-picker v-model.number="postForm.sendtime.end" type="datetime" :format="formattedUTCSendEndDate" value-format="timestamp" placeholder="Select date and time" style="width:105%" />
            </el-form-item>
          </el-col>
          <el-button style="margin-left: 30px;" type="success" @click="submitForm()">
            查询
          </el-button>
        </el-row>
        <el-table
          :empty-text="emptytext"
          height="700"
          :data="mailList"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <el-table-column
            prop="unikey"
            label="unikey"
            width="180"
          />
          <el-table-column
            prop="mail_id"
            label="邮件id"
            width="180"
          />
          <el-table-column
            prop="mail_type"
            label="类型"
            width="70"
          >
            <template slot-scope="{row}">
              <el-tag v-if="row.mail_type === 1">群发</el-tag>
              <el-tag v-if="row.mail_type === 2">全体</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="subject"
            label="邮件标题"
            width="160"
          />
          <el-table-column
            prop="content"
            label="邮件内容"
          />
          <el-table-column
            prop="sendtime"
            label="发送时间UTC"
            width="160"
          >
            <template slot-scope="{row}">
              <span>
                {{ parseUTCTime(row.sendtime) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="expiretime"
            label="过期时间UTC"
            width="160"
          >
            <template slot-scope="{row}">
              <span>
                {{ parseUTCTime(row.expiretime) }}
              </span>
            </template>
          </el-table-column>
          <!--      <el-table-column prop="to" label="收件人" width="95">-->
          <!--      </el-table-column>-->
          <el-table-column label="附件" align="center" width="50">
            <template slot-scope="{row}">
              <span v-if="row.attachments != null && row.attachments.length > 0" class="link-type" @click="handleFetchAtta(row.attachments)">查看</span>
              <el-tag v-else type="info">无</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="90"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :current-page="curpage"
          :page-size="pagesize"
          :page-count="totalpage"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
        <el-dialog :visible.sync="dialogAttaVisible" title="附件">
          <el-table :data="attaData" border fit highlight-current-row style="width: 100%">
            <el-table-column prop="item_id" label="ItemId" />
            <el-table-column prop="item_num" label="ItemNum" />
          </el-table>
        </el-dialog>
      </div>
    </el-form>
  </div>
</template>
<script>
// import Pagination from '@/components/Pagination/index.vue'
import { delMail, getMailList } from '@/api/mail'
import { parseUTCTime } from '@/utils'

export default {
  components: {

  },
  data() {
    return {
      gameid: '',
      postForm: {
        subject: '',
        content: '',
        createtime: {
          start: '',
          end: ''
        },
        sendtime: {
          start: '',
          end: ''
        },
        create_address: '',
        update_address: ''
      },
      rules: {
        gameid: [{ required: true, validator: (rule, value, callback) => {
          if (!this.gameid) {
            callback(new Error('请选择'))
          } else {
            callback()
          }
        }, trigger: 'blur' }],
        subject: [{ required: false, message: '', trigger: 'blur' }],
        content: [{ required: false, message: '', trigger: 'blur' }],
        createtime: {
          start: [{ required: false, validator: (rule, value, callback) => {
            if (this.postForm.createtime.end && !this.postForm.createtime.start) {
              callback(new Error('请同时选择'))
            } else {
              callback()
            }
          }, trigger: 'blur' }],
          end: [{ required: false, validator: (rule, value, callback) => {
            if (this.postForm.createtime.start && !this.postForm.createtime.end) {
              callback(new Error('请同时选择'))
            } else {
              callback()
            }
          }, trigger: 'blur' }]
        },
        sendtime: {
          start: [{ required: false, validator: (rule, value, callback) => {
            if (this.postForm.sendtime.end && !this.postForm.sendtime.start) {
              callback(new Error('请同时选择'))
            } else {
              callback()
            }
          }, trigger: 'blur' }],
          end: [{ required: false, validator: (rule, value, callback) => {
            if (this.postForm.sendtime.start && !this.postForm.sendtime.end) {
              callback(new Error('请同时选择'))
            } else {
              callback()
            }
          }, trigger: 'blur' }]
        }
      },
      dialogAttaVisible: false,
      mailList: [],
      attaData: [],
      pagesize: 10,
      totalpage: 0,
      curpage: 0,
      emptytext: ' ',
      querydata: null
    }
  },
  computed: {
    formattedUTCCreateStartDate() {
      if (!this.postForm.createtime.start) {
        return ''
      }

      return 'UTC:' + parseUTCTime(this.postForm.createtime.start / 1000)
    },
    formattedUTCCreateEndDate() {
      if (!this.postForm.createtime.end) {
        return ''
      }

      return 'UTC: ' + parseUTCTime(this.postForm.createtime.end / 1000)
    },
    formattedUTCSendStartDate() {
      if (!this.postForm.sendtime.start) {
        return ''
      }

      return 'UTC: ' + parseUTCTime(this.postForm.sendtime.start / 1000)
    },
    formattedUTCSendEndDate() {
      if (!this.postForm.sendtime.end) {
        return ''
      }

      return 'UTC: ' + parseUTCTime(this.postForm.sendtime.end / 1000)
    }
  },
  created() {
    // this.querydata = JSON.parse(JSON.stringify(this.postForm))
    // this.getList(this.querydata)
  },
  methods: {
    parseUTCTime,
    getList(data) {
      if (data.createtime.start === '' || data.createtime.end === '') {
        data.createtime.start = 0
        data.createtime.end = 0
      }
      if (data.createtime.start && data.createtime.end) {
        data.createtime.start = data.createtime.start / 1000
        data.createtime.end = data.createtime.end / 1000
      }
      if (data.sendtime.start === '' || data.sendtime.end === '') {
        data.sendtime.start = 0
        data.sendtime.end = 0
      }
      if (data.sendtime.start && data.sendtime.end) {
        data.sendtime.start = data.sendtime.start / 1000
        data.sendtime.end = data.sendtime.end / 1000
      }
      getMailList(this.gameid, this.curpage, this.pagesize, data).then(response => {
        if (response.code === 0) {
          this.mailList = response.data
          this.curpage = response.curpage
          this.totalpage = response.totalpage
          if (this.mailList === undefined || this.mailList.length <= 0) {
            this.emptytext = 'No data'
          }
        }
      })
    },
    submitForm() {
      console.log('valid begin')
      try {
        this.$refs['postForm'].validate((valid) => {
          console.log('valid end', valid)
          if (valid) {
            this.querydata = JSON.parse(JSON.stringify(this.postForm))
            this.curpage = 0
            this.getList(this.querydata)
          }
        })
      } catch (e) {
        console.log(e)
      }
    },
    handleCurrentChange(val) {
      this.curpage = val
      this.getList(this.querydata)
    },
    handleFetchAtta(row) {
      this.attaData = row
      this.dialogAttaVisible = true
    },
    handleUpdate(row) {
      // this.$store.dispatch('emailView/addEmail', row)
      sessionStorage.setItem('editEmail' + row.mail_id, JSON.stringify(row))
      sessionStorage.setItem('gameid', this.gameid)
      sessionStorage.setItem('mailtype', row.mail_type)
      this.$router.push('update/' + row.mail_id)
    },
    handleDelete(row) {
      console.log(row)
      delMail(this.gameid, row.mail_id).then((response) => {
        if (response.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1200,
            onClose: () => {
              if (this.curpage === this.totalpage && this.mailList.length < 2 && this.curpage > 1) {
                this.curpage--
              }
              this.getList(this.querydata)
            }
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error',
            duration: 1200
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
