<template>
  <a-card size="small" :bordered="false" class="promotion-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate ref="rangeCreateDate" :value="createDate" @change="dateCreateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="促销名称">
                <a-input id="promotion-promotionName" v-model.trim="queryParam.name" allowClear placeholder="请输入总部销退单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="显示状态">
                <a-select
                  v-model="queryParam.showFlag"
                  placeholder="请选择显示状态"
                >
                  <a-select-option :value="1">已显示</a-select-option>
                  <a-select-option :value="0">未显示</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="促销状态">
                <v-select
                  v-model="queryParam.state"
                  ref="saleStatus"
                  id="promotion-saleStatus"
                  code="PROMO_STATE"
                  placeholder="请选择促销状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" :disabled="disabled" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" :disabled="disabled" @click="resetSearchForm()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
        <!-- 操作按钮 -->
        <div class="table-operator" v-if="$hasPermissions('B_promotionManagementAdd')">
          <a-button type="primary" class="button-error" @click="openAddModal = true">新增</a-button>
        </div>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+94.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 自定义表头 -->
        <template slot="arrowFalgTitle">
          <a-tooltip placement="top">
            <template slot="title">
              <span>易码通轮播促销展示显示状态</span>
            </template>
            显示状态<a-icon type="question-circle" :style="{ marginLeft: '10px' }" />
          </a-tooltip>
        </template>
        <!-- 显示状态 -->
        <template slot="arrowFalg" slot-scope="text, record">
          <a-switch
            checkedChildren="显示"
            unCheckedChildren="隐藏"
            id="promotion-isEnable"
            v-model="record.isEnable"
            :disabled="record.state!='PUBLISH'"
            @change="changeFlagHandle(record)" />
        </template>
        <!-- 促销时间 -->
        <template slot="promotionTime" slot-scope="text, record">
          <span>{{ record.activeDateStart }}至{{ record.activeDateEnd }}</span>
        </template>
        <!-- 参与客户 -->
        <template slot="joinCustomers" slot-scope="text, record">
          <span @click="handleCustomers(record)">共有<span class="font1">{{ record.promoBuyerSnSet?record.promoBuyerSnSet.length:0 }}</span>个客户</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)" class="desc font1">{{ record.description }}</div>
          </a-tooltip>
          <div v-else @click="promotionDesc(record)" class="desc font1">{{ record.description }}</div>
        </template>
        <!-- 促销展示 -->
        <template slot="salesShow" slot-scope="text, record">
          <div @click="handleSaleShow(record)" v-if="record.contentType!='LINK'&&record.imageSet && record.imageSet.length>0">
            <img :src="record.imageSet[0]" alt="图片走丢啦" width="60" />
          </div>
          <div v-else-if="record.contentType=='LINK'&&record.imageSet && record.imageSet.length>0">
            <img :src="record.imageSet[0]" alt="图片走丢啦" width="60" />
          </div>
          <span v-else>--</span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <div>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="promotionEdit(record)"
              v-if="(record.state=='UNPUBLISH' || record.state=='CLOSE') && $hasPermissions('B_promotionManagementAdd')"
              id="promotion-edit-btn">促销编辑</a-button>
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleRelease(record,'edit')"
              v-if="(record.state=='PUBLISH' || record.state=='CLOSE')&&$hasPermissions('B_promotionManagementContent')"
              id="promotion-modify-btn">发布修改</a-button>
            <a-button
              size="small"
              type="link"
              class="button-info"
              @click="handleRelease(record,'add')"
              v-if="record.state=='UNPUBLISH'&&$hasPermissions('B_promotionManagementContent')"
              id="promotion-release-btn">促销发布</a-button>
            <a-button
              size="small"
              type="link"
              class="button-error"
              v-if="record.state=='UNPUBLISH'&&$hasPermissions('B_promotionManagementDel')"
              @click="handleDel(record)"
              id="promotion-del-btn">删除</a-button>
            <span v-if="record.state=='End'">--</span>
          </div>
        </template>
      </s-table>
    </a-spin>
    <!-- 参与客户 -->
    <lookUp-customers-modal ref="lookUpCustomers" :openModal="openCustomerModal" @close="openCustomerModal = false"></lookUp-customers-modal>
    <!-- 促销描述 -->
    <promotion-desc-modal :openModal="openDescModal" :con="descCon" @close="openDescModal = false;descCon=''"></promotion-desc-modal>
    <!-- 促销展示 -->
    <promotion-show-modal ref="showModal" :openModal="openShowModal" @close="openShowModal = false"></promotion-show-modal>
    <!-- 新增 -->
    <addModal :openModal="openAddModal" :itemId="itemId" @close="closeAddModal" @ok="$refs.table.refresh()"></addModal>
    <!-- 促销发布 -->
    <promotion-edit-modal :pageType="pageType" :openModal="openPromotionEditModal" :itemId="itemId" @close="closePromotionEditModal" @ok="$refs.table.refresh()" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { promoTerminalList, promoTerminalDel, updateShowFlag } from '@/api/promoTerminal'
