<template>
  <div>
    <a-card size="small" :bordered="false" class="promotion-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="promotion-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate id="promotion-createDate" ref="rangeCreateDate" :value="createDate" @change="dateCreateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="促销名称">
                <a-input id="promotion-promoName" v-model.trim="queryParam.promoName" allowClear placeholder="请输入促销名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="促销类型">
                <v-select
                  v-model="queryParam.promoType"
                  ref="promotionType"
                  id="promotion-promoType"
                  code="SHOP_PROMO_PROMO_TYPE"
                  placeholder="请选择促销类型"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="促销状态">
                <v-select
                  v-model="queryParam.promoState"
                  ref="promoState"
                  id="promotion-promoState"
                  code="SHOP_PROMO_PROMO_STATE"
                  placeholder="请选择促销状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <div class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" id="promotion-refresh" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" id="promotion-reset" @click="resetSearchForm()">重置</a-button>
              </div>
            </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_promoActivitiesAdd')">
          <a-button type="primary" class="button-error" id="promotion-add1-btn" @click="handleEdit('BUY_PROD_GIVE_PROD')">买产品送产品</a-button>
          <a-button type="primary" class="button-success" id="promotion-add3-btn" @click="handleEdit('BUY_PROD_GIVE_VALID')">买产品返代金券</a-button>
          <a-button type="primary" class="button-warning" id="promotion-add2-btn" @click="handleEdit('PROMO_PROD')">特价产品</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="promotionName" slot-scope="text, record">
            <div :id="'promotion-info-'+record.id" v-if="$hasPermissions('B_promoActivitiesDetail')" class="link-bule nameBox text-overflows2" @click="handleDetail(record)">{{ record.promoName }}</div>
            <div v-else class="nameBox text-overflows2">{{ record.promoName }}</div>
          </template>
          <!-- 促销时间 -->
          <template slot="promotionTime" slot-scope="text, record">
            <span>{{ record.promoStartDate }}至{{ record.promoEndDate }}</span>
          </template>
          <!-- 参与经销商 -->
          <template slot="joinCustomers" slot-scope="text, record">
            <div
              @click="handleCustomers(record)"
              :id="'promotion-seeDealerInfo-'+record.id"
              v-if="record.allDealerFlag&&record.allDealerFlag!='1'">
              共有<span class="link-bule">{{ record.dealerSnList && record.dealerSnList.length||0 }}</span>个客户
            </div>
            <span v-else>全部经销商</span>
          </template>
          <!-- 促销类型 -->
          <template slot="salesDesc" slot-scope="text, record">
            <a-tooltip placement="rightBottom" v-if="record.description&&record.description.length>14">
              <template slot="title">
                <span>{{ record.description }}</span>
              </template>
              <div @click="promotionDesc(record)" :id="'promotion-description-'+record.id" class="link-bule">{{ record.description }}</div>
            </a-tooltip>
            <div v-else-if="!record.description" class="desc">--</div>
            <div v-else @click="promotionDesc(record)" :id="'promotion-description1-'+record.id" class="link-bule">{{ record.description }}</div>
          </template>
          <!-- 操作 -->
          <!-- promoState状态 END已结束    HAVE_DISCARD已废弃    HAVE_RELEASE  已发布    NOT_RELEASE  未发布 -->
          <template slot="action" slot-scope="text, record">
            <div>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                :id="'promotion-edit-btn-'+record.id"
                @click="handleEdit('edit',record)"
                v-if="(record.promoState=='NOT_RELEASE') && $hasPermissions('B_promoActivitiesEdit')">编辑</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                :id="'promotion-abandon-btn-'+record.id"
                v-if="record.promoState=='HAVE_RELEASE'&&record.dealerOpenFlag=='0'&& $hasPermissions('B_promoActivitiesAbandon')"
                @click="handleAbandon(record)">废弃</a-button>
              <a-button
                size="small"
                type="link"
                class="button-warning"
                :id="'promotion-img-btn-'+record.id"
                v-if="record.promoState=='HAVE_RELEASE'&&record.dealerOpenFlag=='0'&& $hasPermissions('B_promoActivitiesImg')"
                @click="handleSet(record)">轮播图</a-button>
              <a-button
                size="small"
                type="link"
                class="button-info"
                @click="handleRelease(record)"
                v-if="record.promoState=='NOT_RELEASE'&&$hasPermissions('B_promoActivitiesRelease')"
                :id="'promotion-release-btn-'+record.id">发布</a-button>
              <a-button
                size="small"
                type="link"
                class="button-error"
                v-if="record.promoState=='NOT_RELEASE'&&$hasPermissions('B_promoActivitiesDel')"
                @click="handleDel(record)"
                :id="'promotion-del-btn-'+record.id">删除</a-button>
            </div>
          </template>
        </s-table>
      </a-spin>
      <!-- 新增促销活动 -->
      <add-promotion-modal :openModal="openAddModal" :typeVal="addPromotionType" @close="closeAddModal" @ok="$refs.table.refresh()" ></add-promotion-modal>
      <!-- 参与经销商 -->
      <lookUp-customers-modal ref="lookUpCustomers" :openModal="openCustomerModal" @close="openCustomerModal = false"></lookUp-customers-modal>
      <!-- 详情 -->
      <detail-Modal :openModal="openDetailModal" :itemSn="itemId" @close="closeDetailModal" @ok="$refs.table.refresh()" />
      <!-- 轮播图修改弹窗 -->
      <a-modal
        closable
        v-model="openSetImgModal"
        :footer="null"
        width="416px"
        centered>
        <div style="display:flex;margin:30px 0 20px 20px;">
          <a-icon type="question-circle" :style="{fontSize:'20px',color:'#faad14'}"/>
          <div style="margin-left:10px;margin-top:-3px;">
            <p style="font-size:16px;font-wight:bold;">设置</p>
            <p v-if="itemFlag=='1'">确定设为首页轮播图吗？</p>
            <p v-else>已有轮播图，不可再次生成</p>
          </div>
        </div>
        <!-- 按钮 -->
        <div style="text-align: right;">
          <a-button
            v-if="itemFlag=='1'"
            id="auditModal-cancel"
            type="primary"
            @click="handleSetModal('0')"
            style="margin-right: 15px;">取消</a-button>
          <a-button
            type="primary"
            id="auditModal-save"
            class="button-info"
            @click="handleSetModal('1')"
            v-if="itemFlag=='1'"
          >确定</a-button>
          <a-button
            v-else
            type="primary"
            id="auditModal-close"
            @click="handleSetModal('0')"
          >知道了</a-button>
        </div>
      </a-modal>
    </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 './lookUpCustomersModal'
