<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" @click="confirm" :loading="confirmLoading" :priv="positionID>0 ? `AdvertiseManage.Edit.${positionID}`:'AdvertiseManage.Add'"><i class="fa fa-save"></i>保存</el-button>
      <el-button @click="preview" v-if="positionID>0" v-show="tmpAdvertisePosition.positionType !== 'video'">
        <i class="fa fa-eye"></i>预览
      </el-button>
      <el-button @click="commitAudit" :priv="'AdvertiseManage.CommitAudit.'+positionID"
        v-if="('published'!=tmpAdvertisePosition.status)&&('auditing'!=tmpAdvertisePosition.status)&&('passed'!=tmpAdvertisePosition.status)&&ID&&tmpAdvertisePosition.isNeedAudit">
        <i class="fa fa-arrow-up"></i>提交审核
      </el-button>
      <el-button @click="auditPassed" :priv="'AdvertiseManage.Audit.'+positionID"
        v-if="('auditing'==tmpAdvertisePosition.status)&&tmpAdvertisePosition.isNeedAudit">
        <i class="fa fa-arrow-right"></i>审核通过
      </el-button>
      <el-button @click="auditNotPass"
        :priv="'AdvertiseManage.Audit.'+positionID"
        v-if="('auditing'==tmpAdvertisePosition.status)&&tmpAdvertisePosition.isNeedAudit">
        <i class="fa fa-exclamation-triangle text-danger"></i>审核不通过
      </el-button>
      <el-button @click="editAgain"
        :priv="'AdvertiseManage.Audit.'+positionID"
        v-if="(('passed'==tmpAdvertisePosition.status)||('published'==tmpAdvertisePosition.status))&&tmpAdvertisePosition.isNeedAudit">
        <i class="fa fa-edit"></i>重新编辑
      </el-button>
    </el-toolbar>
    <!-- 广告版位详情面板 -->
    <div class="detail-panel">
      <el-form :model="tmpAdvertisePosition" ref="createAdvertisePositionDataForm" label-width="100px" v-loading="dataLoading">
        <!-- 弹框顶部 -->
        <div class="dialog-top">
          <el-row>
            <el-col :span="12">
              <el-form-item label="版位名称：" prop="positionName" :verify="['NotNull']">
                <el-input class="form-item" v-model="tmpAdvertisePosition.positionName" @blur="setAlias"></el-input>
              </el-form-item>
              <el-form-item label="版位类型：" prop="positionType">
                <el-select v-model="tmpAdvertisePosition.positionType" class="form-item">
                  <el-option v-for="pt in positionTypeOption" :key="pt.key" :label="pt.value" :value="pt.key">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="广告策略：" prop="strategy">
                <el-select v-model="tmpAdvertisePosition.strategy" class="form-item">
                  <el-option v-for="str in strategyOptions" :key="str.ID" :label="str.name" :value="str.ID">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版位别名：" prop="code" :verify="['NotNull']">
                <el-input class="form-item" v-model="tmpAdvertisePosition.code"></el-input>
              </el-form-item>
              <el-form-item label="所属栏目：" prop="catalogID">
                <tree-select :value.sync="tmpAdvertisePosition.catalogID" clearable :items="catalogTree" :dim-info="{'enable':true}" width="80%">
                </tree-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 弹框中间部分，通过判断所选版位类型来显示出不同的内容 -->
        <div class="dialog-middle">
          <div v-if="tmpAdvertisePosition.positionType === 'couplet'">
            <el-form-item label="版位位置：">
              <el-checkbox class="scroll-checkbox" true-label="Y" false-label="" v-model="tmpAdvertisePosition.scroll">随屏滚动</el-checkbox>
            </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="左边距：" prop="paddingLeft">
                    <el-input-number v-model="tmpAdvertisePosition.paddingLeft" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                  </el-form-item>
                  <el-form-item label="上边距：" prop="paddingTop">
                    <el-input-number v-model="tmpAdvertisePosition.paddingTop" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                  </el-form-item>
                    </el-col>
                    <el-col :span="12">
                  <el-form-item label="右边距：" prop="paddingRight">
                    <el-input-number v-model="tmpAdvertisePosition.paddingRight" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                  </el-form-item>
                </el-col>
              </el-row>
          </div>
          <div v-if="tmpAdvertisePosition.positionType === 'fixure'">
            <el-form-item label="版位位置：">
              <el-checkbox class="scroll-checkbox" true-label="Y" false-label="" v-model="tmpAdvertisePosition.align">全屏居中</el-checkbox>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="左边距：" prop="paddingLeft">
                  <el-input-number v-model="tmpAdvertisePosition.paddingLeft" :disabled="tmpAdvertisePosition.align === 'Y'" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                </el-form-item>
                  </el-col>
                  <el-col :span="12">
                <el-form-item label="上边距：" prop="paddingTop">
                  <el-input-number v-model="tmpAdvertisePosition.paddingTop" :disabled="tmpAdvertisePosition.align === 'Y'" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="tmpAdvertisePosition.positionType === 'banner' || tmpAdvertisePosition.positionType === 'couplet' || tmpAdvertisePosition.positionType === 'fixure' || tmpAdvertisePosition.positionType === 'float' || tmpAdvertisePosition.positionType === 'imagechange' || tmpAdvertisePosition.positionType === 'imagelist'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="宽度：" prop="positionWidth" :verify="['NotNull']" >
                  <el-input-number v-model="tmpAdvertisePosition.positionWidth" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="高度：" prop="positionHeight" :verify="['NotNull']" >
                  <el-input-number v-model="tmpAdvertisePosition.positionHeight" :min="0" :max="99999" class="form-item"></el-input-number>&nbsp;px
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <el-form-item label="描述：" prop="description">
          <el-input type="textarea" :rows="4" v-model="tmpAdvertisePosition.description" style="width:90%;"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <el-toolbar align="right" v-if="positionID>0">
      <el-button @click="add" :priv="'AdvertiseManage.Edit.'+positionID">
        <i class="fa fa-plus"></i>添加广告
      </el-button>
    </el-toolbar>
    <el-list-view ref="advertiseList" v-if="positionID>0" :data-read-url="getData" :auto-get-data="false" :pageSize="10">
      <template slot-scope="row">
        <div class="panel-card">
          <el-row> <a class="list-card-title" href="javascript:void(0)"  @click.stop="edit(row.ID)">{{row.adName}}</a></el-row>
          <el-row>
            <el-col :span="8"><span>广告类型：</span> <em>{{row.adTypeName || '无'}}</em> </el-col>
            <el-col :span="8"><span>上线日期：</span> <em>{{row.startTime | fixDateTime}}</em> </el-col>
            <el-col :span="8"><span>下线日期：</span> <em>{{row.endTime | fixDateTime}}</em> </el-col>
          </el-row>
          <el-row>
              <el-col :span="8"><span>下线默认：</span>
              <i v-if="row.isOpen === 'Y'" class="fa fa-check icon-success"></i>
              <i v-else class="fa fa-times icon-danger"></i>
              </el-col>
              <el-col :span="8"><span>权重：</span> <em>{{row.weight || 0}}</em> </el-col>
              <el-col :span="8"><span>点击数：</span> <em>{{row.hitCount || 0}}</em> </el-col>
          </el-row>
          <el-row class="list-card-buttons">
            <el-col :span="10">
              <el-tag size="small">
                <span v-if="row.isOpen === 'Y'"><i class="fa fa-check icon-success"></i>启用</span>
                <span v-else><i class="fa fa-times icon-danger"></i>停用</span>
              </el-tag>
            </el-col>
            <el-col :span="14" class="tar">
              <el-button @click.stop="start([row])" type="text" :title="row.isOpen === 'Y' ? '停用' : '启用'" :priv="'AdvertiseManage.Edit.'+positionID">
                <span v-if="row.isOpen === 'Y'"><i class="fa fa-ban"></i>停用</span>
                <span v-else><i class="fa fa-check-circle"></i>启用</span>
              </el-button>
              <el-button @click.stop="setUnlineDefaultAdv([row])" type="text" :title="row.defaultAdvName ? '取消默认' : '设为默认'" :priv="'AdvertiseManage.Edit.'+positionID">
                <i class="fa fa-key"> {{row.defaultAdvName ? '取消默认' : '设为默认'}}</i>
              </el-button>
              <el-button @click.stop="edit(row.ID)" type="text" title="编辑" :priv="'AdvertiseManage.Edit.'+positionID">
                <i class="fa fa-edit"></i>编辑
              </el-button>
              <el-button @click.stop="del([row])" type="text" title="删除" :priv="'AdvertiseManage.Delete.'+positionID">
                <i class="fa fa-times"></i>删除
              </el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-list-view>
    <advertise-position-audit-dialog :show.sync="auditDialogModal" :postil="tmpAdvertisePosition.postil" :ID="ID" @callback="dialogCallback"></advertise-position-audit-dialog>

  </div>
