<template>
  <div>
    <a-card size="small" :bordered="false" class="promotionList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="promotionList-form" @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" id="promotionList-rangeDate" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="促销名称/简称">
                <a-input id="promotionList-queryWord" v-model.trim="queryParam.queryWord" allowClear placeholder="请输入促销名称/简称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="发布状态">
                <v-select
                  v-model="queryParam.enabledFlag"
                  ref="enabledFlag"
                  id="promotionList-enabledFlag"
                  code="PUBLISH_STATE"
                  placeholder="请选择发布状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="活动状态">
                <v-select
                  v-model="queryParam.state"
                  ref="state"
                  id="promotionList-state"
                  code="PROMOTION_STATE"
                  placeholder="请选择活动状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="创建人">
                <creatorList ref="creatorList" id="promotionList-creatorId" @change="creatorChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="经销商名称">
                <custList ref="custList" id="promotionList-tenantSn" @change="custChange"></custList>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="promotionList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm()" :disabled="disabled" id="promotionList-reset">重置</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 tableBtnSet" >
          <a-button v-if="$hasPermissions('B_dealerPromotionAdd')" id="promotionList-add" type="primary" @click="handleAdd">新增</a-button>
          <a-checkbox @change="handleDealerAudit" v-if="$hasPermissions('B_dealerAudit')" :checked="queryParam.dealerAuditFlag &&queryParam.dealerAuditFlag==1">
            待审核（修改参与客户）
          </a-checkbox>
        </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="'promotionList-info-'+record.id" v-if="$hasPermissions('B_dealerPromotionDetail')" class="link-bule nameBox">
              <span @click="handleDetail(record)" style="vertical-align: middle;">{{ record.title }}</span>
              <a-badge count="叠" v-show="record.stackFlag == 1" :number-style="{ backgroundColor: '#00aa00', marginLeft:'5px', zoom:'80%' }" />
              <a-badge count="累" v-show="record.borrowFlag == 1" :number-style="{ backgroundColor: '#F5222D', marginLeft:'5px', zoom:'80%' }" />
            </div>
            <div v-else class="nameBox text-overflows2">{{ record.title }}</div>

          </template>
          <!-- 促销时间-->
          <template slot="promotionTime" slot-scope="text, record">
            <div>{{ record.promotionDateStart.split(' ')[0] }}~{{ record.promotionDateEnd.split(' ')[0] }}</div>
          </template>
          <!-- 参与客户 -->
          <template slot="joinCustomers" slot-scope="text, record">
            <span class="joinCustomer" :id="'promotionList-customers-'+record.id" v-if="record.dealerScope ==='ALL_DEALER'" @click="handleCustomers(record)">全部客户</span>
            <span class="joinCustomer" :id="'promotionList-customers-'+record.id" v-else @click="handleCustomers(record)">共有<span style="color:#39f;vertical-align:top;">{{ record.dealerQty ||0 }}</span>个客户</span>
            <a-badge count="审" v-show="record.dealerAuditFlag == 1 &&(record.state==='NOT_START'||record.state==='RUNNING') " :number-style="{ backgroundColor: '#F5222D', zoom:'80%' }" />
          </template>
          <!-- 发布状态 -->
          <template slot="releaseStatus" slot-scope="text, record">
            <a-switch
              v-if="$hasPermissions('B_dealerPromotionStatus')"
              :id="'promotionList-enable-'+record.id"
              @change="changeStatus(record)"
              :disabled="record.state!='NOT_START' && record.state!='RUNNING'"
              :checked="record.enabledFlag == 1 ? true : false"></a-switch>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <!--  state 待提交:WAIT_SUBMIT 待审核:WAIT_AUDIT 未开始:NOT_START 进行中:RUNNING 审核不通过:AUDIT_REJECT 已结束:IS_OVER -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              class="button-warning"
              @click="handleSetRules(record)"
              v-if="$hasPermissions('B_dealerPromotionRules')&&(record.state =='WAIT_SUBMIT'||record.state == 'AUDIT_REJECT')"
              :id="'promotionList-examine-btn'+record.id">规则设置</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_dealerPromotionEdit')&&(record.state == 'WAIT_SUBMIT' ||record.state == 'AUDIT_REJECT')"
              @click="handleEdit(record)"
              class="button-info"
              :id="'promotionList-edit-btn'+record.id">编辑</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_dealerPromotionAudit')&&record.state == 'WAIT_AUDIT'"
              @click="handleCheck(record)"
              class="button-info"
              :id="'promotionList-audit-btn'+record.id">审核</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_editTime')&&(record.state == 'NOT_START' || record.state=='RUNNING' ||record.state == 'IS_OVER')"
              @click="handleTime(record)"
              class="button-info"
              :id="'promotionList-editTime-btn'+record.id">时间变更</a-button>
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_overActive')&&(record.state == 'NO_START' || record.state=='RUNNING')"
              @click="handleEnd(record)"
              class="button-info"
              :id="'promotionList-edit-btn'+record.id">终止</a-button>
            <!-- canDelFlag  1显示删除按钮 0不显示删除按钮 （权限：发布状态  关闭 活动状态 进行中||已结束 并且从没有销售单参与过该活动） -->
            <a-button
              size="small"
              type="link"
              v-if="$hasPermissions('B_dealerPromotionDel')&&record.canDelFlag == 1"
              @click="handleDel(record)"
              class="button-error"
              :id="'promotionList-del-btn'+record.id">删除</a-button>
            <a-button
              size="small"
              type="link"
              v-if="record.state != 'AUDIT_REJECT' &&$hasPermissions('B_dealerPromotionCopy')"
              @click="handleCopyModal(record)"
              class="button-info"
              :id="'promotionList-copy-btn'+record.id">复制</a-button>
          </template>
        </s-table>
      </a-spin>
      <!-- 参与客户 -->
      <lookUp-customers-modal
        :itemSn="itemPromotionSn"
        :showType="itemStatusType"
        ref="lookUpCustomers"
        :openModal="openCustomerModal"
        :chooseDealerList="chooseDealerArr"
        @submitAudit="editCustomerOk"
        @handleAudit="auditCustomerOk"
        @close="closeCustomer"></lookUp-customers-modal>
      <!-- 新增/编辑弹窗-->
      <add-modal v-drag :itemSn="itemSn" :openModal="openModal" @ok="handleOk" @close="openModal=false" />
      <!-- 促销时间变更 -->
      <edit-active-end-time ref="editTime" v-drag :openModal="editEndModal" @ok="$refs.table.refresh()" @close="editEndModal=false" />
      <!-- 终止促销 -->
      <end-desc-modal v-drag :openModal="openEndActivityModal" @ok="$refs.table.refresh()" :itemObj="endObj" @close="closeEndActivityModal" ></end-desc-modal>
      <!-- 审核弹窗 -->
      <a-modal
        closable
        v-model="openAuditModal"
        :footer="null"
        width="416px"
        centered>
        <div style="display:flex;margin:30px 0 20px 20px;">
          <a-icon type="question-circle" :style="{fontSize:'23px',color:'#faad14'}"/>
          <div style="margin-left:10px;">
            <p style="font-size:16px;font-wight:bold;">提示</p>
            <p>请点击下方按钮确认操作?</p>
          </div>
        </div>
        <!-- 按钮 -->
        <div style="text-align: right;">
          <a-button
            id="auditModal-cancel"
            class="button-cancel"
            @click="closeAuditModal"
            style="margin-right: 15px;">审核不通过</a-button>
          <a-button
            type="primary"
            id="auditModal-save"
            class="button-primary"
            :loading="loadingAudit"
            @click="handleAuditModal"
          >审核通过</a-button>
        </div>
      </a-modal>
      <!-- 复制弹窗 -->
      <a-modal
        closable
        v-model="openCopyModal"
        :footer="null"
        width="416px"
        centered>
        <div class="copyContent">
          <p>提示：</p>
          <p>复制选择的促销活动，将在列表生成一条相同的【待提交】的促销活动，可进行编辑！</p>
          <p>是否确认生成？</p>
          <p>附件无法复制，请重新上传</p>
        </div>
        <!-- 按钮 -->
        <div class="copyBtn">
          <a-button
            id="copyModal-cancel"
            class="button-cancel"
            @click="closeCopyModal"
            style="margin-right: 15px;">取消</a-button>
          <a-button
            type="primary"
            id="copyModal-save"
            class="button-primary"
            @click="handleCopy"
          >确定</a-button>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import addModal from './addModal.vue'
