<template>
  <a-modal
    centered
    class="promotion-modal"
    :footer="null"
    :maskClosable="false"
    :title="isEdit?'编辑':'新增'"
    v-model="isShow"
    @cancel="isShow = false"
    :width="900">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotion-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="促销名称" prop="name">
          <a-input v-model="form.name" placeholder="请输入促销名称（最多30个字符）" :maxLength="30"></a-input>
        </a-form-model-item>
        <a-form-model-item label="促销时间" prop="time">
          <a-range-picker
            style="width:100%"
            v-model="form.time"
            :format="dateFormat"
            :disabled-date="disabledDate"
            @change="dateChange"
            :placeholder="['开始时间', '结束时间']" />
        </a-form-model-item>
        <a-form-model-item label="参与经销商" prop="promoBuyerList">
          <a-row :gutter="15">
            <!-- <a-col :md="15" :sm="24">
              <a-select
                v-model="form.buyerLimitEnable"
                placeholder="请选择参与经销商"
              >
                <a-select-option :value="0">全部经销商</a-select-option>
                <a-select-option :value="1">部分经销商</a-select-option>
              </a-select>
            </a-col> -->
            <a-col :md="5" :sm="24">
              <a-button type="primary" :loading="spinning" @click="handleDealerModal">选择经销商</a-button>
            </a-col>
            <a-col :md="6" :sm="24" v-show="chooseDealerList && chooseDealerList.length>0">
              已{{ chooseDealerList.length }}选项
            </a-col>
            <a-col :md="24" :sm="24" v-show="chooseDealerList && chooseDealerList.length>0">
              <div class="buyerBox">
                <a-tag closable v-for="con in chooseDealerList" :key="con.buyerSn" @close="delBuyerName(con)">
                  {{ con.buyerName }}
                </a-tag>
              </div>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item style="margin-bottom:10px;" label="促销描述" prop="description" :wrapperCol="{ span: 16 }" :labelCol="{ span: 4 }">
          <a-textarea
            :rows="5"
            id="promotion-remark"
            :maxLength="500"
            v-model="form.description"
            placeholder="请输入备注(最多500个字符)"
            allowClear />
        </a-form-model-item>
      </a-form-model>
      <div class="btn-cont">
        <a-button id="promotion-modal-back" @click="isShow = false" >取消</a-button>
        <a-button type="primary" style="margin-left: 15px;" :loading="spinning" id="promotion-modal-save" @click="handleSave">确定</a-button>
      </div>
    </a-spin>
    <!-- 选择经销商 -->
    <a-modal
      title="选择经销商"
      :visible="openDealerModal"
      :footer="null"
      centered
      class="lookUpCustomers-modal"
      @cancel="openDealerModal = false"
      width="60%"
    >
      <div class="dealerModalCon">
        <chooseDealer ref="dealerChoose" @plAdd="handleAddDealer"></chooseDealer>
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { promoTerminalSave, promoTerminalDetail } from '@/api/promoTerminal'
import chooseDealer from './chooseDealer'
import moment from 'moment'
export default {
  name: 'PromotionAddModal',
  mixins: [commonMixin],
  components: { chooseDealer },
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemId: {
      //  弹框显示状态
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      openDealerModal: false,
      spinning: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      form: {
        promoActiveSn: undefined,
        name: '',
        time: [],
        activeDateStart: undefined,
        activeDateEnd: undefined,
        activeDateEnable: '1',
        buyerLimitEnable: '1',
        description: '',
        promoBuyerList: []
      },
      rules: {
        promoBuyerList: [{ required: true, message: '请选择参与经销商', trigger: 'change' }],
        time: [{ required: true, message: '请选择促销时间', trigger: 'change' }],
        name: [{ required: true, message: '请输入促销名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入促销描述', trigger: 'blur' }]
      },
      dateFormat: 'YYYY-MM-DD',
      isEdit: false,
      chooseDealerList: []// 选择经销商列表
    }
  },
  methods: {
    disabledDate (current) {
      return current && current < moment().startOf('day')
    },
    handleDealerModal () {
      this.openDealerModal = true
      const _this = this
      if (_this.chooseDealerList.length == 0) {
        _this.form.promoBuyerList = []
      }
      const arr = _this.chooseDealerList.map(item => {
        return item.buyerSn
      })
      // 选择经销商回显
      _this.$nextTick(() => {
        _this.$refs.dealerChoose.pageInit(arr)
      })
    },
    // 日期  change
    dateChange (date, dateStrings) {
      if (dateStrings && dateStrings[0]) {
        this.form.time = dateStrings
        this.form.activeDateStart = date.length ? dateStrings[0] : ''
        this.form.activeDateEnd = date.length ? dateStrings[1] : ''
      } else {
        this.form.time = []
      }
    },
    // 添加经销商
    handleAddDealer (list) {
      this.chooseDealerList = list.map(con => {
        return {
          buyerSn: con.dealerSn,
          buyerName: con.dealerName
        }
      })
      const newArr = list.map(item => {
        return {
          buyerSn: item.dealerSn
        }
      })
      this.form.promoBuyerList = newArr
      this.openDealerModal = false
      // 移除表单必填项
      this.$refs.ruleForm.clearValidate('promoBuyerList')
    },
    // 获取编辑详情
    getEditInfo () {
      promoTerminalDetail({ sn: this.itemId }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.chooseDealerList = data.promoBuyerList
          data.promoBuyerList = data.promoBuyerList.map(item => {
            return {
              buyerSn: item.buyerSn
            }
          })
          data.time = [data.activeDateStart, data.activeDateEnd]
          this.form = data
        }
      })
    },
    // 删除所选经销商
    delBuyerName (row) {
      const pot = this.chooseDealerList.findIndex(con => { return con.buyerSn == row.buyerSn })
      this.chooseDealerList.splice(pot, 1)
    },
    //  保存促销
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          delete form.time
          _this.spinning = true
          promoTerminalSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.isShow = false
              _this.$emit('ok', res.data)
            }
            _this.spinning = false
          })
        } else {
          _this.spinning = false
          return false
        }
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.ruleForm.resetFields()
        this.form = {
          promoActiveSn: undefined,
          name: '',
          time: [],
          activeDateStart: undefined,
          activeDateEnd: undefined,
          activeDateEnable: '1',
          buyerLimitEnable: '1',
          description: '',
          promoBuyerList: []
        }
        this.isEdit = false
        this.chooseDealerList = []
      } else {
        this.isEdit = !!this.itemId
        if (this.itemId) {
          this.getEditInfo()
        }
      }
    }
  }
}
</script>

<style lang="less">
.promotion-modal {
	.ant-modal-body {
		padding: 40px 40px 24px;
	}
  .buyerBox{
    border:1px solid #d9d9d9;margin-top:10px;border-radius:4px;padding:4px 10px;background:#f2f2f2;max-height:130px;overflow-y:scroll;
  }
	.btn-cont {
		text-align: center;
		margin: 35px 0 10px;
	}
}
</style>
