<template>
  <div class="main-content p-game-share-add">
    <el-alert
      title="当前数据为【正式】数据！"
      type="warning"
      class="mgb-20"
      effect="dark"
      style="width: 60%"
      v-if="!isDev"
    />
    <el-form
      ref="shareForm"
      :model="shareForm"
      :rules="shareFormRules"
      label-width="120px"
      style="width: 60%"
    >
      <el-form-item
        label="游戏名称"
        prop="name"
      >
        <el-input
          v-model="gameInfo.game_name"
          disabled
        />
      </el-form-item>
      <el-form-item
        label="分享类型"
        prop="share_type"
      >
        <el-select
          v-model="shareForm.share_type"
          placeholder="请选择分享类型"
          style="width: 100%"
          @change="changeShareType"
        >
          <el-option
            v-for="(item, index) in shareTypes"
            :key="index"
            :label="`${item.value}(${item.key})`"
            :value="item.key"
          />
        </el-select>
        <el-button
          v-if="permEdit"
          size="mini"
          @click="modalShareTypeVisible = true"
        >编辑分享类型</el-button>
      </el-form-item>
      <el-form-item
        label="默认分享"
        prop="default_share"
      >
        <el-switch v-model="shareForm.default_share" />
        <span class="ipt-tip">设为默认分享, 那么在遇到该分享类型下没有满足条件的分享图,
          会使用该分享图, 一种分享类型下只能有一条默认分享记录.
          将当前记录变成默认分享后,
          将移除这个游戏同分享类型下其他分享图的默认分享属性。</span>
      </el-form-item>

      <el-form-item
        label="地域"
        prop="area"
      >
        <el-select
          v-model="shareForm.area"
          placeholder="请选择地域"
          style="width: 100%"
        >
          <el-option
            label="不指定地域"
            :value="null"
          >不指定地域</el-option>
          <el-option
            v-for="(item, index) in areas"
            :key="index"
            :label="item.name"
            :value="item._id"
          />
        </el-select>
        <el-button
          v-if="permEdit"
          size="mini"
          @click="modalAreaVisible = true"
        >编辑地域</el-button>
      </el-form-item>
      <el-form-item
        label="性别"
        prop="sex"
      >
        <el-radio-group v-model="shareForm.sex">
          <el-radio label="0">不指定</el-radio>
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="优先级"
        prop="type"
      >
        <el-radio-group
          v-model="shareForm.type"
          @change="changeType"
        >
          <el-radio :label="0">分享优先</el-radio>
          <el-radio :label="1">广告优先</el-radio>
          <el-radio :label="2">只分享</el-radio>
          <el-radio :label="3">只广告</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="!onlyAd">
        <el-form-item
          label="分享次数"
          prop="share_count"
        >
          <el-input v-model.number="shareForm.share_count" />
          <span class="ipt-tip">分享首先的情况下, 分享n次后, 将切换成广告, 0代表不限次数。</span>
        </el-form-item>
        <el-form-item
          label="分享组"
          prop="share_word"
        >
          <el-row
            v-for="(item, index) in shareGroups"
            :key="index"
            class="share-group"
            type="flex"
            align="middle"
            :gutter="16"
          >
            <el-col :span="2">
              <div class="img-box">
                <img
                  class="img img-fit"
                  :src="item.share_image"
                />
              </div>
            </el-col>
            <el-col :span="14">
              <div class="txt ell">{{ item.share_word }}</div>
            </el-col>
            <el-col :span="6">
              <el-button
                v-if="permEdit"
                type="primary"
                size="mini"
                @click="editShareGroup(item, index)"
              >编辑</el-button>
              <el-button
                v-if="permEdit"
                type="danger"
                size="mini"
                @click="delShareGroup(index)"
              >删除</el-button>
            </el-col>
          </el-row>
          <el-button
            v-if="permEdit"
            size="mini"
            @click="addShareGroup"
          >添加分享语</el-button>
        </el-form-item>

      </div>
      <div v-if="!onlyShare">
        <el-form-item
          label="广告 ID"
          prop="ad_id"
        >
          <el-input v-model="shareForm.ad_id" />
        </el-form-item>
        <el-form-item
          label="广告次数"
          prop="ad_count"
        >
          <el-input v-model.number="shareForm.ad_count" />
          <span class="ipt-tip">广告首先的情况下, 最多播放广告n次后, 将切换成分享, 暂时无用。</span>
        </el-form-item>
        <el-form-item
          label="广告播放间隔"
          prop="ad_cd"
        >
          <el-input v-model.number="shareForm.ad_cd" />
          <span class="ipt-tip">点击广告的间隔时间, 暂时无用。</span>
        </el-form-item>
      </div>

      <el-form-item
        label="备注"
        prop="comment"
      >
        <el-input
          v-model="shareForm.comment"
          type="textarea"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="permEdit"
          type="primary"
          @click="save"
        >保存</el-button>
        <el-button
          v-if="permPublish"
          type="warning"
          @click="publish"
        >发布</el-button>
        <el-button
          v-if="permEdit"
          type="success"
          @click="restore"
        >重置</el-button>
        <el-button
          v-if="permEdit"
          @click="resetForm('shareForm')"
        >清空</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
    <!-- Modal - 编辑分享类型 -->
    <el-dialog
      title="分享类型列表"
      :visible.sync="modalShareTypeVisible"
      width="35%"
    >
      <el-button
        v-if="permEdit"
        type="primary"
        @click="addShareType"
      >新增</el-button>
      <el-table
        :data="shareTypes"
        style="width: 100%"
        class="table mgt-20 mgb-20"
        height="350"
        size="mini"
      >
        <el-table-column
          prop="key"
          label="key"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          prop="value"
          label="说明"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          v-if="permEdit"
          prop="name"
          label="操作"
          fixed="right"
          width="126"
        >
          <template slot-scope="scope">
            <el-button
              v-if="permEdit"
              type="text"
              size="small"
              @click="editShareType(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="permEdit"
              type="text"
              size="small"
              @click="delShareType(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="modalShareTypeVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- Modal - 编辑分享类型 - 新增/编辑 -->
    <el-dialog
      title="编辑分享类型"
      :visible.sync="modalShareTypeEditVisible"
      append-to-body
      :before-close="closeShareTypeEditModal"
      width="35%"
    >
      <el-form
        ref="shareTypeForm"
        :model="shareTypeForm"
        :rules="shareTypeFormRules"
        label-width="50px"
      >
        <el-form-item
          label="key"
          prop="key"
        >
          <el-input v-model="shareTypeForm.key" />
        </el-form-item>
        <el-form-item
          label="说明"
          prop="value"
        >
          <el-input v-model="shareTypeForm.value" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeShareTypeEditModal">取 消</el-button>
        <el-button
          v-if="permEdit"
          type="primary"
          @click="saveShareType"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- Modal - 编辑地域 -->
    <el-dialog
      title="地域列表"
      :visible.sync="modalAreaVisible"
      width="35%"
    >
      <el-button
        v-if="permEdit"
        type="primary"
        @click="addArea"
      >新增</el-button>
      <el-table
        :data="areas"
        style="width: 100%"
        class="table mgt-20 mgb-20"
        size="mini"
        height="350"
      >
        <el-table-column
          prop="name"
          label="名称"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          v-if="permEdit"
          prop="name"
          label="操作"
          fixed="right"
          width="126"
        >
          <template slot-scope="scope">
            <el-button
              v-if="permEdit"
              type="text"
              size="small"
              @click="editArea(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="permEdit"
              type="text"
              size="small"
              @click="delArea(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
        <el-button @click="modalAreaVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- Modal - 编辑地域 - 新增/编辑 -->
    <el-dialog
      title="编辑地域"
      :visible.sync="modalAreaEditVisible"
      append-to-body
      :before-close="closeModalAreaEdit"
      width="35%"
    >
      <el-form
        ref="areaForm"
        :model="areaForm"
        :rules="areaFormRules"
        label-width="50px"
      >
        <el-form-item
          label="说明"
          prop="name"
        >
          <el-input v-model="areaForm.name" />
        </el-form-item>
        <el-form-item label="地区">
          <el-scrollbar
            style="height: 350px;"
            class="scrollbar"
          >
            <el-tree
              ref="tree"
              :data="regions"
              show-checkbox
              :props="{ label: 'text' }"
              node-key="id"
            />
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeModalAreaEdit">取 消</el-button>
        <el-button
          v-if="permEdit"
          type="primary"
          @click="saveArea"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- Modal - 分享语 -->
    <el-dialog
      title="编辑分享语"
      :visible.sync="modalShareGroupVisible"
      width="500px"
      :before-close="closeModalShareGroup"
    >
      <el-form
        ref="shareGroupForm"
        :model="shareGroupForm"
        :rules="shareGroupFormRules"
        label-width="100px"
      >
        <el-form-item
          label="分享图"
          prop="share_image"
          class="uploader-box"
        >
          <el-upload
            class="uploader"
            action="/api/common/upload"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadErr"
            :headers="{
              authorization: 'Bearer ' + token
            }"
            name="image-file"
            :data="{
              sub_path: '/share-images/',
              file_type: 'share_images'
            }"
          >
            <img
              v-if="shareGroupForm.share_image"
              :src="shareGroupForm.share_image"
              class="uploader-img"
            />
            <i
              v-else
              class="el-icon-plus uploader-icon"
            />
          </el-upload>
        </el-form-item>
        <el-form-item
          label="分享语"
          prop="share_word"
        >
          <el-input v-model="shareGroupForm.share_word" />
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeModalShareGroup">取 消</el-button>
        <el-button
          v-if="permEdit"
          type="primary"
          @click="saveShareGroup"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getShareTypes,
  saveShareType,
  delShareType,
  getShare,
  saveShare,
  updateShare,
  getShareList
} from '@/api/share'
import { getGame } from '@/api/games'
import { getRegions, saveArea, getAreas, delArea } from '@/api/common'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import getPageTitle from '@/utils/get-page-title'
import { Promise, reject } from 'q'

