<template>
  <a-card size="small" :bordered="false" class="promotionRulesList-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="rangeDate" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="促销名称">
                <a-input id="promotionRulesList-name" v-model.trim="queryParam.name" allowClear placeholder="请输入促销名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <v-select code="ENABLE_FLAG" id="promotionRulesList-enabledFlag" v-model="queryParam.enabledFlag" allowClear placeholder="请选择状态"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="promotionRulesList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="promotionRulesList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button id="promotionRulesList-add" type="primary" v-if="$hasPermissions('B_promotionRules_add')" class="button-error" @click="openModal=true">新增</a-button>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1210, y: tableHeight }"
        bordered>
        <!-- 促销时间 -->
        <template slot="activeDate" slot-scope="text, record">
          <div v-if="record.activeDateEnable != '0'">
            <span v-if="record.activeDateStart || record.activeDateEnd">{{ record.activeDateStart }} 至 {{ record.activeDateEnd }}</span>
            <span v-else>--</span>
          </div>
          <span v-else>不限</span>
        </template>
        <!-- 状态 -->
        <template slot="enabledFlag" slot-scope="text, record">
          <a-switch
            v-if="$hasPermissions('B_promotionRules_enable')"
            id="promotionRulesList-enable"
            checkedChildren="启用"
            unCheckedChildren="禁用"
            @change="changeStatus(record)"
            :checked="record.enabledFlag == 1 ? true : false" />
          <span v-else :style="{color:(record.enabledFlag==1?'#00aa00':'#999')}"> {{ record.enabledFlag==1? '已启用': '已禁用' }} </span>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            v-if="record.enabledFlag != 1 && $hasPermissions('B_promotionRules_ruleSet')"
            class="button-primary"
            @click="handleRule(record)"
            id="promotionRulesList-rule-btn">规则设置</a-button>
          <a-button
            size="small"
            type="link"
            v-if="record.enabledFlag != 1 && $hasPermissions('B_promotionRules_edit')"
            class="button-info"
            @click="handleEdit(record)"
            id="promotionRulesList-edit-btn">编辑</a-button>
          <a-button
            size="small"
            type="link"
            v-if="$hasPermissions('B_promotionRules_detail')"
            class="button-success"
            @click="handleDetail(record)"
            id="promotionRulesList-detail-btn">详情</a-button>
          <span v-if="!(record.enabledFlag != 1 && $hasPermissions('B_promotionRules_ruleSet')) && !(record.enabledFlag != 1 && $hasPermissions('B_promotionRules_edit')) && !$hasPermissions('B_promotionRules_detail')">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 新增 -->
    <basic-info-modal :openModal="openModal" :itemSn="itemSn" @ok="handleOk" @close="closeModal" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import { promoActiveList, promoActiveEnable } from '@/api/promoActive'
export default {
  components: { STable, VSelect, basicInfoModal, rangeDate },
  data () {
    return {
      spinning: false,
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        name: '', //  名称
        enabledFlag: undefined //  状态
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销名称', dataIndex: 'name', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '促销时间', scopedSlots: { customRender: 'activeDate' }, width: 170, align: 'center' },
        { title: '参与客户', dataIndex: 'promoBuyerName', width: 180, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '备注', dataIndex: 'remark', width: 200, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '状态', scopedSlots: { customRender: 'enabledFlag' }, width: 100, align: 'center', fixed: 'right' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 170, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return promoActiveList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
            let str = ''
            const promoBuyerList = data.list[i].promoBuyerList ? data.list[i].promoBuyerList : []
            promoBuyerList.map(item => {
              str += item.buyerName + '，'
            })
            str = str.substr(0, str.length - 1)
            data.list[i].promoBuyerName = str || '全部客户'
          }
          this.total = data.count || 0
          this.disabled = false
          this.spinning = false
          return data
        })
      },
      total: 0, //  总条数
      openModal: false, //  弹框
      itemSn: '' //  当前sn
    }
  },
  methods: {
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0] ? date[0] + ' 00:00:00' : ''
      this.queryParam.endDate = date[1] ? date[1] + ' 23:59:59' : ''
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.name = ''
      this.queryParam.enabledFlag = undefined
      this.$refs.table.refresh(true)
    },
    //  编辑
    handleEdit (row) {
      this.itemSn = row.promoActiveSn
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (data) {
      this.$refs.table.refresh(true)
    },
    // 关闭弹框
    closeModal () {
      this.itemSn = ''
      this.openModal = false
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ path: `/promotionRulesManagement/promotionRules/detail/${row.id}/${row.promoActiveSn}` })
    },
    // 规则设置
    handleRule (row) {
      this.$router.push({ path: `/promotionRulesManagement/promotionRules/rule/${row.id}/${row.promoActiveSn}` })
    },
    // 启用 禁用
    changeStatus (record) {
      const params = {
        sn: record.promoActiveSn,
        flag: record.enabledFlag == 1 ? '0' : '1'
      }
      this.spinning = true
      promoActiveEnable(params).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
        }
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 245
    }
  },
  mounted () {
    const _this = this
    this.$nextTick(() => { // 页面渲染完成后的回调
      _this.setTableH()
    })
  }
}
</script>