import lookUpCustomersModal from './lookUpCustomersModal'
import promotionDescModal from './promotionDescModal'
import promotionShowModal from './promotionShowModal'
import addModal from './addModal'
import promotionEditModal from './editModal'
export default {
  name: 'PromotionList',
  mixins: [commonMixin],
  components: {
    STable,
    VSelect,
    rangeDate,
    lookUpCustomersModal,
    promotionShowModal,
    promotionDescModal,
    addModal,
    promotionEditModal
  },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      disabled: false, //  查询、重置按钮是否可操作
      openCustomerModal: false,
      openDescModal: false,
      openShowModal: false,
      openAddModal: false,
      openPromotionEditModal: false,
      createDate: [], //  创建时间
      itemId: '',
      descCon: '', // 描述内容
      pageType: '', // 发布类型  add  促销发布  edit 发布修改
      dealerSn: [],
      // 查询参数
      queryParam: {
        beginDate: undefined,
        endDate: undefined,
        name: '',
        showFlag: undefined,
        state: undefined
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        return promoTerminalList(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
              data.list[i].isEnable = data.list[i].showFlag + '' === '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: 'name', width: '12%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '促销时间', scopedSlots: { customRender: 'promotionTime' }, width: '8%', align: 'center' },
        { title: '参与客户', scopedSlots: { customRender: 'joinCustomers' }, width: '12%', align: 'center' },
        { title: '促销描述', scopedSlots: { customRender: 'salesDesc' }, width: '12%', align: 'center' },
        { title: '促销展示', scopedSlots: { customRender: 'salesShow' }, width: '6%', align: 'center' },
        { slots: { title: 'arrowFalgTitle' }, scopedSlots: { customRender: 'arrowFalg' }, 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: {
    // 关闭添加促销活动弹窗
    closeAddModal () {
      this.openAddModal = false; this.itemId = ''
    },
    // 参与经销商
    handleCustomers (row) {
      this.openCustomerModal = true
      this.$nextTick(() => {
        this.$refs.lookUpCustomers.pageInit({ dealerSnList: row.promoBuyerSnSet ? row.promoBuyerSnSet : undefined, promoActiveSn: row.promoActiveSn })
      })
    },
    //  创建时间  change
    dateCreateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 促销展示
    handleSaleShow (record) {
      this.openShowModal = true
      this.$nextTick(() => {
        this.$refs.showModal.pageInit({ type: record.contentType, con: record.content })
      })
    },
    // 修改显示状态
    changeFlagHandle (record) {
      const _data = {
        sn: record.promoActiveSn,
        showFlag: record.isEnable ? '1' : '0'
      }
      this.spinning = true
      updateShowFlag(_data).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.$refs.table.refresh()
          this.spinning = false
        }
      })
    },
    // 促销编辑
    promotionEdit (item) {
      this.itemId = item.promoActiveSn
      this.$nextTick(() => {
        this.openAddModal = true
      })
    },
    // 促销描述
    promotionDesc (row) {
      this.descCon = row.description
      this.$nextTick(() => {
        this.openDescModal = true
      })
    },
    // 删除促销活动
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '点击确定，该内容将会被删除，不可再恢复!',
        centered: true,
        onOk () {
          _this.spinning = true
          promoTerminalDel({ sn: row.promoActiveSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    resetSearchForm () {
      this.$refs.rangeCreateDate.resetDate(this.createDate)
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.queryParam.name = ''
      this.queryParam.showFlag = undefined
      this.queryParam.state = undefined
      this.$refs.table.refresh(true)
    },
    // 促销发布
    handleRelease (row, type) {
      this.itemId = row.promoActiveSn
      this.pageType = row.imageSet && row.imageSet.length > 0 ? 'edit' : type
      this.$nextTick(() => {
        this.openPromotionEditModal = true
      })
    },
    // 关闭促销发布
    closePromotionEditModal () {
      this.openPromotionEditModal = false
      this.itemId = ''
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  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>
