<template>
  <div class="main-content">
    <el-row>
      <el-col :span="12">
        <div>
          <el-select
            v-model="platform_id"
            @change="changePlatform"
            placeholder="请选择平台"
            class="w100 mgb-20"
          >
            <el-option
              v-for="item in platformsArr"
              :key="item.platform.platform_id"
              :label="item.platform.name"
              :value="item.platform.platform_id"
            />
          </el-select>
          <el-collapse
            v-model="activeNames"
            v-if="allPos.length > 0"
          >
            <el-collapse-item
              :name="index"
              v-for="(item, index) in allPos"
              :key="index"
            >
              <template slot="title">
                <svg-icon
                  style="margin-right: 20px;"
                  icon-class="del"
                  @click.stop="delPos(index)"
                />
                {{ `[${index+1}]广告位：${item.ld_property.title}(${item.id || '暂无ID'})`}}
              </template>
              <el-form
                :ref="`adPos${index}`"
                :model="item"
                :rules="adPosRules"
                style="width: 100%"
                label-width="120px"
                class="mgt-20 mgb-20"
              >
                <el-form-item
                  label="名称"
                  prop="ld_property.title"
                >
                  <el-input
                    v-model.number="item.ld_property.title"
                    style="width: 70%"
                  ></el-input>
                </el-form-item>

                <el-form-item
                  label="区域"
                  prop="area"
                >
                  <el-select
                    v-model="item.area"
                    placeholder="请选择广告投放区域"
                    style="width: 70%"
                    multiple
                  >
                    <el-option
                      v-for="(area, idx) in areaList"
                      :key="idx"
                      :label="`${area.name}(${area.key})`"
                      :value="area.area_id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="类型"
                  prop="type"
                >
                  <el-select
                    v-model="item.type"
                    placeholder="请选择广告类型"
                    style="width: 70%"
                    filterable
                  >
                    <el-option
                      v-for="(type,idx) in typeList"
                      :key="idx"
                      :label="type.name"
                      :value="type.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="模式"
                  prop="mode"
                >
                  <el-select
                    v-model="item.mode"
                    placeholder="请选择广告播放模式"
                    style="width: 70%"
                  >
                    <el-option
                      v-for="(mode,idx) in modeList"
                      :key="idx"
                      :label="mode.name"
                      :value="mode.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="坐标：X"
                  prop="x"
                >
                  <el-input
                    v-model.number="item.x"
                    style="width: 70%"
                  ></el-input>
                  <span class="ipt-tip">广告位中心点坐标x （取值：0~15）</span>
                </el-form-item>
                <el-form-item
                  label="坐标：Y"
                  prop="y"
                >
                  <el-input
                    v-model.number="item.y"
                    style="width: 70%"
                  ></el-input>
                  <span class="ipt-tip">广告位中心点坐标y （取值：0~15）</span>
                </el-form-item>
                <el-form-item
                  label="偏移量：X"
                  prop="offsetX"
                >
                  <el-input
                    v-model.number="item.x_offset"
                    style="width: 70%"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="偏移量：Y"
                  prop="offsetY"
                >
                  <el-input
                    v-model.number="item.y_offset"
                    style="width: 70%"
                  ></el-input>
                </el-form-item>
                <el-form-item label="实际坐标">
                  <span>x: {{perW * item.x + item.x_offset}},y: {{perH * item.y + item.y_offset}}</span>
                </el-form-item>
                <el-form-item
                  label="广告位标题"
                  prop="ld_property.show_name"
                >
                  <el-input
                    v-model="item.ld_property.show_name"
                    style="width: 70%"
                    placeholder="大家都在玩的爆款游戏"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="位置底图"
                  prop="ld_property.bg_img"
                  class="uploader-box"
                >
                  <el-upload
                    class="uploader"
                    action="/api/common/upload"
                    :show-file-list="false"
                    :on-success="
                    (res, file, fileList) => {
                      return uploadSuccess(
                        res,
                        file,
                        fileList,
                        index
                      )
                    }
                  "
                    :on-error="uploadErr"
                    :headers="{
                    authorization: 'Bearer ' + token
                  }"
                    name="image-file"
                    :data="{ sub_path: '/ad_bg/', file_type: 'ad_bg' }"
                  >
                    <img
                      v-if="item.ld_property.bg_img"
                      :src="item.ld_property.bg_img"
                      class="uploader-img"
                    />
                    <i
                      v-else
                      class="el-icon-plus uploader-icon"
                    />
                  </el-upload>
                </el-form-item>
                <el-form-item
                  label="是否抖动"
                  prop="ld_property.is_shake"
                >
                  <el-switch v-model="item.ld_property.is_shake"></el-switch>
                </el-form-item>
                <el-form-item
                  label="是否有红点"
                  prop="ld_property.has_dot"
                >
                  <el-switch v-model="item.ld_property.has_dot"></el-switch>
                </el-form-item>
                <el-form-item
                  label="是否显示广告名"
                  prop="ld_property.is_show_name"
                >
                  <el-switch v-model="item.ld_property.is_show_name"></el-switch>
                </el-form-item>
                <el-form-item
                  label="关闭时隐藏"
                  prop="ld_property.is_hide"
                >
                  <el-switch v-model="item.ld_property.is_hide"></el-switch>
                </el-form-item>
                <el-form-item
                  label="关联广告位"
                  prop="ld_property.related"
                >
                  <el-select
                    v-model="item.ld_property.related"
                    placeholder="关联广告位"
                    style="width: 70%"
                    multiple
                  >
                    <el-option
                      v-for="(pos,idx) in allPos"
                      :key="idx"
                      :label="pos.ld_property.title"
                      :value="pos.id"
                    >
                    </el-option>
                  </el-select>
                  <span class="ipt-tip">关联广告位需选择非自身广告位</span>
                </el-form-item>
                <el-form-item
                  label="缩放比"
                  prop="ld_property.scale"
                >
                  <el-input
                    style="width: 70%"
                    v-model="item.ld_property.scale"
                    placeholder="1"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="全面屏坐标"
                  prop="ld_property.full_screen_coord"
                >
                  <el-input
                    style="width: 70%"
                    v-model="item.ld_property.full_screen_coord"
                    placeholder="x,y,scale"
                  ></el-input>
                  <span class="ipt-tip">全面屏专用坐标，格式“x,y,scale”（x坐标,y坐标,缩放比）</span>
                </el-form-item>

                <el-form-item v-if="platform_id">
                  <el-button
                    type="primary"
                    @click="savePos(index)"
                  >保存</el-button>
                  <el-button
                    type="danger"
                    @click="delPos(index)"
                  >删除</el-button>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>

          <div
            class="tip "
            v-else
          >
            <placeholder />
          </div>

          <div
            class="btn-group"
            v-if="platform_id"
          >
            <el-button
              class="mgt-20 w100"
              @click="addPos"
              v-if="permEdit"
            >新增</el-button>
          </div>
        </div>

      </el-col>
      <el-col :span="12">
        <coordinate
          class="al-c"
          :perW="perW"
          :perH="perH"
        />
      </el-col>
    </el-row>

  </div>
