<template>
  <div class="app-container">
    <!-- filter -->
    <el-form ref="filterForm" :inline="true" :model="filterForm" class="filter">
      <el-form-item label="关键字" prop="key">
        <el-input v-model="filterForm.key" placeholder="关键字"/>
      </el-form-item>
      <el-form-item :label="$t('main.shop')" prop="key" v-if="userLevel === 1">
        <el-select
            v-model="filterForm.sender"
            :placeholder="'选择'+$t('main.shop')"
            name="sender"
            required
            class="w100"
        >
          <el-option
              v-for="item in allDepts"
              :key="item._id"
              :label="item.name"
              :value="item._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetFilterForm">重置</el-button>
      </el-form-item>
    </el-form>
    <router-link to="/shop/mail_new">
      <el-button
          type="primary"
          icon="el-icon-edit"
          v-permission="['shopmail:edit']"
      >
        添加
      </el-button>
    </router-link>
    <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%;margin-top:30px;"
    >
      <el-table-column
          width="180px"
          align="center"
          label="添加时间"
      >
        <template slot-scope="{row}">
          <span>{{ row.createdAt | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="发送时间"
      >
        <template slot-scope="{row}">
          <span>{{ formatSendTime(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="类型"
      >
        <template slot-scope="{row}">
          <span>{{ row.type === 0 ? '普通': '群发' }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="发件人"
          prop="sender"
          v-if="userLevel === 1"
          :formatter = "formatDept"
      >
      </el-table-column>
      <el-table-column
          label="收件人"
      >
        <template slot-scope="{row}">
          <span>{{ formatReceive(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          min-width="200px"
          label="邮件标题"
      >
        <template slot-scope="{row}">
          <router-link
              :to="'/shop/mail_edit/'+row._id"
              class="link-type"
          >
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
          label="附件"
      >
        <template slot-scope="{row}">
          <span>{{ formatItems(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          width="320"
          label="操作"
          fixed="right"
      >
        <template slot-scope="scope">
          <router-link :to="'/shop/mail_edit/'+scope.row._id">
            <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                v-permission="['shopmail:edit']"
            >
              编辑
            </el-button>
          </router-link>
          <el-button
              type="danger"
              size="small"
              style="margin-left: 10px"
              v-permission="['shopmail:delete']"
              @click="handleDelete(scope)"
          >
            {{ $t('permission.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { IShopData } from '@/api/types'
import Pagination from '@/components/Pagination/index.vue'
import { getShops } from '@/api/shop'
import { parseTime } from '@/utils'
import { getAllCategory, getAllTags } from '@/api/question'
import { UserModule } from '@/store/modules/user'
import { EVENT_ACTIVITY_UPDATE, EVENT_MAIL_UPDATE, EVENT_SHOP_UPDATE, EventBus } from '@/utils/event-bus'
import { deleteMail, getMails, IMailData } from '@/api/mail'
import { LAST_SHOP } from '@/utils/storage'

@Component({
  name: 'MailList',
  components: {
    Pagination
  },
  filters: {
    parseTime: (timestamp: string) => {
      return parseTime(timestamp)
    },
    parseDate: (timestamp: string) => {
      if (!timestamp) {
        return '-'
      }
      return parseTime(timestamp, '{y}-{m}-{d}')
    },
    formatCount: (count: string) => {
      if (!count) {
        return 0
      }
      return count
    }
  }
})

export default class extends Vue {
  private total = 0
  private list: IMailData[] = []
  private listLoading = true
  private allDepts: IShopData[] = []
  private listQuery = {
    page: 1,
    limit: 20,
    key: '',
    sender: ''
  }

  private typeOptions: any[] = []
  private tagSet: Set<string> = new Set()
  private tagOptions: string[] = []
  private filterForm = {
    key: '',
    sender: ''
  }

  $refs!: {
    filterForm: HTMLFormElement
  }

  get userLevel() {
    return UserModule.level
  }

  async created() {
    if (UserModule.level === 1) {
      await this.getRemoteDeptList()
      EventBus.$on(EVENT_SHOP_UPDATE, () => {
        this.getRemoteDeptList()
      })
      if (this.$local.get(LAST_SHOP)) {
        this.filterForm.sender = this.$local.get(LAST_SHOP).id
        this.listQuery.sender = this.$local.get(LAST_SHOP).id
      }
    } else {
      this.filterForm.sender = UserModule.department
      this.listQuery.sender = UserModule.department
    }
    await this.getRemoteCategory()
    await this.getList()
    EventBus.$on(EVENT_MAIL_UPDATE, () => {
      this.getList()
    })
  }

  beforeDestory() {
    EventBus.$off(EVENT_MAIL_UPDATE)
    if (UserModule.level === 1) {
      EventBus.$off(EVENT_SHOP_UPDATE)
    }
  }

  private async getList() {
    this.listLoading = true
    const { data } = await getMails(this.listQuery)
    this.listLoading = false
    this.list = data.records
    this.total = data.total
  }

  private async handleDelete(scope: any) {
    const { $index, row } = scope
    await this.$confirm('确认删除该记录?', 'Warning', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteMail({ ids: [row._id] })
    this.list.splice($index, 1)
    this.$message({
      type: 'success',
      message: '删除成功!'
    })
  }

  private search() {
    this.filterData()
  }

  private filterData() {
    this.listQuery.key = this.filterForm.key
    this.listQuery.sender = this.filterForm.sender
    this.listQuery.page = 1
    this.getList()
  }

  private resetFilterForm() {
    this.$refs.filterForm.resetFields()
  }

  private async getRemoteDeptList() {
    const { data } = await getShops({ })
    if (!data.records) return
    this.allDepts = data.records
  }

  private async getRemoteTags() {
    const { data } = await getAllTags()
    console.log(data)
    this.tagSet = new Set(data)
    this.tagOptions = data
  }

  private async getRemoteCategory() {
    const { data } = await getAllCategory()
    for (const cat of data) {
      const subArr = []
      for (const s of cat.children) {
        subArr.push({
          value: s._id,
          label: s.name
        })
      }
      this.typeOptions.push({
        value: cat._id,
        label: cat.name,
        children: subArr
      })
    }
  }

  private formatDept(row: number, column: number, cellValue: string) {
    let result = '未指定'
    for (const dep of this.allDepts) {
      if (dep._id === cellValue) {
        result = dep.name
        break
      }
    }
    return result
  }

  private formatBool(row: number, column: number, cellValue: boolean) {
    return cellValue ? '是' : '否'
  }

  private formatReceive(data: any) {
    if (data.type === 0) {
      return `${data.accounts.length}人`
    } else if (data.type === 1) {
      return data.senderShop
    } else {
      return ''
    }
  }

  private formatItems(data: any) {
    return data.items.length + '件物品'
  }

  private formatSendTime(data: any) {
    let str = `${parseTime(data.sendTime, '{y}/{m}/{d}')}`
    if (data.endTime) {
      str += `-${parseTime(data.endTime, '{y}/{m}/{d}')}`
    }
    return str
  }
}
</script>
