<template>
  <div class="app-container-push-log">
    <div class="filter-container">
      <el-select
        v-model="listQuery.sysOrigin"
        :placeholder="$t('pages.messagePushTask.filter.system')"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in sysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.shelfStatus"
        :placeholder="$t('pages.messagePushTask.filter.status')"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in shelfStatusList"
          :key="String(item.value)"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        {{ $t('pages.messagePushTask.filter.search') }}
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.messagePushTask.filter.add') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column
        prop="remarks"
        :label="$t('pages.messagePushTask.table.remarks')"
        align="center"
      />
      <el-table-column
        prop="sysOrigin"
        :label="$t('pages.messagePushTask.table.system')"
        align="center"
      >
        <template slot-scope="scope">
          <sys-origin-icon :icon="scope.row.sysOrigin" :desc="scope.row.sysOrigin" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.messagePushTask.table.language')" align="center">
        <template slot-scope="scope">
          {{ getLanguageLabel(scope.row.language) }}
        </template>
      </el-table-column>
      <el-table-column prop="title" :label="$t('pages.messagePushTask.table.title')" align="center" />
      <el-table-column prop="content" :label="$t('pages.messagePushTask.table.content')" align="center" />
      <el-table-column :label="$t('pages.messagePushTask.table.schedule')" align="center">
        <template slot-scope="scope">
          <el-tag>{{ getScheduleLabel(scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('pages.messagePushTask.table.status')" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.shelfStatus == 1" type="success">
            {{ $t('pages.messagePushTask.statusOption.published') }}
          </el-tag>
          <el-tag v-if="scope.row.shelfStatus == 0" type="danger">
            {{ $t('pages.messagePushTask.statusOption.unpublished') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('pages.messagePushTask.table.createdAt')"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        :label="$t('pages.messagePushTask.table.actions')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate(scope.row)">
            {{ $t('pages.messagePushTask.actions.edit') }}
          </el-button>
          <el-button type="text" @click.native="handleDelete(scope.row.id)">
            {{ $t('pages.messagePushTask.actions.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <el-dialog
      :title="dialogTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="65%"
    >
      <div>
        <el-form ref="form" class="i18n-form" :model="form" :rules="rules" label-width="100px">
          <el-form-item prop="remarks" :label="$t('pages.messagePushTask.form.remarks')">
            <el-input
              v-model="form.remarks"
              :placeholder="$t('pages.messagePushTask.placeholder.remarks')"
              maxlength="200"
            />
          </el-form-item>
          <el-form-item prop="title" :label="$t('pages.messagePushTask.form.title')">
            <el-input
              v-model="form.title"
              :placeholder="$t('pages.messagePushTask.placeholder.title')"
              maxlength="200"
            />
          </el-form-item>
          <el-form-item prop="content" :label="$t('pages.messagePushTask.form.content')">
            <el-input
              v-model="form.content"
              type="textarea"
              :placeholder="$t('pages.messagePushTask.placeholder.content')"
              maxlength="1000"
            />
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.system')" prop="sysOrigin">
            <el-select v-model="form.sysOrigin">
              <el-option
                v-for="item in sysOriginPlatforms"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.client')" prop="platform">
            <el-select
              v-model="form.platform"
              clearable
              :placeholder="$t('pages.messagePushTask.placeholder.all')"
            >
              <el-option
                v-for="item in appPlatforms"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.pushPlatform')" prop="deviceType">
            <el-select v-model="form.deviceType">
              <el-option
                v-for="item in deviceTypes"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.language')" prop="language">
            <el-select
              v-model="form.language"
              clearable
              :placeholder="$t('pages.messagePushTask.placeholder.selectLanguage')"
            >
              <el-option :label="$t('pages.messagePushTask.languageOption.ar')" value="ar" />
              <el-option :label="$t('pages.messagePushTask.languageOption.tr')" value="tr" />
              <el-option :label="$t('pages.messagePushTask.languageOption.other')" value="en" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.businessScene')" prop="businessScene">
            <el-select v-model="form.businessScene">
              <el-option
                :label="$t('pages.messagePushTask.businessScene.officialNotice')"
                value="OFFICIAL_MESSAGE_NOTICE"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.fixedUserIds')" prop="fixedUserIds">
            <el-input
              v-model.trim="form.fixedUserIds"
              type="textarea"
              :placeholder="$t('pages.messagePushTask.placeholder.fixedUserIds')"
              @blur="fixedUserIdBlur"
              @input="fixedUserIdKeyup"
            />
            <div class="font-info">
              {{ $t('pages.messagePushTask.tips.fixedUserIds', { count: inputFixedNumber }) }}
            </div>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.status')" prop="shelfStatus">
            <el-select v-model="form.shelfStatus">
              <el-option
                v-for="item in shelfStatusList"
                :key="String(item.value)"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pages.messagePushTask.form.schedule')">
            <el-row class="demo-autocomplete">
              <el-col :span="3">
                <el-input v-model="form.days" :placeholder="$t('pages.messagePushTask.placeholder.day')" />
              </el-col>
              <el-col :span="3">
                <el-input v-model="form.hours" :placeholder="$t('pages.messagePushTask.placeholder.hour')" />
              </el-col>
              <el-col :span="3">
                <el-input v-model="form.minutes" :placeholder="$t('pages.messagePushTask.placeholder.minute')" />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit()">
              {{ $t('pages.messagePushTask.actions.save') }}
            </el-button>
            <el-button @click="handleClose()">
              {{ $t('pages.messagePushTask.actions.cancel') }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { messageBusinessScene, userTypes } from '@/constant/type'
import { appPlatforms, deviceTypes, sysOriginPlatforms } from '@/constant/origin'
import { pushTaskPage, savePushTask, deletePushTask } from '@/api/message'
import Pagination from '@/components/Pagination'
import { validPositiveNumber } from '@/utils/validate'
import { pickerOptions } from '@/constant/el-const'

function getFormData() {
  return {
    id: '',
    title: '',
    sysOrigin: '',
    content: '',
    businessScene: 'OFFICIAL_MESSAGE_NOTICE',
    platform: '',
    fixedUserIds: '',
    origin: '',
    language: '',
    deviceType: '',
    remarks: '',
    shelfStatus: '',
    days: '',
    hours: '',
    minutes: ''
  }
}

export default {
  components: { Pagination },
  data() {
    return {
      pickerOptions,
      appPlatforms,
      formVisible: false,
      dialogMode: 'create',
      deviceTypes,
      sysOriginPlatforms,
      messageBusinessScene,
      userTypes,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        shelfStatus: '',
        sysOrigin: ''
      },
      listLoading: true,
      form: getFormData(),
      inputFixedNumber: 0
    }
  },
  computed: {
    dialogTitle() {
      const key = this.dialogMode === 'edit' ? 'edit' : 'create'
      return this.$t(`pages.messagePushTask.dialog.${key}`)
    },
    shelfStatusList() {
      return [
        {
          value: false,
          name: this.$t('pages.messagePushTask.statusOption.unpublished')
        },
        {
          value: true,
          name: this.$t('pages.messagePushTask.statusOption.published')
        }
      ]
    },
    rules() {
      return {
        hours: [
          { required: true, message: this.$t('pages.messagePushTask.validation.enterHours'), trigger: 'blur' },
          { min: 1, max: 2, message: this.$t('pages.messagePushTask.validation.length1To2'), trigger: 'blur' }
        ],
        minutes: [
          { required: true, message: this.$t('pages.messagePushTask.validation.enterMinutes'), trigger: 'blur' },
          { min: 1, max: 2, message: this.$t('pages.messagePushTask.validation.length1To2'), trigger: 'blur' }
        ],
        title: [
          { required: true, message: this.$t('pages.messagePushTask.validation.enterTitle'), trigger: 'blur' },
          { min: 3, max: 200, message: this.$t('pages.messagePushTask.validation.length3To200'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('pages.messagePushTask.validation.enterContent'), trigger: 'blur' },
          { min: 3, max: 500, message: this.$t('pages.messagePushTask.validation.length3To500'), trigger: 'blur' }
        ],
        sysOrigin: {
          required: true,
          message: this.$t('pages.messagePushTask.validation.selectSystem'),
          trigger: 'blur'
        },
        deviceType: {
          required: true,
          message: this.$t('pages.messagePushTask.validation.selectPushPlatform'),
          trigger: 'blur'
        },
        platform: {
          required: true,
          message: this.$t('pages.messagePushTask.validation.selectPlatform'),
          trigger: 'blur'
        },
        shelfStatus: {
          required: true,
          message: this.$t('pages.messagePushTask.validation.selectStatus'),
          trigger: 'blur'
        }
      }
    }
  },
  created() {
    this.renderData()
  },
  methods: {
    renderData() {
      const that = this
      that.listLoading = true
      pushTaskPage(that.listQuery).then(res => {
        const { body } = res
        that.total = body.total || 0
        that.list = body.records
        that.listLoading = false
      })
    },
    handleCreate() {
      this.dialogMode = 'create'
      this.inputFixedNumber = 0
      this.resetForm()
      this.formVisible = true
    },
    handleSearch() {
      this.renderData()
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = row.id
    },
    handleUpdate(row) {
      const that = this
      that.dialogMode = 'edit'
      that.inputFixedNumber = 0
      that.form = row
      that.formVisible = true
    },
    handleDelete(id) {
      const that = this
      that.$confirm(
        that.$t('pages.messagePushTask.confirm.deleteMessage'),
        that.$t('pages.messagePushTask.confirm.title'),
        {
          confirmButtonText: that.$t('pages.messagePushTask.confirm.confirm'),
          cancelButtonText: that.$t('pages.messagePushTask.confirm.cancel'),
          type: 'warning'
        }
      ).then(() => {
        deletePushTask(id).then(() => {
          that.$message({
            type: 'success',
            message: that.$t('pages.messagePushTask.message.success')
          })
          that.resetForm()
          this.renderData()
        }).catch(() => {
          that.$opsMessage.success()
        })
      }).catch(() => {
        that.$message({
          type: 'info',
          message: that.$t('pages.messagePushTask.confirm.cancelled')
        })
      })
    },
    onSubmit() {
      const that = this
      that.$refs.form.validate(valid => {
        if (!valid) {
          console.error('error submit!!')
          return false
        }
        savePushTask(that.form).then(res => {
          if (res.status) {
            that.$message({
              type: 'success',
              message: that.$t('pages.messagePushTask.message.success')
            })
            that.resetForm()
            that.formVisible = false
            this.renderData()
          } else {
            that.$opsMessage.fail(res.errorMsg)
          }
        }).catch(() => {
          that.$opsMessage.success()
        })
      })
    },
    fixedUserIdBlur() {
      const list = this.filterUserIds(this.form.fixedUserIds.split(','), 100)
      this.form.fixedUserIds = list.join(',')
      this.inputFixedNumber = list.length
    },
    filterUserIds(contentArrays, maxSize) {
      const inputNumber = contentArrays.length
      const list = []
      for (let index = 0; index < inputNumber; index++) {
        const item = contentArrays[index]
        if (validPositiveNumber(item)) {
          list.push(item)
        }
        if (list.length === maxSize) {
          break
        }
      }
      return list
    },
    handleClose() {
      this.formVisible = false
    },
    resetForm() {
      this.form = getFormData()
    },
    fixedUserIdKeyup(value) {
      if (!value) {
        this.inputFixedNumber = 0
        return
      }
      const contentArrays = value.split(',')
      if (contentArrays.length > 100) {
        const list = this.filterUserIds(contentArrays, 100)
        this.form.fixedUserIds = list.join(',')
        this.inputFixedNumber = list.length
        return
      }
      this.inputFixedNumber = contentArrays.length
    },
    getLanguageLabel(language) {
      if (language === 'ar') {
        return this.$t('pages.messagePushTask.languageOption.ar')
      }
      if (language === 'tr') {
        return this.$t('pages.messagePushTask.languageOption.tr')
      }
      if (language) {
        return this.$t('pages.messagePushTask.languageOption.other')
      }
      return ''
    },
    getScheduleLabel(row) {
      const dayText = row.days != null && row.days !== ''
        ? this.$t('pages.messagePushTask.scheduleText.everyMonthDay', { day: row.days })
        : this.$t('pages.messagePushTask.scheduleText.everyDay')
      const hourText = this.$t('pages.messagePushTask.scheduleText.hour', { value: row.hours })
      const minuteText = this.$t('pages.messagePushTask.scheduleText.minute', { value: row.minutes })
      return `${dayText} ${hourText} ${minuteText}`.trim()
    }
  }
}
</script>
