<template>
  <div>
    <a-card size="small" :bordered="false" class="carouselImage-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="carouselImage-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate id="carouselImage-createDate" ref="rangeCreateDate" :value="createDate" @change="dateCreateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="轮播图名称">
                <a-input id="carouselImage-bannerName" v-model.trim="queryParam.bannerName" allowClear placeholder="请输入轮播图名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="轮播图状态">
                <v-select
                  v-model="queryParam.state"
                  ref="stateDictValue"
                  id="carouselImage-state"
                  code="SHOP_BANNER_STATE"
                  placeholder="请选择轮播图状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" id="carouselImage-refresh" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" id="carouselImage-reset" @click="resetSearchForm()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <!-- 列表 -->
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 操作按钮 -->
        <div class="table-operator" v-if="$hasPermissions('B_homepageCarouselAdd')">
          <a-button type="primary" id="carouselImage-add-btn" @click="handleAddOrEdit()">新增</a-button>
        </div>
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+70+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <!-- 促销时间 -->
          <template slot="promotionTime" slot-scope="text, record">
            <span>{{ record.bannerStartDate }}至{{ record.bannerEndDate }}</span>
          </template>
          <!-- 参与经销商 -->
          <template slot="joinCustomers" slot-scope="text, record">
            <span class="customerBox" v-if="$hasPermissions('B_homepageCarouselSee')&&(record.allDealerFlag&&record.allDealerFlag=='0')" @click="handleCustomers(record)" :id="'carouselImage-seeDealerInfo-'+record.id">共有<span class="link-bule">{{ record.dealerQty }}</span>个客户</span>
            <span v-else-if="!$hasPermissions('B_homepageCarouselSee')&&(record.allDealerFlag&&record.allDealerFlag=='0')">共有<span class="link-bule">{{ record.dealerQty }}</span>个客户</span>
            <span v-else-if="$hasPermissions('B_homepageCarouselSee')&&(record.allDealerFlag&&record.allDealerFlag=='1')">全部经销商</span>
            <span v-else>--</span>
          </template>
          <!-- 封面展示 -->
          <template slot="salesShow" slot-scope="text, record">
            <div v-if="record.imageUrl" @click="handleCheckImg(record)" :id="'carouselImage-seeImgInfo-'+record.id">
              <img :src="record.imageUrl" alt="图片走丢啦" width="60"/>
            </div>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <!-- state状态 END已结束    CLOSE已关闭    PUBLISH  已发布    UNPUBLISH  未发布 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-warning"
              :id="'carouselImage-edit-btn-'+record.id"
              @click="handleAddOrEdit(record)"
              v-if="(record.state=='UNPUBLISH' || record.state=='CLOSE') && $hasPermissions('B_homepageCarouselEdit')">编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-success"
              @click="handleSee(record)"
              v-if="(record.state=='PUBLISH' || record.state=='END')&&$hasPermissions('B_homepageCarouselDetail')"
              :id="'carouselImage-seeDetail-btn-'+record.id">查看</a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="closeReleaseDel(record,'PUBLISH')"
              v-if="(record.state=='UNPUBLISH'||record.state=='CLOSE')&&$hasPermissions('B_homepageCarouselRelease')"
              :id="'carouselImage-release-btn-'+record.id">发布</a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="closeReleaseDel(record,'CLOSE')"
              v-if="(record.state=='PUBLISH')&&$hasPermissions('B_homepageCarouselClose')"
              :id="'carouselImage-release-btn-'+record.id">关闭</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              v-if="(record.state=='UNPUBLISH'||record.state=='CLOSE')&&$hasPermissions('B_homepageCarouselDel')"
              @click="closeReleaseDel(record,'1')"
              :id="'carouselImage-del-btn-'+record.id">删除</a-button>
          </template>
        </s-table>
      </a-spin>
      <!-- 参与经销商 -->
      <lookUp-customers-modal ref="lookUpCustomers" :openModal="openCustomerModal" @close="openCustomerModal = false"></lookUp-customers-modal>
      <!-- 封面展示 -->
      <imgShowModal v-drag ref="checkedImg" :openModal="openCheckedImgModal" @close="openCheckedImgModal=false"></imgShowModal>
      <!-- 查看 -->
      <detail-Modal :openModal="openDetailModal" :itemSn="itemId" @close="closeDetailModal" @ok="openDetailModal=false"/>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import lookUpCustomersModal from '@/views/easyPassManagement/promotionalActivities/lookUpCustomersModal'