import detailModal from './detailModal'
import addPromotionModal from './addPromotionModal'
// 接口
import { shopPromoActiveList, shopPromoDel, shopPromoRelease, shopPromoDiscard, updateShopBanner } from '@/api/shopPromo'
import { updateSetShopBanner } from '@/api/shopBanner'

export default {
  name: 'PromotionalActivitiesList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, lookUpCustomersModal, detailModal, addPromotionModal },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      openCustomerModal: false, // 打开参与经销商弹窗
      openDetailModal: false, // 打开详情弹窗
      createDate: [], //  创建时间
      openSetImgModal: false, // 设置首页轮播图弹窗
      openAddModal: false, // 新增促销活动
      addPromotionType: null, // 新增促销活动类型   BUY_PROD_GIVE_PROD买产品送产品     BUY_PROD_GIVE_VALID买产品返代金券    PROMO_PROD特价产品
      // 查询参数
      queryParam: {
        beginDate: undefined, // 促销开始时间
        endDate: undefined, // 促销结束时间
        promoName: '', // 促销名称
        promoType: undefined, // 促销类型
        promoState: undefined// 是否发布
      },
      itemId: '', // 当前活动sn
      itemObj: null, // 促销活动当前行信息
      itemFlag: null, // 设置轮播图显示弹窗按钮
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return shopPromoActiveList(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: '促销名称', scopedSlots: { customRender: 'promotionName' }, width: '18%', align: 'left' },
        { title: '促销时间', scopedSlots: { customRender: 'promotionTime' }, width: '18%', align: 'center' },
        { title: '参与经销商', scopedSlots: { customRender: 'joinCustomers' }, width: '8%', align: 'center' },
        { title: '促销类型', dataIndex: 'promoTypeDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '加盟商开关权限', dataIndex: 'dealerOpenFlag', width: '8%', align: 'center', customRender: function (text) { return (text ? text == '1' ? '是' : '否' : '--') } },
        // { title: '首页轮播图', dataIndex: 'shopBannerFlag', width: '6%', align: 'center', customRender: function (text) { return (text ? text == '1' ? '是' : '否' : '--') } },
        { title: '促销状态', dataIndex: 'promoStateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '11%', align: 'center' }
      ]
    }
  },
  methods: {
    //  创建时间  change
    dateCreateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 参与经销商
    handleCustomers (row) {
      this.openCustomerModal = true
      this.$nextTick(() => {
        this.$refs.lookUpCustomers.pageInit({ dealerSnList: row.dealerSnList ? row.dealerSnList : undefined })
      })
    },
    //
    closeAddModal () {
      this.openAddModal = false
    },
    // 新增  编辑
    handleEdit (type, row) {
      if (type === 'edit') {
        this.$router.push({ name: 'promotionalEditActivity', params: { pageType: type, sn: row.promoSn } })
      } else {
        this.addPromotionType = type
        this.openAddModal = true
      }
    },
    // 删除促销活动
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '点击确定，该内容将会被删除，不可再恢复!',
        centered: true,
        onOk () {
          _this.spinning = true
          shopPromoDel({ promoSn: row.promoSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 废弃
    handleAbandon (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要废弃该促销活动吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shopPromoDiscard({ promoSn: row.promoSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 重置
    resetSearchForm () {
      this.createDate = []
      this.$refs.rangeCreateDate.resetDate([])
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.queryParam.promoName = ''
      this.queryParam.promoType = undefined
      this.queryParam.promoState = undefined
      this.itemFlag = null
      this.$refs.table.refresh(true)
    },
    // 促销发布
    handleRelease (row, type) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要发布该促销活动吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          shopPromoRelease({ promoSn: row.promoSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 打开 设置轮播图弹窗
    handleSet (row) {
      this.itemObj = row
      this.spinning = true
      updateSetShopBanner({ bizSn: row.promoSn, stateList: ['UNPUBLISH', 'PUBLISH', 'CLOSE'] }).then(res => {
        if (res.status == 200) {
          this.itemFlag = res.data && Object.keys(res.data).length > 0 ? '0' : '1'
          this.openSetImgModal = true
          this.spinning = false
        } else {
          this.spinning = false
        }
      })
    },
    // 设置轮播图
    handleSetModal (val) {
      const _this = this
      if (val === '1') {
        _this.setImage()
      } else {
        _this.openSetImgModal = false
      }
    },
    // 设置轮播图
    setImage (val) {
      const _this = this
      _this.spinning = true
      updateShopBanner({ promoSn: _this.itemObj.promoSn, shopBannerFlag: 1 }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
          _this.openSetImgModal = false
          _this.itemObj = null
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    // 打开详情
    handleDetail (row) {
      this.openDetailModal = true
      this.itemId = row.promoSn
    },
    // 关闭详情
    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>
  .font1{
   color:#39f;
  }
  .desc{
    width: 100%;
    padding:0 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    box-sizing: border-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
</style>
