<template>
  <div class="app-container-push-log">
    <div class="filter-container">

      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        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="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in shelfStatusList"
          :key="item.value"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
    >
      <el-table-column prop="remarks" label="备注" align="center" />
      <el-table-column prop="sysOrigin" label="系统" 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="语言" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.language == 'ar'">阿拉伯语</span>
          <span v-if="scope.row.language == 'tr'">土耳其语</span>
          <span v-if="scope.row.language != 'ar' && scope.row.language != 'tr' && scope.row.language != ''">其他语言</span>
          <span v-if="scope.row.language == ''" />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" align="center" />
      <el-table-column prop="content" label="内容" align="center" />
      <el-table-column label="执行时间" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.days != null ? '每月' + scope.row.days + '号' : '每天' }} {{ scope.row.hours }}时 {{ scope.row.minutes }}分</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.shelfStatus == 1" type="success">上架</el-tag>
          <el-tag v-if="scope.row.shelfStatus == 0" type="danger">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" @click.native="handleDelete(scope.row.id)">删除</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="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="65%"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item prop="remarks" label="备注">
            <el-input v-model="form.remarks" placeholder="给后台人员看的描述信息" maxlength="200" />
          </el-form-item>
          <el-form-item prop="title" label="Push标题">
            <el-input v-model="form.title" placeholder="最多输入200字" maxlength="200" />
          </el-form-item>
          <el-form-item prop="content" label="Push内容">
            <el-input v-model="form.content" type="textarea" placeholder="最多输入500字" maxlength="1000" />
          </el-form-item>
          <el-form-item label="系统" 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="客户端" prop="platform">
            <el-select v-model="form.platform" clearable placeholder="全部">
              <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="推送平台" 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="语言" prop="language">
            <el-select v-model="form.language" clearable placeholder="请选择语言">
              <el-option label="阿拉伯语" value="ar" />
              <el-option label="土耳其语" value="tr" />
              <el-option label="其他语言" value="en" />
            </el-select>
          </el-form-item>
          <el-form-item label="业务场景" prop="businessScene">
            <el-select v-model="form.businessScene">
              <el-option label="官方通知" value="OFFICIAL_MESSAGE_NOTICE" />
            </el-select>
          </el-form-item>
          <el-form-item label="定投UID" prop="fixedUserIds">
            <el-input v-model.trim="form.fixedUserIds" type="textarea" placeholder="请输入定投用户ID多个以逗号分隔 123,321" @blur="fixedUserIdBlur" @input="fixedUserIdKeyup" />
            <div class="font-info">{{ inputFixedNumber }}/100 定投会忽略 "语言" 过滤条件参数</div>
          </el-form-item>
          <el-form-item label="状态" prop="shelfStatus">
            <el-select v-model="form.shelfStatus">
              <el-option
                v-for="item in shelfStatusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执行时间">
            <el-row class="demo-autocomplete">
              <el-col :span="3">
                <el-input v-model="form.days" placeholder="几号(可空)" />
              </el-col>
              <el-col :span="3">
                <el-input v-model="form.hours" placeholder="几时(必填项)" />
              </el-col>
              <el-col :span="3">
                <el-input v-model="form.minutes" placeholder="几分(必填项)" />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit()">保存</el-button>
            <el-button @click="handleClose()">取消</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'

export default {
  components: { Pagination },
  data() {
    return {
      pickerOptions,
      appPlatforms,
      textOptTitle: '',
      formVisible: false,
      deviceTypes,
      sysOriginPlatforms,
      messageBusinessScene,
      userTypes,
      shelfStatusList: [
        { value: false, name: '下架' },
        { value: true, name: '上架' }
      ],
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        shelfStatus: '',
        sysOrigin: ''
      },
      listLoading: true,
      form: {
        id: '',
        title: '',
        sysOrigin: '',
        content: '',
        businessScene: 'OFFICIAL_MESSAGE_NOTICE',
        platform: '',
        fixedUserIds: '',
        origin: '',
        language: '',
        deviceType: '',
        remarks: '',
        shelfStatus: '',
        days: '',
        hours: '',
        minutes: ''
      },
      rules: {
        hours: [
          { required: true, message: '请输入小时', trigger: 'blur' },
          { min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur' }
        ],
        minutes: [
          { required: true, message: '请输入分钟', trigger: 'blur' },
          { min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' }
        ],
        sysOrigin: { required: true, message: '请选择系统', trigger: 'blur' },
        deviceType: { required: true, message: '请选择推送平台', trigger: 'blur' },
        platform: { required: true, message: '请选择平台', trigger: 'blur' },
        shelfStatus: { required: true, message: '请选择状态', trigger: 'blur' }
      },
      inputFixedNumber: 0
    }
  },
  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() {
      const that = this
      that.inputFixedNumber = 0
      that.resetForm()
      that.formVisible = true
    },
    handleSearch() {
      this.renderData()
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true
      this.thatSelectedUserId = row.id
    },
    handleUpdate(row) {
      const that = this
      that.inputFixedNumber = 0
      that.form = row
      that.formVisible = true
    },
    handleDelete(id) {
      const that = this
      that.$confirm('确定删除任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePushTask(id).then(res => {
          that.$message({
            type: 'success',
            message: 'Successful'
          })
          that.resetForm()
          this.renderData()
        }).catch(er => {
          that.$opsMessage.success()
        })
      }).catch(() => {
        that.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    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: 'Successful'
            })
            that.resetForm()
            that.formVisible = false
            this.renderData()
          } else {
            that.$opsMessage.fail(res.errorMsg)
          }
        }).catch(er => {
          that.$opsMessage.success()
        })
      })
    },
    fixedUserIdBlur(value) {
      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
      var 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 = {
        id: '',
        title: '',
        sysOrigin: '',
        content: '',
        businessScene: 'OFFICIAL_MESSAGE_NOTICE',
        platform: '',
        fixedUserIds: '',
        origin: '',
        language: '',
        deviceType: '',
        remarks: '',
        shelfStatus: '',
        days: '',
        hours: '',
        minutes: ''
      }
    },
    fixedUserIdKeyup(value) {
      if (!value) {
        this.inputFixedNumber = 0
        return
      }
      var contentArrays = value.split(',')
      if (contentArrays.length > 100) {
        var list = this.filterUserIds(contentArrays, 100)
        this.form.fixedUserIds = list.join(',')
        this.inputFixedNumber = list.length
        return
      }
      this.inputFixedNumber = contentArrays.length
    }
  }
}
</script>