import imgShowModal from '@/views/easyPassManagement/shoppingManagement/imgShowModal'
import detailModal from './detailModal'
// 接口
import { shopBannerList, updateShopBanner } from '@/api/shopBanner'
export default {
  name: 'PromotionList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, lookUpCustomersModal, detailModal, imgShowModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      openCustomerModal: false, // 打开参与经销商弹窗
      openCheckedImgModal: false, // 查看封面图弹窗
      openDetailModal: false, // 打开详情弹窗
      itemId: '', // 当前活动sn
      createDate: [], //  创建时间
      // 查询参数
      queryParam: {
        beginDate: undefined, // 创建开始时间
        endDate: undefined, // 创建结束时间
        bannerName: '', // 轮播图名称
        state: undefined// 轮播图状态
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return shopBannerList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      columns: [// 表头
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '轮播图名称', dataIndex: 'bannerName', width: '13%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '轮播时间', scopedSlots: { customRender: 'promotionTime' }, width: '13%', align: 'center' },
        { title: '参与经销商', scopedSlots: { customRender: 'joinCustomers' }, width: '8%', align: 'center' },
        { title: '封面展示', scopedSlots: { customRender: 'salesShow' }, width: '6%', align: 'center' },
        { title: '轮播图状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ]
    }
  },
  methods: {
    // 新增  编辑
    handleAddOrEdit (row) {
      if (!row) {
        this.$router.push({ name: 'carouselImageAdd' })
      } else {
        this.$router.push({ name: 'carouselImageEdit', params: { sn: row.bannerSn, bizType: row.bizType || 'none' } })
      }
    },
    //  创建时间  change
    dateCreateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 参与经销商
    handleCustomers (row) {
      this.openCustomerModal = true
      this.$nextTick(() => {
        this.$refs.lookUpCustomers.pageInit({ bannerSn: row.bannerSn })
      })
    },
    // 封面图片
    handleCheckImg (record) {
      this.openCheckedImgModal = true
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.checkedImg.pageInit(record.imageUrl)
      })
    },
    // 重置
    resetSearchForm () {
      this.createDate = []
      this.$refs.rangeCreateDate.resetDate([])
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.queryParam.bannerName = ''
      this.queryParam.state = undefined
      this.$refs.table.refresh(true)
    },
    // 发布  关闭  删除
    closeReleaseDel (row, val) {
      const _this = this
      let tipDetail = null
      const ajaxData = { bannerSn: row.bannerSn }
      if (val != '1') {
        tipDetail = '确认要' + (val === 'CLOSE' ? '关闭' : '发布') + '吗？'
        ajaxData.state = val
        ajaxData.delFlag = undefined
      } else {
        tipDetail = '点击确定，该内容将会被删除，不可再恢复!'
        ajaxData.state = undefined
        ajaxData.isDel = val
      }
      this.$confirm({
        title: '提示',
        content: tipDetail,
        centered: true,
        onOk () {
          _this.spinning = true
          updateShopBanner(ajaxData).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 打开详情
    handleSee (row) {
      this.openDetailModal = true
      this.itemId = row.bannerSn
    },
    // 关闭详情
    closeDetailModal () {
      this.openDetailModal = false
      this.itemId = ''
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
  .customerBox{
    cursor:pointer;
  }
</style>