</template>
<script>
import util from '@src/common/util.js'
import advertisePositionAuditDialog from './advertisePositionAuditDialog.vue'
import TreeSelect from '@src/components/TreeSelect.vue'

export default {
  components: {
    'tree-select': TreeSelect,
    'advertise-position-audit-dialog': advertisePositionAuditDialog
  },
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  filters: {
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      positionType: '',
      confirmLoading: false,
      positionID: 0,
      strategyOptions: [],
      positionTypeOption: [], // 版位类型下拉框数据
      catalogTree: [], // 栏目树数据
      auditDialogModal: false,
      advertiseID: null,
      advertiseDialogModal: false, // 新建/编辑广告弹框控制
      advertiseData: [], // 广告数据
      tmpAdvertisePosition: {
        positionName: '',
        code: '',
        positionType: 'banner',
        catalogID: 0,
        strategy: '',
        positionWidth: '400',
        positionHeight: '200',
        paddingLeft: '100',
        paddingRight: '100',
        paddingTop: '100',
        scroll: '',
        description: '',
        align: ''
      }, // 当前版位的数据
      selectedRows: [], // 当前选中的广告行
      dataLoading: false
    }
  },
  async created() {
    this.positionID = this.ID
    !!this.positionID && this.loadingAdvertiseData()
    let getCatalogTree = await axios.get('/ui/atverdiseposition/bindtree')
    this.catalogTree = getCatalogTree.data.data
    let getpositionType = await axios.get('/ui/atverdiseposition/positiontype')
    this.positionTypeOption = getpositionType.data.data
    let getStrategy = await axios.get('/ui/atverdiseposition/strategy')
    this.strategyOptions = getStrategy.data.data
  },
  methods: {
    async confirm() {
      try {
        await util.validateForm(this.$refs['createAdvertisePositionDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.confirmLoading = true
      // 判断是新建还是编辑
      if (this.positionID === 'new' || !this.positionID) {
        let res = await axios.post('/ui/atverdiseposition', this.tmpAdvertisePosition)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          await this.$nextTick()
          await util.updatePriv()
          this.positionID = res.data.ID
          this.loadingAdvertiseData()
          this.$router.replace(this.$route.path.replace('advertise/new', `advertise/${this.positionID}`))
        }
      } else {
        // 判断是否有更改版位类型
        try {
          if (this.tmpAdvertisePosition.positionType === this.positionType) {
            let res = await axios.put(`/ui/atverdiseposition/${this.positionID}`, this.tmpAdvertisePosition)
            util.showResponseMessage(res.data)
            this.loadingAdvertiseData()
            if (res.data.status === 1) {
              this.loadingAdvertiseData()
            }
          } else {
            await this.$confirm('修改版位类型会删除广告数据！确定修改？', '提示', {
              type: 'warning'
            })
            let res = await axios.put(`/ui/atverdiseposition/${this.positionID}`, this.tmpAdvertisePosition)
            util.showResponseMessage(res.data)
            if (res.data.status === 1) {
              this.loadingAdvertiseData()
            }
          }
        } catch (e) {
          this.confirmLoading = false
          return
        }
      }
      this.confirmLoading = false
    },
    // 汉字首字母转拼音
    async setAlias() {
      if (this.tmpAdvertisePosition.positionName && this.tmpAdvertisePosition.positionName.length > 0) {
        let code = window.util.getSpell(this.tmpAdvertisePosition.positionName, true)
        if (code && code.length > 0) {
          this.$set(this.tmpAdvertisePosition, 'code', code)
        }
      }
    },
    preview() {
      if (!this.positionID) {
        this.$alert('请选择需要预览的广告版位', '提示', {
          type: 'info'
        })
        return
      }
      window.open(`preview.html?&ID=${this.positionID}&type=ADPosition`)
    },
    // 提交审核
    async commitAudit() {
      if (!this.positionID) {
        this.$alert('请先选择一个广告版位', '提示', { type: 'info' })
        return
      }
      try {
        await this.$confirm('确定要提交审核申请吗？', '提交确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (error) {
        return
      }
      try {
        let res = await axios.put(`/ui/atverdiseposition/${this.positionID}/commitaudit`)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.loadingAdvertiseData()
        }
      } catch (e) {

      }
    },
    // 审核通过
    async auditPassed() {
      if (!this.positionID) {
        this.$alert('请先选择一个广告版位', '提示', { type: 'info' })
        return
      }
      let obj = {
        status: 'passed'
      }
      let res = await axios.put(`/ui/atverdiseposition/${this.positionID}/adpaudit`, obj)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadingAdvertiseData()
      }
    },
    // 审核不通过
    async auditNotPass() {
      if (!this.positionID) {
        this.$alert('请先选择一个广告版位', '提示', { type: 'info' })
        return
      }
      this.auditDialogModal = true
    },
    // 重新编辑
    async editAgain() {
      if (!this.positionID) {
        this.$alert('请先选择一个广告版位', '提示', { type: 'info' })
        return
      }
      let obj = {
        status: 'editagain'
      }
      let res = await axios.put(`/ui/atverdiseposition/${this.positionID}/adpaudit`, obj)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadingAdvertiseData()
      }
    },
    getData() {
      return [
        '/ui/atverdise',
        {
          params: {
            positionID: this.positionID
          }
        }
      ]
    },
    dialogCallback() {
      this.loadingAdvertiseData()
    },
    // 获取广告表格数据
    async loadingAdvertiseData() {
      this.confirmLoading = false
      this.dataLoading = true
      try {
        let res = await axios.get('/ui/atverdiseposition/initadpdialog', {
          params: {
            positionID: this.positionID
          }
        })
        this.tmpAdvertisePosition = res.data.data
        this.positionType = this.tmpAdvertisePosition.positionType
        this.$refs.advertiseList && (await this.$refs.advertiseList.getData())
      } catch (e) {}
      this.dataLoading = false
      // await this.$refs.dataTable.getData()
    },
    // 新建广告
    add() {
      if (this.tmpAdvertisePosition.status === 'auditing' || this.tmpAdvertisePosition.status === 'passed') {
        this.$alert('审核中或者审核通过的不能添加广告！', '提示', {
          type: 'info'
        })
        return
      }
      if (this.tmpAdvertisePosition.isNeedAudit === 'true' && this.tmpAdvertisePosition.status === 'published') {
        this.$alert('不能添加广告！', '提示', {
          type: 'info'
        })
        return
      }
      if (this.positionID < 0) {
        this.$alert('广告没有版位！', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      let path = this.$route.path.substring(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(`${path}/${this.positionID}/list/new`)
    },
    // 编辑广告
    edit(id) {
      let path = this.$route.path.substring(0, this.$route.path.lastIndexOf('/'))
      this.$router.push(`${path}/${this.positionID}/list/${id}`)
    },
    // 删除广告
    async del(rows) {
      // 判断当前是否有选中的广告
      if (rows.length === 0) {
        this.$alert('请选择需要删除的广告', '提示', {
          type: 'info'
        })
        return
      }
      let rowIds = []
      rows.forEach(function(row) {
        rowIds.push(row.ID)
      })
      try {
        await this.$confirm('确定要删除广告吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/atverdise/${rowIds.join(',')}`, {params: {positionID: this.positionID}})
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.loadingAdvertiseData()
        }
      } catch (e) {

      }
    },
    // 启用/停用广告
    async start(rows) {
      // 判断当前是否有选中的广告
      if (rows.length === 0) {
        this.$alert('请先选择要启用/停用的广告', '提示', {
          type: 'info'
        })
        return
      }
      let rowIds = []
      rows.forEach(function(row) {
        rowIds.push(row.ID)
      })
      let ids = rowIds.join(',')
      let res = await axios.put(`/ui/atverdise/${ids}/start`, {
        positionID: this.positionID
      })
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadingAdvertiseData()
      }
    },
    // 设为/取消默认广告
    async setUnlineDefaultAdv(rows) {
      // 判断当前是否有选中的广告
      if (rows.length === 0) {
        this.$alert('请先选择要设置或取消下线默认显示的广告', '提示', {
          type: 'info'
        })
        return
      }
      let rowIds = []
      rows.forEach(function(row) {
        rowIds.push(row.ID)
      })
      let ids = rowIds.join(',')
      let res = await axios.put(`/ui/atverdise/${ids}/setunlinedefaultadv`, {
        positionID: this.positionID
      })
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.loadingAdvertiseData()
      }
    }
  }
}
</script>

<style scoped>
.form-item {
  width: 80%;
}

.scroll-checkbox {
  margin-left: 32px;
}
</style>