export default {
  name: 'GameDetailsShareEdit',
  data() {
    return {
      // common
      uid: '',
      isDev: false,
      permEdit: false,
      permPublish: false,
      gameInfo: {},
      shareTypes: [],
      regions: [],
      areas: [],
      token: '',
      onlyShare: false,
      onlyAd: false,
      curShareType: '',
      selectedShareType: [],
      // main
      shareForm: {
        default_share: false,
        share_images: [],
        share_words: [],
        share_count: 0,
        ad_count: 0,
        ad_cd: 0,
        type: 0,
        game_id: '',
        share_type: '',
        share_image: '',
        share_word: '',
        sex: '0',
        area: null,
        comment: '',
        ad_id: ''
      },
      shareFormRules: {
        default_share: [
          { required: true, message: '请选择是否默认分享', trigger: 'blur' }
        ],
        share_count: [
          { required: true, message: '请输入分享次数', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        ad_count: [
          {
            required: true,
            message: '请输入广告次数',
            trigger: 'blur'
          },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        ad_cd: [
          {
            required: true,
            message: '请输入广告播放间隔',
            trigger: 'blur'
          },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        ad_id: [
          {
            required: true,
            message: '请输入广告ID',
            trigger: 'blur'
          }
        ],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        share_type: [
          { required: true, message: '请选择分享类型', trigger: 'blur' }
        ],
        share_word: [
          { required: true, message: '请至少添加一个分享组', trigger: 'blur' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }]
      },
      imageUrl: '',
      // modal - shareType
      modalShareTypeVisible: false,
      shareTypeList: [],
      // modal - shareTypeEdit
      modalShareTypeEditVisible: false,
      shareTypeForm: {
        key: '',
        value: ''
      },
      shareTypeFormRules: {
        key: [{ required: true, message: '请输入key', trigger: 'blur' }],
        value: [{ required: true, message: '请输入说明', trigger: 'blur' }]
      },
      // modal - area
      modalAreaVisible: false,
      areaList: [],
      // modal - areaEdit
      modalAreaEditVisible: false,
      areaForm: {},
      areaFormRules: {
        name: [{ required: true, message: '请输入地域描述', trigger: 'blur' }]
      },
      // modal - shareGroup
      shareGroups: [],
      modalShareGroupVisible: false,
      shareGroupForm: {},
      shareGroupFormRules: {
        share_word: [
          { required: true, message: '请输入分享语', trigger: 'blur' }
        ],
        share_image: [
          { required: true, message: '请上传分享图', trigger: 'blur' }
        ]
      },
      isNewGroup: true,
      groupIndex: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    this.uid = this.$route.params.uid
    this.isDev = this.$route.query.data_type === 'dev' ? true : false
    if (!this.uid || this.uid === 'new') {
      this.$router.push('/games/details/new/info')
    } else {
      this.getGameInfo()
      this.getShareTypes()
      this.getRegions()
      this.getAreas()
      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`)
  },
  methods: {
    // common
    getGameInfo() {
      getGame({ uid: this.uid })
        .then(res => {
          const { data } = res
          if (data.errcode === 0) {
            this.gameInfo = data.gameInfo
            this.shareForm.game_id = this.gameInfo.game_id
            this.$route.meta.title = this.gameInfo.game_name
            document.title = getPageTitle(this.gameInfo.game_name)
            if (this.$route.query.id && this.$route.query.id !== 'new') {
              this.getShare()
            }
            this.getShareList()
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getShareTypes() {
      getShareTypes()
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.shareTypes = data.records
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getRegions() {
      getRegions()
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.regions = data.records
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getAreas() {
      getAreas()
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.areas = data.records
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getShare() {
      getShare({
        id: this.$route.query.id,
        game_id: this.gameInfo.game_id,
        uid: this.uid,
        data_type: this.$route.query.data_type
      })
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.shareForm = data.record
            for (let i = 0; i < this.shareForm.share_images.length; i++) {
              this.shareGroups.push({
                share_word: this.shareForm.share_words[i],
                share_image: this.shareForm.share_images[i]
              })
            }
            if (!this.shareForm.area) this.shareForm.area = null
            this.curShareType = this.shareForm.share_type
            if (this.shareForm.type === 2) this.onlyShare = true
            if (this.shareForm.type === 3) this.onlyAd = true
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getShareList() {
      getShareList({
        uid: this.uid,
        gameId: this.gameInfo.game_id
      })
        .then(res => {
          const data = res.data
          if (data.errcode === 0) {
            this.selectedShareType = data.records.map(item => {
              return item.share_type
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    changeType(val) {
      if (val === 2) {
        this.onlyShare = true
        this.onlyAd = false
      } else if (val === 3) {
        this.onlyShare = false
        this.onlyAd = true
      } else {
        this.onlyShare = false
        this.onlyAd = false
      }
    },
    changeShareType(val) {
      if (this.selectedShareType.includes(val) && this.curShareType !== val) {
        this.shareForm.share_type = ''
        this.$message.error('已有此分享类型，请选择其他分享类型！')
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.shareForm.uid = this.uid
          if (!this.shareForm._id) {
            saveShare(this.shareForm)
              .then(res => {
                const data = res.data
                if (data.errcode === 0) {
                  this.$message.success('分享图保存成功！')
                  this.$router.push(
                    `/games/details/${this.uid}/share/edit?id=${
                      data.result._id
                    }`
                  )
                }
              })
              .catch(err => {
                console.log(err)
              })
          } else if (this.shareForm._id) {
            updateShare(this.shareForm)
              .then(res => {
                const data = res.data
                if (data.errcode === 0) {
                  this.$message.success('分享图更新成功！')
                  this.$refs['shareForm'].clearValidate()
                  this.curShareType = this.shareForm.share_type
                  this.getShareList()
                }
              })
              .catch(err => {
                console.log(err)
              })
          }
        } else {
          this.$message.error('请按要求填写表单！')
        }
      })
    },
    validateForm(formName) {
      return new Promise((resolve, reject) => {
        this.$refs[formName].validate(valid => {
          valid ? resolve() : reject()
        })
      })
    },
    resetForm(formName) {
      this.shareForm.share_words = []
      this.shareForm.share_images = []
      this.shareGroups = []
      this.$refs[formName].resetFields()
    },
    formatterShareForm() {
      if (!this.onlyAd && this.shareGroups.length > 0) {
        this.shareForm.share_word = this.shareGroups[0].share_word
        this.shareForm.share_image = this.shareGroups[0].share_image
        this.shareForm.share_words = []
        this.shareForm.share_images = []
        for (let i = 0; i < this.shareGroups.length; i++) {
          this.shareForm.share_words.push(this.shareGroups[i].share_word)
          this.shareForm.share_images.push(this.shareGroups[i].share_image)
        }
      }

      if (this.onlyShare) {
        this.shareForm.ad_count = 0
        this.shareForm.ad_cd = 0
        this.shareForm.ad_id = ''
      }
      if (this.onlyAd) {
        this.shareForm.share_images = []
        this.shareForm.share_words = []
        this.shareForm.share_word = ''
        this.shareForm.share_image = ''
      }
    },
    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)
          })
      })
    },
    updateShare(data) {
      return new Promise((resolve, reject) => {
        updateShare(data)
          .then(res => {
            const data = res.data
            data.errcode === 0 ? resolve(data) : reject()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    save() {
      this.formatterShareForm()
      this.validateForm('shareForm')
        .then(() => {
          const data = this.shareForm
          data.isDev = true
          data.published = false
          this.saveShare(data)
            .then(data => {
              const shareId =
                this.$route.query.id && this.$route.query.id !== 'new'
                  ? this.$route.query.id
                  : data.result._id
              this.$message.success('分享图保存成功！')
              this.$refs['shareForm'].clearValidate()
              this.$router.push(
                `/games/details/${
                  this.uid
                }/share/edit?id=${shareId}&data_type=dev`
              )
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message.error('请按要求填写表单!')
        })
    },
    publish() {
      this.formatterShareForm()
      this.validateForm('shareForm')
        .then(() => {
          const submitArr = []
          const devData = JSON.parse(JSON.stringify(this.shareForm))
          const proData = JSON.parse(JSON.stringify(this.shareForm))
          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.$refs['shareForm'].clearValidate()
              this.$message.success('分享图发布成功!')
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message.error('请按要求填写表单!')
        })
    },
    goBack() {
      this.$router.push(`/games/details/${this.uid}/share`)
    },
    restore() {
      if (this.$route.query.data_type === 'pro') {
        this.$router.go(0)
      } else {
        this.$router.push(
          `/games/details/${this.uid}/share/edit?id=${
            this.$route.query.id
          }&data_type=pro`
        )
      }
    },
    // modal - 编辑分享类型
    addShareType() {
      this.shareTypeForm = {
        key: '',
        value: ''
      }
      this.openShareTypeEditModal()
    },
    editShareType(row) {
      this.shareTypeForm = JSON.parse(JSON.stringify(row))
      this.openShareTypeEditModal()
    },
    delShareType(row) {
      this.$confirm('是否要删除该分享类型?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delShareType({ id: row._id })
            .then(res => {
              const { data } = res
              if (data.errcode === 0) {
                this.$message.success('分享类型删除成功！')
                this.getShareTypes()
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    openShareTypeEditModal() {
      this.modalShareTypeEditVisible = true
    },
    closeShareTypeEditModal() {
      this.modalShareTypeEditVisible = false
      this.$refs['shareTypeForm'].clearValidate()
    },
    saveShareType() {
      this.$refs['shareTypeForm'].validate(valid => {
        if (valid) {
          saveShareType({
            record: {
              id: this.shareTypeForm._id,
              key: this.shareTypeForm.key,
              val: this.shareTypeForm.value
            }
          })
            .then(res => {
              const data = res.data
              if (data.errcode === 0) {
                this.$message.success('分享类型保存成功')
              }
              this.modalShareTypeEditVisible = false
              this.getShareTypes()
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          this.$message.error('请按要求填写表单！')
        }
      })
    },
    // modal - 地域
    addArea() {
      this.openModalAreaEdit()
      this.areaForm = {
        name: ''
      }
      setTimeout(() => {
        this.$refs['tree'].setCheckedKeys([])
      }, 0)
    },
    editArea(row) {
      this.openModalAreaEdit()
      this.areaForm = JSON.parse(JSON.stringify(row))
      const checkedKey = this.areaForm.locations
      setTimeout(() => {
        this.$refs['tree'].setCheckedKeys(checkedKey)
      }, 0)
    },
    delArea(row) {
      this.$confirm('是否要删除该地域?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delArea({ id: row._id })
            .then(res => {
              const { data } = res
              if (data.errcode === 0) {
                this.$message.success('地域删除成功！')
                this.getAreas()
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // modal - 编辑地域
    saveArea() {
      const node = this.$refs.tree.getCheckedNodes()
      const locations = node.map(item => {
        return item.id
      })
      this.$refs['areaForm'].validate(valid => {
        if (valid && node.length > 0) {
          saveArea({
            id: this.areaForm._id,
            name: this.areaForm.name,
            locations: locations
          }).then(res => {
            const data = res.data
            if (data.errcode === 0) {
              this.$message.success('地域保存成功！')
              this.closeModalAreaEdit()
              this.getAreas()
            }
          })
        } else {
          this.$message.error('请按要求填写表单！')
        }
      })
    },
    openModalAreaEdit() {
      this.modalAreaEditVisible = true
    },
    closeModalAreaEdit() {
      this.$refs['areaForm'].clearValidate()
      this.modalAreaEditVisible = false
    },
    // modal - 分享组
    addShareGroup() {
      this.shareGroupForm = {
        share_word: '',
        share_image: ''
      }
      this.isNewGroup = true
      this.openModalShareGroup()
    },
    editShareGroup(group, index) {
      this.shareGroupForm = JSON.parse(JSON.stringify(group))
      this.isNewGroup = false
      this.groupIndex = index
      this.openModalShareGroup()
    },
    delShareGroup(index) {
      this.$confirm('是否要删除该分享组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.shareGroups.splice(index, 1)
          this.$message.success('分享组删除成功！')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    uploadSuccess(res, file) {
      this.shareGroupForm.share_image = res.url
    },
    saveShareGroup() {
      this.$refs['shareGroupForm'].validate(valid => {
        if (valid) {
          if (this.isNewGroup) {
            this.shareGroups.push(this.shareGroupForm)
            this.closeModalShareGroup()
          } else {
            this.shareGroups.splice(this.groupIndex, 1, this.shareGroupForm)
            this.closeModalShareGroup()
          }
        } else {
          this.$message.error('请完整填写表单！')
        }
      })
    },
    uploadErr() {
      this.$message.error('图片上传失败！')
    },
    openModalShareGroup() {
      this.modalShareGroupVisible = true
    },
    closeModalShareGroup() {
      this.$refs['shareGroupForm'].clearValidate()
      this.modalShareGroupVisible = false
    }
  }
}
</script>

<style lang="scss">
.p-game-share-add {
  .share-group {
    margin-bottom: 20px;
    .img-box {
      width: 40px;
      height: 40px;
    }
  }
}
</style>

<style scoped>
.scrollbar >>> .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>

