<template>
  <a-modal
    centered
    class="promotionAdd-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="promotionAdd-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-form-model-item label="促销名称" prop="name">
          <a-input id="promotionAdd-name" 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%"
            id="promotionAdd-time"
            v-model="form.time"
            :format="dateFormat"
            :disabled-date="disabledDate"
            @change="dateChange"
            :placeholder="['开始时间', '结束时间']" />
        </a-form-model-item>
        <a-form-model-item label="参与经销商" prop="dealerSnList">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-button type="primary" id="promotionAdd-addDealer" :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 :id="'promotionAdd-dealerList'+con.dealerSn" v-for="con in chooseDealerList" :key="con.dealerSn" @close="delBuyerName(con)">
                  {{ con.dealerName }}
                </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="promotionAdd-remark"
            :maxLength="500"
            v-model="form.description"
            placeholder="请输入备注(最多500个字符)"
            allowClear />
        </a-form-model-item>
      </a-form-model>
      <div class="btn-cont">
        <a-button id="promotionAdd-modal-cancel" @click="isShow = false" >取消</a-button>
        <a-button
          v-if="!isEdit"
          type="primary"
          style="margin-left: 15px;"
          :loading="spinning"
          id="promotion-modal-save"
          @click="handleSave">确定</a-button>
        <a-button
          v-else
          type="primary"
          style="margin-left: 15px;"
          :loading="spinning"
          id="promotion-modal-save"
          @click="handleEdit">确定</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 moment from 'moment'
// 组件
import chooseDealer from './chooseDealer'
// 接口
import { promoActiveCreate, promoActiveDetail, promoActiveUpdate } from '@/api/promoActive'
export default {
  name: 'PromotionAddModal',
  mixins: [commonMixin],
  components: { chooseDealer },
  props: {
    openModal: {//  弹框显示状态
      type: Boolean,
      default: false
    },
    itemId: {// 当前活动sn
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      openDealerModal: false, // 打开经销商弹窗
      formItemLayout: {// form表单  label布局设置
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      // 提交数据
      form: {
        promoActiveSn: undefined, // 活动sn
        name: '', // 促销名称
        time: [], // 促销时间
        activeDateStart: undefined, // 活动开始时间
        activeDateEnd: undefined, // 活动结束时间
        activeDateEnable: '1',
        description: '', // 促销描述
        dealerSnList: []// 参与经销商列表sn
      },
      // 表单必填项规则验证
      rules: {
        dealerSnList: [{ 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
      let arr = []
      if (_this.chooseDealerList.length == 0) {
        _this.form.dealerSnList = []
      } else {
        arr = _this.chooseDealerList.map(item => { return item.dealerSn })
      }
      // 选择经销商回显
      _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] + ' 00:00:00' : ''
        this.form.activeDateEnd = date.length ? dateStrings[1] + ' 23:59:59' : ''
      } else {
        this.form.time = []
      }
    },
    // 添加经销商
    handleAddDealer (list) {
      this.chooseDealerList = list
      this.openDealerModal = false
      // 移除表单必填项
      this.$refs.ruleForm.clearValidate('dealerSnList')
    },
    // 获取编辑详情
    getEditInfo () {
      promoActiveDetail({ sn: this.itemId }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.chooseDealerList = data.promoDealerList
          data.time = [data.activeDateStart, data.activeDateEnd]
          this.form = data
        }
      })
    },
    // 删除所选经销商
    delBuyerName (row) {
      const pot = this.chooseDealerList.findIndex(con => { return con.dealerSn == row.dealerSn })
      this.chooseDealerList.splice(pot, 1)
    },
    //  保存促销
    handleSave () {
      const _this = this
      const newArr = this.chooseDealerList.map(item => {
        return item.dealerSn
      })
      this.form.dealerSnList = newArr
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          delete form.time
          _this.spinning = true
          promoActiveCreate(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
        }
      })
    },
    // 修改促销
    handleEdit () {
      const _this = this
      const newArr = this.chooseDealerList.map(item => {
        return item.dealerSn
      })
      this.form.dealerSnList = newArr
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          delete form.time
          _this.spinning = true
          promoActiveUpdate(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
        }
      })
    },
    // 重置
    reSetForm () {
      this.$refs.ruleForm.resetFields()
      this.form = {
        promoActiveSn: undefined,
        name: '',
        time: [],
        activeDateStart: undefined,
        activeDateEnd: undefined,
        activeDateEnable: '1',
        buyerLimitEnable: '1',
        description: '',
        dealerSnList: []
      }
      this.isEdit = false
      this.chooseDealerList = []
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.reSetForm()
      } else {
        this.isEdit = !!this.itemId
        if (this.itemId) {
          this.getEditInfo()
        }
      }
    }
  }
}
</script>

<style lang="less">
.promotionAdd-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>
