<template>
  <a-modal
    centered
    class="promotionAdd-modal"
    :footer="null"
    :maskClosable="false"
    :title="itemSn?'编辑':'新增'"
    v-model="isShow"
    @cancel="isShow=false"
    width="70%">
    <a-spin :spinning="spinning" tip="Loading...">
      <div class="promotionAdd-con">
        <a-form-model
          id="promotionAdd-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol">
          <a-row>
            <a-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="促销名称" prop="promoName" :label-col="{span:6}" :wrapper-col="{span:14}">
                <a-input
                  id="promotionAdd-promoName"
                  :maxLength="20"
                  v-model.trim="form.promoName"
                  placeholder="请输入促销名称(最多20个字符)"
                  allowClear/>
              </a-form-model-item>
            </a-col>
            <a-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <a-form-model-item label="促销时间" prop="time" :label-col="{span:6}" :wrapper-col="{span:14}">
                <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-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="排序" prop="sort">
                <a-input-number
                  style="width:37%"
                  id="promotionAdd-sort"
                  allowClear
                  placeholder="请输入排序数字(数字越大越靠后)"
                  v-model="form.sort"
                  :min="0"
                  :max="99999999"/>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="参与经销商" prop="allDealerFlag">
                <a-row :gutter="15">
                  <a-col :md="10" :sm="24">
                    <a-select
                      style="width:90%;"
                      id="promotionAdd-allDealerFlag"
                      v-model="form.allDealerFlag"
                      placeholder="请选择参与经销商"
                      @change="changeDealerScope"
                      allowClear>
                      <a-select-option id="promotionAdd-dealerScope-all" value="1">全部经销商</a-select-option>
                      <a-select-option id="promotionAdd-dealerScope-some" value="0">部分经销商</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :md="3" :sm="24" v-show="form.allDealerFlag && form.allDealerFlag!='1' ">
                    <a-button id="promotionAdd-dealerScope" type="primary" :loading="spinning" @click="handleDealerModal">选择</a-button>
                  </a-col>
                  <a-col :md="5" :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" id="promotionAdd-dealerSn" :key="con.dealerSn" @close="delBuyerName(con)">
                        {{ con.dealerName }}
                      </a-tag>
                    </div>
                  </a-col>
                </a-row>
              </a-form-model-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="imageUrl_box">
              <a-form-model-item label="封面图片" prop="imageUrl">
                <Upload
                  class="upload"
                  id="promotionAdd-imageUrl"
                  v-model="form.imageUrl"
                  ref="imageSet"
                  :fileSize="10"
                  :maxNums="1"
                  @change="changeImage"
                  listType="picture-card"></Upload>
                <div class="upload-desc">说明：单张大小小于10Mb；建议尺寸：宽（750px）*高（300px）</div>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="促销描述" prop="description">
                <a-input
                  v-model="form.description"
                  type="textarea"
                  id="promotionAdd-description"
                  placeholder="请输入促销描述（最多500个字符）"
                  :maxLength="500" />
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="加盟商开关权限" prop="dealerOpenFlag">
                <v-select
                  v-model="form.dealerOpenFlag"
                  id="promotionAdd-dealerOpenFlag"
                  code="FLAG"
                  showType="radio"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <div class="btn-cont">
          <a-button id="promotionAdd-close-btn" style="margin-right: 15px;" @click="isShow = false">取消</a-button>
          <a-button
            type="primary"
            class="button-primary"
            :disabled="spinning"
            id="promotionAdd-submit-btn"
            @click="handleSave()">保存</a-button>
        </div>
      </div>
    </a-spin>
    <!-- 选择经销商 -->
    <chooseDealer ref="chooseDearler" :openModal="openDealerModal" :chooseInfo="chooseSnList" @close="closeDealerModal" @ok="addDealerOk"></chooseDealer>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { STable, VSelect, Upload } from '@/components'
import chooseDealer from '@/views/easyPassManagement/homepageCarouselImg/chooseDealer'
// 接口
import { shopPromoDetail, saveShopPromo } from '@/api/shopPromo'