import lookUpCustomersModal from './lookUpCustomersModal'
import endDescModal from './endDescModal'
import rangeDate from '@/views/common/rangeDate.vue'
import creatorList from '@/views/common/creatorList.vue'
import editActiveEndTime from './editActiveEndTime.vue'
import supplier from '@/views/common/supplier.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import custList from '@/views/common/custList.vue'
import debounce from 'lodash/debounce'
// 接口
import { dealerPromotionList, dealerPromotionDel, modifyEnabledFlag, promotionAudit, promotionIsOver, handleCopyData, midwaySubmit, dealerMidwayAudit, updateDealerSnList } from '@/api/promotion'
export default {
  name: 'DealerPromotionManagementList',
  mixins: [commonMixin],
  components: { STable, supplier, VSelect, rangeDate, warehouse, lookUpCustomersModal, endDescModal, addModal, editActiveEndTime, creatorList, custList },
  data () {
    this.handleAuditModal = debounce(this.handleAuditModal, 800)
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 新增弹框是否显示
      openCustomerModal: false, // 参与客户弹窗
      editEndModal: false, // 更改促销时间
      openDetailModal: false, // 详情弹窗
      tableHeight: 0, // 表格高度
      // 查询参数
      queryParam: {
        beginDate: undefined, // 开始时间
        endDate: undefined, // 结束时间
        queryWord: '', // 促销名称/简称
        enabledFlag: undefined, // 发布状态
        state: undefined, // 活动状态
        creatorId: undefined, // 创建人
        dealerAuditFlag: undefined, // 审核  0 不通过 1通过
        dealerSn: undefined// 经销商
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '促销名称', scopedSlots: { customRender: 'promotionName' }, width: '16%', align: 'left' },
        { title: '促销简称', dataIndex: 'description', width: '13%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '促销时间', scopedSlots: { customRender: 'promotionTime' }, width: '13%', align: 'center' },
        { title: '参与客户', scopedSlots: { customRender: 'joinCustomers' }, width: '11%', align: 'center', ellipsis: true },
        { title: '促销描述', dataIndex: 'content', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '创建人', dataIndex: 'creatorName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '活动状态', dataIndex: 'stateDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '发布状态', scopedSlots: { customRender: 'releaseStatus' }, width: '6%', align: 'center', ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据 有分页
        return dealerPromotionList(Object.assign(parameter, this.queryParam)).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
        })
      },
      itemSn: null, // 经销商促销活动SN
      openAuditModal: false, // 审核弹窗,
      openCopyModal: false, // 复制弹窗
      itemPromotionSn: '', // 参与客户，当前sn
      itemStatusType: '', // 按你加载类型 isEdit 编辑 isAudit 审核 isClose关闭
      chooseDealerArr: [], // 所选择经销商列表
      loadingAudit: false,
      endObj: null, // 终止促销数据
      openEndActivityModal: false// 打开终止促销弹窗
    }
  },
  methods: {
    // 经销商列表查询
    custChange (val) {
      this.queryParam.dealerSn = val.key
    },
    // 创建人
    creatorChange (val) {
      this.queryParam.creatorId = val.key
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ name: 'dealerPromotionManagementDetail', query: { sn: row.promotionSn } })
    },
    // 创建时间
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  新增
    handleAdd () {
      this.itemSn = null
      this.openModal = true
    },
    // 参与客户
    handleCustomers (row) {
      this.itemPromotionSn = row.promotionSn
      if ((row.state === 'NOT_START' || row.state === 'RUNNING') && row.dealerAuditFlag && (row.dealerAuditFlag == 0 || row.dealerAuditFlag == 2)) {
        this.itemStatusType = 'isEdit'
      } else if ((row.state === 'NOT_START' || row.state === 'RUNNING') && row.dealerAuditFlag && row.dealerAuditFlag == 1) {
        this.itemStatusType = 'isAudit'
      } else {
        this.itemStatusType = 'isClose'
      }
      this.getDealerSnList({ promotionSn: row.promotionSn })
    },
    async getDealerSnList (ajaxData) {
      const dealerSnArr = await updateDealerSnList(ajaxData)
      this.chooseDealerArr = dealerSnArr.data
      this.openCustomerModal = true
    },
    //  基本信息  保存
    handleOk () {
      this.itemSn = null
      this.resetSearchForm()
    },
    //  编辑
    handleEdit (row) {
      this.openModal = true
      this.itemSn = row.promotionSn
    },
    // 发布状态
    changeStatus (record) {
      const params = {
        promotionSn: record.promotionSn,
        enabledFlag: record.enabledFlag == 1 ? '0' : '1'
      }
      this.spinning = true
      modifyEnabledFlag(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
        }
      })
    },
    // 规则设置
    handleSetRules (row) {
      this.$router.push({ name: 'dealerPromotionManagementRule', query: { type: 'rule', sn: row.promotionSn } })
    },
    // 审核参与客户
    handleDealerAudit (val) {
      this.queryParam.dealerAuditFlag = val.target.checked ? '1' : undefined
      this.$nextTick(() => {
        this.$refs.table.refresh(true)
      })
    },
    // 审核
    handleCheck (row) {
      const _this = this
      _this.itemSn = row.promotionSn
      _this.openAuditModal = true
    },
    // 打开审核弹窗
    handleAuditModal () {
      this.loadingAudit = true
      this.handleAudit({ promotionSn: this.itemSn, auditFlag: 1 })
    },
    // 关闭审核弹窗
    closeAuditModal () {
      this.handleAudit({ promotionSn: this.itemSn, auditFlag: 0 })
    },
    // 审核
    handleAudit (ajaxData) {
      const _this = this
      _this.spinning = true
      promotionAudit(ajaxData).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        }
        _this.itemSn = null
        _this.openAuditModal = false
        _this.spinning = false
        _this.loadingAudit = false
      })
    },
    // 打开复制弹窗
    handleCopyModal (row) {
      this.itemSn = row.promotionSn
      this.$nextTick(() => {
        this.openCopyModal = true
      })
    },
    // 复制
    handleCopy () {
      const _this = this
      _this.spinning = true
      handleCopyData({ promotionSn: this.itemSn }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        }
        _this.itemSn = null
        _this.openCopyModal = false
        _this.spinning = false
      })
    },
    // 关闭复制弹窗
    closeCopyModal () {
      this.itemSn = null
      this.openCopyModal = false
    },
    // 促销时间变更
    handleTime (row) {
      this.editEndModal = true
      const showData = {
        sn: row.promotionSn,
        name: row.title,
        timeStart: row.promotionDateStart,
        timeEnd: row.promotionDateEnd
      }
      this.$refs.editTime.setData(showData)
    },
    // 终止
    handleEnd (row) {
      this.endObj = {
        sn: row.promotionSn,
        name: row.description,
        desc: row.overInfo || undefined
      }
      this.openEndActivityModal = true
    },
    closeEndActivityModal () {
      this.openEndActivityModal = false
      this.endObj = null
    },
    // 关闭采购退货详情弹框
    closeDetailModal () {
      this.itemSn = null
      this.openDetailModal = false
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除该活动吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          dealerPromotionDel({ sn: row.promotionSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 修改参与客户   参与客户提交审核
    editCustomerOk () {
      const _this = this
      midwaySubmit({ promotionSn: _this.itemPromotionSn }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        }
      })
    },
    // 参与客户
    auditCustomerOk (con) {
      const _this = this
      dealerMidwayAudit({ promotionSn: _this.itemPromotionSn, dealerAuditStatus: con }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        }
      })
    },
    // 关闭参与客户弹窗
    closeCustomer () {
      this.openCustomerModal = false
      this.itemPromotionSn = ''
      this.chooseDealerArr = []
    },
    //  重置
    resetSearchForm () {
      // 获取创建人默认值
      const creatorObj = this.$store.state.user.info
      const newObj = {
        key: creatorObj.userid,
        name: creatorObj.userNameCN,
        label: creatorObj.userNameCN
      }
      this.$refs.creatorList.setDefaultVal(newObj)
      this.queryParam = {
        beginDate: undefined,
        endDate: undefined,
        queryWord: '',
        enabledFlag: undefined, // 发布状态
        state: undefined,
        creatorId: creatorObj.userid,
        dealerAuditFlag: undefined,
        dealerSn: undefined
      }
      this.$refs.custList.resetForm()
      this.$refs.rangeDate.resetDate()
      this.$refs.table.refresh(true)
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.openDetailModal = false
      this.itemSn = null
      this.$refs.table.clearTable()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 235
    }
  },
  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.$refs.table.refresh()
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
  .promotionList-wrap{
    .nameBox{
     padding:0 5px;
    }
  }
  .joinCustomer{
    cursor:pointer;
  }
  .copyContent{
    margin:30px 10px 20px;
    p{
      margin-bottom:6px !important;
      font-size:14px;
    }
    p:last-child{
        font-size:12px;
        color:#666;
        text-align:right;
    }
  }
  .copyBtn{
    text-align:center;
    button{
      width: 45%;
      height:40px;
      line-height:40px;
    }
  }
  .tableBtnSet{
   display: flex;
   align-items: center;
   justify-content: space-between;
  }
</style>