</template>


<script>
import {mapGetters} from 'vuex'
import {getGame} from '@/api/games'
import {getAdPosList, addAdPos, modifyAdPos, delAdPos} from '@/api/ad'
import {getAdAreaList} from '@/api/ad'
import getPageTitle from '@/utils/get-page-title'
import Coordinate from '@/components/Coordinate'
import Placeholder from '@/components/Placeholder'
import {reject, Promise} from 'q'
import {getToken} from '@/utils/auth'

export default {
  name: 'GameDetailsAdPos',
  data() {
    return {
      // common
      uid: '',
      token: '',
      type: 'normal',
      platform_id: '',
      platformsArr: [],
      gameInfo: {},
      permEdit: false,
      permPublish: false,
      hasList: false,
      areaList: {},
      typeList: [
        {
          name: 'icon(1)',
          value: 1,
        },
        {
          name: 'banner(2)',
          value: 2,
        },
        {
          name: '抽屉-普通(0)',
          value: 0,
        },
        {
          name: '抽屉-详细(3)',
          value: 3,
        },
        {
          name: '弹窗-小(5)',
          value: 5,
        },
        {
          name: '弹窗-大(4)',
          value: 4,
        },
        {
          name: '弹窗-超大(10)',
          value: 10,
        },
        {
          name: '滚动-横向(6)',
          value: 6,
        },
        {
          name: '滚动-横向（小）(7)',
          value: 7,
        },
        {
          name: '滚动-竖向(8)',
          value: 8,
        },
        {
          name: '列表(9)',
          value: 9,
        },
      ],
      modeList: [
        {
          name: '单播',
          value: 1,
        },
        {
          name: '轮播',
          value: 2,
        },
      ],
      perW: 0,
      perH: 0,
      // form
      adPos: {},
      adPosRules: {
        'ld_property.title': [
          {required: true, message: '请填写广告位名称', trigger: 'blur'},
        ],
        area: [
          {required: true, message: '请选择广告投放区域', trigger: 'blur'},
        ],
        type: [{required: true, message: '请选择广告类型', trigger: 'blur'}],
        mode: [
          {required: true, message: '请选择广告播放类型', trigger: 'blur'},
        ],
        x: [{required: true, message: '请填写广告中心坐标 X', trigger: 'blur'}],
        y: [{required: true, message: '请填写广告中心坐标 Y', trigger: 'blur'}],
        x_offset: [
          {
            type: 'number',

            message: '偏移量必须是数值',
            trigger: 'blur',
          },
        ],
        y_offset: [
          {
            type: 'number',
            message: '偏移量必须是数值',
            trigger: 'blur',
          },
        ],
      },
      activeNames: [],
      defaultPos: {
        area: '',
        type: '',
        mode: '',
        x: 0,
        y: 0,
        x_offset: 0,
        y_offset: 0,
        ld_property: {
          title: '',
          show_name: '',
          bg_img: '',
          has_dot: false,
          is_shake: false,
          is_hide: true,
          is_show_name: false,
          related: [],
          scale: 1,
          full_screen_coord: ''
        },
      },
      allPos: [],
    }
  },
  components: {
    Coordinate,
    Placeholder,
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  mounted() {
    this.uid = this.$route.params.uid
    this.type = this.$route.query.type ? this.$route.query.type : 'normal'
    this.token = getToken()
    this.permEdit =
      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`)
    this.getGameInfo(this.getAdPosList)
    this.getAdAreaList()
  },
  methods: {
    getGameInfo(cb) {
      getGame({uid: this.uid})
        .then(res => {
          const {data} = res
          if (data.errcode === 0) {
            this.gameInfo = data.gameInfo
            this.platformsArr = data.gameInfo.platforms
            this.$route.meta.title = this.gameInfo.game_name
            document.title = getPageTitle(this.gameInfo.game_name)
            if (this.$route.query.platform_id) {
              this.platform_id = this.$route.query.platform_id
            } else {
              this.platform_id = this.platformsArr[0]
                ? this.platformsArr[0].platform.platform_id
                : ''
            }
            const game_size = this.gameInfo.game_size.split('*')
            this.perW = game_size[0] / 16
            this.perH = game_size[1] / 16
            if (cb && cb instanceof Function) cb()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getAdPosList() {
      getAdPosList({
        uid: this.uid,
        gameid: parseInt(this.gameInfo.game_id),
        channelid: parseInt(this.platform_id),
      })
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.allPos = data.message || []
            this.allPos.map(item => {
              item.area = JSON.parse(item.area)
              item.area = item.area.map(item => parseInt(item))
              item.ld_property = item.ld_property
                ? JSON.parse(item.ld_property)
                : {
                    title: '',
                    show_name: '',
                    bg_img: '',
                    has_dot: false,
                    is_shake: false,
                    is_hide: true,
                    is_show_name: false,
                    related: [],
                    scale: 1,
                    full_screen_coord: ''
                  }
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getAdAreaList() {
      getAdAreaList()
        .then(res => {
          const {data} = res
          if (data.errcode === 0) {
            this.areaList = data.adAreaList
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    changePlatform() {
      this.getAdPosList()
    },
    uploadSuccess(res, file, fileList, index) {
      this.allPos[index].ld_property.bg_img = res.url
    },
    uploadErr() {
      this.$message.error('图片上传失败！')
    },
    addPos() {
      const defaultPos = JSON.parse(JSON.stringify(this.defaultPos))
      this.activeNames.push(this.allPos.length)
      this.allPos.push(defaultPos)
    },
    delPos(index) {
      this.$confirm('是否要删除该广告位?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delAdPos({
            uid: this.uid,
            id: this.allPos[index].id,
          })
            .then(res => {
              const data = res.data
              if (data.errcode === 0) {
                this.$message.success('成功删除广告位！')
                this.allPos.splice(index, 1)
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },
    async savePos(index) {
      const valid = await this.validForm(`adPos${index}`)
      if (valid) {
        const posInfo = JSON.parse(JSON.stringify(this.allPos[index]))

        // if (posInfo.ld_property.related === posInfo.id) {
        //   this.$message.error('关联广告位不可选则自身！')
        //   return
        // }

        posInfo.ld_property.scale = parseFloat(posInfo.ld_property.scale) || 1

        if (this.allPos[index].id) {
          // 更新
          const self = this
          modifyAdPos({
            uid: this.uid,
            area: JSON.stringify(posInfo.area),
            gameid: parseInt(this.gameInfo.game_id),
            channelid: parseInt(this.platform_id),
            id: parseInt(posInfo.id),
            ld_property: JSON.stringify(posInfo.ld_property),
            mode: parseInt(posInfo.mode),
            type: parseInt(posInfo.type),
            x: parseInt(posInfo.x),
            y: parseInt(posInfo.y),
            x_offset: parseInt(posInfo.x_offset),
            y_offset: parseInt(posInfo.y_offset),
          })
            .then(res => {
              const data = res.data
              if (data.errcode === 0) {
                this.$message.success('广告位修改成功！')
                this.$refs[`adPos${index}`][0].clearValidate()
                this.getAdPosList()
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          const self = this

          addAdPos({
            uid: this.uid,
            area: JSON.stringify(posInfo.area),
            gameid: parseInt(this.gameInfo.game_id),
            channelid: parseInt(this.platform_id),
            ld_property: JSON.stringify(posInfo.ld_property),
            mode: parseInt(posInfo.mode),
            type: parseInt(posInfo.type),
            x: parseInt(posInfo.x),
            y: parseInt(posInfo.y),
            x_offset: parseInt(posInfo.x_offset),
            y_offset: parseInt(posInfo.y_offset),
          })
            .then(res => {
              const data = res.data
              if (data.errcode === 0) {
                this.$message.success('广告位新增成功！')
                this.$refs[`adPos${index}`][0].clearValidate()
                this.getAdPosList()
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      } else {
        this.$message.error('请按要求填写表单！')
      }
    },

    validForm(formName) {
      return new Promise((resolve, reject) => {
        this.$refs[formName][0].validate(valid => {
          valid ? resolve(true) : reject()
        })
      })
    },
  },
}
</script>


<style scoped>
.btn-group >>> .el-button + .el-button {
  margin-left: 0;
}
</style>


