<template>
  <div class="main-content">
    <!-- filter -->
    <el-form
      ref="filterForm"
      :inline="true"
      :model="filterForm"
      class="filter"
    >
      <el-form-item
        label="分享类型"
        prop="shareType"
      >
        <el-select
          v-model="filterForm.shareType"
          placeholder="请选择分享类型"
        >
          <el-option
            v-for="(item, index) in shareTypes"
            :key="index"
            :label="`${item.value}(${item.key})`"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="类型"
        prop="type"
      >
        <el-select
          v-model="filterForm.type"
          placeholder="请选择类型"
        >
          <el-option
            label="分享优先"
            :value="0"
          />
          <el-option
            label="广告优先"
            :value="1"
          />
          <el-option
            label="只分享"
            :value="2"
          />
          <el-option
            label="只广告"
            :value="3"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="search"
        >查询</el-button>
        <el-button @click="reset('filterForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- toolbar -->
    <div class="toolbar clearfix">
      <div class="l fl">
        <el-button
          v-if="permEdit"
          type="primary"
          @click="addShare"
        >新增</el-button>
        <el-button
          @click="switchData"
          type="success"
        >{{ switchText }}</el-button>
        <el-button
          v-if="batch.show && permPublish && isDev"
          type="warning"
          @click="batchPublish"
        >批量发布</el-button>
        <el-button
          v-if="batch.show && permEdit"
          type="danger"
          @click="batchDel"
        >批量删除</el-button>
        <el-button
          v-if="permEdit"
          @click="batchOpt"
        >{{ batch.txt }}</el-button>

      </div>
      <div class="r fr">
        <el-button
          type="primary"
          @click="refreshData"
        >刷新</el-button>
      </div>
    </div>
    <!-- table -->
    <el-alert
      title="当前数据为【正式】数据！"
      v-if="!isDev"
      type="warning"
      class="mgt-20 mgb-20 w100"
      effect="dark"
    />
    <el-table
      v-loading="isLoaded"
      :data="tableData"
      style="width: 100%"
      class="table mgt-20 mgb-20"
      @selection-change="tableSelectionChange"
      @row-click="rowClick"
    >
      <el-table-column
        v-if="batch.show"
        type="selection"
        width="55"
      />
      <el-table-column
        prop="gameName"
        label="游戏"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        prop="typeName"
        label="分享类型"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        prop="type"
        label="类型"
        show-overflow-tooltip
        sortable
        :formatter="formatType"
      />
      <el-table-column
        label="分享图"
        show-overflow-tooltip
        sortable
        width="260"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.type === 3">无</span>
          <div v-else>
            <img
              :src="scope.row.share_image"
              width="30"
              height="30"
              style="vertical-align: middle"
            />
            <span>{{ scope.row.share_word }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="ad_id"
        label="广告ID"
        show-overflow-tooltip
        sortable
      />
      <el-table-column
        prop="default_share"
        label="默认分享"
        show-overflow-tooltip
        sortable
        :formatter="formatDefault"
      />
      <el-table-column
        prop="areaName"
        label="地域"
        show-overflow-tooltip
        sortable
        :formatter="formatArea"
      />
      <el-table-column
        prop="sex"
        label="性别"
        show-overflow-tooltip
        sortable
        :formatter="formatSex"
      />
      <el-table-column
        prop="published"
        label="已发布"
        show-overflow-tooltip
        sortable
        :formatter="formPublished"
      />
      <el-table-column
        prop="name"
        label="操作"
        fixed="right"
        width="126"
      >
        <template slot-scope="scope">

          <el-button
            v-if="permView"
            type="text"
            size="small"
            @click.stop="editShare(scope.row)"
          >详情</el-button>
          <el-button
            v-if="isDev && permPublish"
            type="text"
            size="small"
            @click.stop="publishShare(scope.row)"
          >发布</el-button>
          <el-button
            v-if="(isDev && permEdit) || (!isDev && permPublish)"
            type="text"
            size="small"
            @click.stop="delShare(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination -->
    <el-pagination
      class="al-r"
      layout="total, sizes, prev, pager, next, jumper"
      :hide-on-single-page="true"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import { getShareList, getShareTypes, delShares, saveShare } from '@/api/share'
import { getGame } from '@/api/games'
import { mapGetters } from 'vuex'
import getPageTitle from '@/utils/get-page-title'

export default {
  name: 'GameDetailShare',
  data() {
    return {
      // common
      uid: '',
      permView: false,
      permEdit: false,
      permPublish: false,
      gameInfo: {},
      isDev: true,
      // filter
      shareTypes: [],
      filterForm: {
        shareType: '',
        type: ''
      },
      //  toolbar
      batch: {
        show: false,
        txt: '批量操作'
      },
      switchText: '获取正式数据',
      //   table
      tableData: [],
      isLoaded: false,
      multipleSelection: [],
      // pagination
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    this.uid = this.$route.params.uid
    if (!this.uid || this.uid === 'new') {
      this.$router.push('/games/details/new/info')
    } else {
      this.getGameInfo(this.getData)
      this.getShareTypes()
    }
    this.permEdit =
      this.userInfo.permissions.includes(`${this.uid}-edit`) ||
      this.userInfo.permissions.includes(`${this.uid}-publish`) ||
      this.userInfo.permissions.includes(`games-writeable`)
    this.permView =
      this.userInfo.permissions.includes(`${this.uid}-readable`) ||
      this.userInfo.permissions.includes(`${this.uid}-edit`) ||
      this.userInfo.permissions.includes(`${this.uid}-publish`) ||
      this.userInfo.permissions.includes(`games-writeable`)
    this.permPublish =
      this.userInfo.permissions.includes(`${this.uid}-publish`) ||
      this.userInfo.permissions.includes(`games-writeable`)
  },
  methods: {
    // common
    getGameInfo(cb) {
      getGame({ uid: this.uid })
        .then(res => {
          const { data } = res
          if (data.errcode === 0) {
            this.gameInfo = data.gameInfo
            this.$route.meta.title = this.gameInfo.game_name
            document.title = getPageTitle(this.gameInfo.game_name)
            if (cb && cb instanceof Function) cb()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // filter
    getShareTypes() {
      getShareTypes()
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.shareTypes = data.records
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    search() {
      this.currentPage = 1
      this.getData()
    },
    reset(formName) {
      this.$refs[formName].resetFields()
    },
    // toolbar
    refreshData() {
      this.currentPage = 1
      this.getData()
    },
    addShare() {
      this.$router.push(`/games/details/${this.uid}/share/edit?id=new`)
    },
    batchDel() {
      this.$confirm(
        `是否删除所选${this.multipleSelection.length}条分享图？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const ids = this.multipleSelection.map(item => {
            return item._id
          })

          delShares({
            ids: ids,
            isDev: this.isDev
          }).then(res => {
            const { data } = res
            if (data.errcode === 0) {
              this.$message.success('删除成功！')
            }
            this.refreshData()
          })
        })
        .catch(() => {
          this.$notify.info({
            title: '消息',
            message: '已取消删除'
          })
        })
    },
    batchPublish() {
      this.$confirm(
        `是否发布所选${this.multipleSelection.length}条分享图？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const submitArr = []
          this.multipleSelection.map(row => {
            const devData = JSON.parse(JSON.stringify(row))
            const proData = JSON.parse(JSON.stringify(row))
            devData.isDev = true
            devData.published = true

            proData.isDev = false
            proData.published = true

            submitArr.push(this.saveShare(devData))
            submitArr.push(this.saveShare(proData))
          })
          Promise.all(submitArr)
            .then(() => {
              this.$message.success('分享图发布成功!')
              this.getData()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$notify.info({
            title: '消息',
            message: '已取消发布'
          })
        })
    },
    batchOpt() {
      this.batch.show = !this.batch.show
      this.batch.txt = this.batch.show ? '关闭' : '批量操作'
    },
    switchData() {
      this.isDev = !this.isDev
      this.isDev
        ? (this.switchText = '获取正式数据')
        : (this.switchText = '获取测试数据')
      this.currentPage = 1
      this.reset('filterForm')
      this.getData()
    },
    // table
    getData() {
      this.isLoaded = true
      getShareList({
        uid: this.uid,
        shareType: this.filterForm.shareType,
        type: this.filterForm.type,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        gameId: this.gameInfo.game_id,
        isDev: this.isDev
      })
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.tableData = data.records
            this.total = data.total
            this.isLoaded = false
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    formatDefault(row, column, cellValue, index) {
      return cellValue ? '是' : '否'
    },
    formatType(row, column, cellValue, index) {
      if (cellValue === 0) {
        return '分享优先'
      } else if (cellValue === 1) {
        return '广告优先'
      } else if (cellValue === 2) {
        return '只分享'
      } else if (cellValue === 3) {
        return '只广告'
      }
    },
    formatSex(row, column, cellValue, index) {
      if (cellValue === '0') {
        return '不指定'
      } else if (cellValue === '1') {
        return '男'
      } else if (cellValue === '2') {
        return '女'
      }
    },
    formatArea(row, column, cellValue, index) {
      return cellValue ? cellValue : '不指定'
    },
    formPublished(row, column, cellValue, index) {
      return cellValue === true ? '是' : '否'
    },
    delShare(row) {
      this.$confirm('是否删除该分享图?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delShares({
            ids: [row._id],
            uid: this.uid,
            isDev: this.isDev
          })
            .then(res => {
              const data = res.data
              if (data.errcode === 0) {
                this.$message.success('删除成功')
                this.refreshData()
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    saveShare(data) {
      return new Promise((resolve, reject) => {
        saveShare(data)
          .then(res => {
            const data = res.data
            data.errcode === 0 ? resolve(data) : reject()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    publishShare(row) {
      const submitArr = []
      const devData = JSON.parse(JSON.stringify(row))
      const proData = JSON.parse(JSON.stringify(row))
      devData.isDev = true
      devData.published = true

      proData.isDev = false
      proData.published = true

      submitArr.push(this.saveShare(devData))
      submitArr.push(this.saveShare(proData))

      Promise.all(submitArr)
        .then(() => {
          this.$message.success('分享图发布成功!')
          this.getData()
        })
        .catch(err => {
          console.log(err)
        })
    },
    tableSelectionChange(val) {
      this.multipleSelection = val
    },
    editShare(row) {
      const dataType = this.isDev ? 'dev' : 'pro'
      this.$router.push(
        `/games/details/${this.uid}/share/edit?id=${
          row._id
        }&data_type=${dataType}`
      )
    },
    rowClick(row, column, event) {
      const dataType = this.isDev ? 'dev' : 'pro'
      this.$router.push(
        `/games/details/${this.uid}/share/edit?id=${
          row._id
        }&data_type=${dataType}`
      )
    },
    // pagination
    sizeChange(val) {
      this.pageSize = val
      this.getData()
    },
    pageChange(val) {
      this.currentPage = val
      this.getData()
    }
  }
}
</script>