export default {
  name: 'AddPromotionModal',
  mixins: [commonMixin],
  components: { STable, VSelect, Upload, chooseDealer },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {// 活动sn
      type: String,
      default: ''
    },
    typeVal: {// 添加活动类型
      type: String,
      default: ''
    },
    chooseProductNum: {
      type: [String, Number],
      default: null
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false, // 页面加载状态
      // form表单label布局
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 19 }
      },
      dateFormat: 'YYYY-MM-DD', // 促销时间显示格式
      chooseDealerList: [], // 已选择的经销商列表
      chooseSnList: [], // 已选经销商sn集合
      openDealerModal: false, // 经销商弹窗
      isAllDealerFlag: null, // 是否是全部经销商
      form: {
        promoType: undefined, // 促销类型
        promoName: '', // '促销名称'
        time: [], // 促销时间
        promoStartDate: undefined, // 促销时间-开始
        promoEndDate: undefined, // 促销时间-结束
        sort: undefined, // 排序
        allDealerFlag: '1', // 全部经销商 1   部分经销商0'
        imageUrl: undefined, // 促销封面图
        description: '', // '促销描述'
        dealerEditFlag: '0', // 加盟商编辑 0否 1是
        dealerOpenFlag: '0' // 加盟商开关权限 0否 1是
      },
      // 表单验证规则
      rules: {
        promoName: [{ required: true, message: '请输入促销名称', trigger: 'blur' }],
        time: [{ required: true, message: '请选择促销时间', trigger: 'change' }],
        sort: [{ required: true, message: '请输入排序数字', trigger: 'blur' }],
        allDealerFlag: [{ required: true, message: '请选择参与经销商', trigger: 'change' }],
        imageUrl: [{ required: true, message: '请选择要上传的封面图片', trigger: 'change' }],
        description: [{ required: true, message: '请输入促销描述内容', trigger: 'blur' }],
        dealerOpenFlag: [{ required: true, message: '请选择加盟商开关权限', trigger: 'change' }]
      }
    }
  },
  methods: {
    //  封面图片上传
    changeImage (file) {
      this.form.imageUrl = file
    },
    // 参与经销商 change
    changeDealerScope (val) {
      const _this = this
      _this.form.allDealerFlag = val
      if (val == '1' || !val) {
        _this.chooseDealerList = []
      }
    },
    // 部分 打开选择经销商弹窗
    handleDealerModal () {
      this.chooseSnList = this.chooseDealerList.map(item => item.dealerSn)
      this.openDealerModal = true
    },
    // 关闭 选择经销商弹窗
    closeDealerModal () {
      this.chooseSnList = []
      this.openDealerModal = false
    },
    // 部分经销商  选择经销商成功
    addDealerOk (list) {
      const _this = this
      _this.chooseDealerList = list
      _this.openDealerModal = false
    },
    // 部分经销商 删除
    delBuyerName (row) {
      const pos = this.chooseDealerList.findIndex(item => item.dealerSn == row.dealerSn)
      if (pos >= 0) {
        this.chooseDealerList.splice(pos, 1)
      }
    },
    // 禁用日期时间
    disabledDate (current) {
      return current && current < moment().startOf('day')
    },
    // 促销时间  change
    dateChange (date, dateStrings) {
      if (dateStrings && dateStrings[0]) {
        this.form.time = dateStrings
        this.form.promoStartDate = date.length ? dateStrings[0] + ' 00:00:00' : ''
        this.form.promoEndDate = date.length ? dateStrings[1] + ' 23:59:59' : ''
      } else {
        this.form.time = []
      }
    },
    // 保存
    handleSave () {
      const _this = this
      // 验证组件必填项
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.form.promoType = _this.typeVal
          var formData = JSON.parse(JSON.stringify(_this.form))
          // 部分经销商
          if (formData.allDealerFlag == '0') {
            if (_this.chooseDealerList && _this.chooseDealerList.length == 0) {
              _this.$message.warning('请选择参与经销商！')
              return
            }
            formData.dealerSnList = _this.chooseDealerList.map(con => con.dealerSn)
          }
          if (_this.itemSn && _this.itemSn.length > 0) {
            const hasEq = _this.chooseDealerList.filter(item => !formData.shopPromoDealerList.map(k => k.dealerSn).includes(item.dealerSn)) // 经销商是否变更
            const hasEq1 = _this.isAllDealerFlag == 0 && formData.allDealerFlag == 1 // 部分变全部
            const hasChange = _this.isAllDealerFlag == 0 && _this.isAllDealerFlag == formData.allDealerFlag // 是否部分经销商未变更
            console.log(hasEq, hasEq1)
            if (_this.chooseProductNum > 0 && (hasChange && hasEq && hasEq.length > 0 || hasEq1)) {
              _this.$confirm({
                title: '提示',
                content: <div>变更【参与经销商】后将会【<span style="color:red">清空</span>】已选产品列表，确定变更吗？</div>,
                centered: true,
                onOk () {
                  _this.saveSuccess(formData, '1')
                }
              })
            } else {
              _this.saveSuccess(formData, '0')
            }
          } else {
            _this.saveSuccess(formData, '0')
          }
        }
      })
    },
    saveSuccess (ajaxData, type) {
      const _this = this
      _this.spinning = true
      delete ajaxData.time
      delete ajaxData.shopPromoDealerList
      ajaxData.saveType = 'alone'
      saveShopPromo(ajaxData).then(res => {
        if (res.status == 200) {
          _this.spinning = false
          if (res.data.errorMsg && res.data.errorMsg.length > 0) {
            this.$confirm({
              title: '提示',
              content: res.data.errorMsg.map((item, i) => { return <p>{i * 1 + 1}、{item}</p> }),
              centered: true,
              okText: '知道了',
              cancelText: '取消', // 将cancelText设置为空字符串或去掉该属性可以隐藏取消按钮
              cancelButtonProps: {
                style: {
                  display: 'none' // 通过设置样式隐藏取消按钮
                }
              },
              onOk () {
                console.log('知道了')
              }
            })
            return
          }
          _this.$message.success(res.message)
          _this.$nextTick(() => {
            _this.isShow = false
            _this.$emit('ok', type)
          })
        } else {
          _this.spinning = false
        }
      })
    },
    // 重置
    resetSearchForm () {
      this.form = {
        promoType: undefined, // 促销类型
        promoName: '', // '促销名称'
        time: [], // 促销时间
        promoStartDate: undefined, // 促销时间-开始
        promoEndDate: undefined, // 促销时间-结束
        sort: undefined, // 排序
        allDealerFlag: '1', // 全部经销商 1   部分经销商0'
        imageUrl: undefined, // 促销封面图
        description: '', // '促销描述'
        dealerEditFlag: '0', // 加盟商编辑 0否 1是
        dealerOpenFlag: '0' // 加盟商开关权限 0否 1是
      }
      this.chooseDealerList = []
      if (this.$refs.imageSet) {
        this.$refs.imageSet.setFileList('')
      }
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
    },
    //  详情
    async getDetail () {
      const _this = this
      const res = await shopPromoDetail({ sn: _this.itemSn })
      if (res.status == 200) {
        if (res.data.promoStartDate && res.data.promoEndDate) {
          const startTime = res.data.promoStartDate.split(' ')[0]
          const endTime = res.data.promoEndDate.split(' ')[0]
          res.data.time = [startTime, endTime]
        }
        if (res.data.imageUrl) {
          _this.$refs.imageSet.setFileList(res.data.imageUrl)
        }
        _this.form = res.data
        _this.isShowNextStep = true
        if (_this.$route.params.pageType === 'edit') {
          _this.pageType = res.data.promoType
          _this.promotionName = res.data.promoName
        }
        _this.isAllDealerFlag = _this.form.allDealerFlag // 存储是否是全部经销商
        // 部分经销商
        if (_this.form.allDealerFlag == 0) {
          _this.chooseDealerList = _this.form.shopPromoDealerList
        }
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .promotionAdd-modal{
    /deep/.imageUrl_box .ant-form-item-control{
      line-height:0 !important;
    }
    .upload-desc{// 商品图片描述
    padding-top:10px;
      font-size: 12px;
      color: #808695;
    }
    .buyerBox{
      border:1px solid #d9d9d9;
      margin-top:10px;
      border-radius:4px;
      padding:4px 10px;
      background:#f2f2f2;
      max-height:130px;
      overflow-y:scroll;
      scrollbar-width: none;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }

</style>
