<template>
  <div class="promotionEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="promotionEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="promotionEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" />返回列表</a>
          <span v-if="$route.params.sn" style="margin: 0 10px 0 20px;color: #666;font-size: 14px;font-weight: 600;">促销名称：{{ promotionName||'--' }}</span>
          <a-button
            type="link"
            class="button-primary"
            id="promotionEdit-edit-btn"
            @click.stop="handleEdit">
            <a-icon type="edit"/>编辑
          </a-button>
          <a-button type="link" size="small" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
      </a-page-header>
      <div ref="tableSearch">
        <a-card size="small" :bordered="false" class="promotionEditInfo" v-show="showDetail">
          <div slot="title">
            <span>基础信息</span>
          </div>
          <div v-if="form">
            <a-descriptions>
              <a-descriptions-item label="促销名称">{{ form.promoName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="促销类型">{{ form.promoTypeDictValue || '--' }}</a-descriptions-item>
              <a-descriptions-item label="促销时间">
                {{ form.promoStartDate }}{{ form.promoStartDate?' ~ ':'' }}{{ form.promoEndDate }}
              </a-descriptions-item>
              <a-descriptions-item label="排序">{{ (form.sort||form.sort==0)? form.sort: '--' }}</a-descriptions-item>
              <a-descriptions-item label="加盟商开关权限">{{ form.dealerOpenFlag=='0'?'否':'是' }}</a-descriptions-item>
              <a-descriptions-item label="参与经销商" v-if="form.allDealerFlag=='1'">全部经销商</a-descriptions-item>
              <a-descriptions-item label="参与经销商" v-else>
                <span v-if="!form.shopPromoDealerList||(form.shopPromoDealerList&&form.shopPromoDealerList.length==0)">--</span>
                <div v-else @click="handleSee">共<span class="link-bule">{{ form.shopPromoDealerList.length }}</span>个</div>
              </a-descriptions-item>
              <a-descriptions-item :span="3" label="封面图片"><img @click="handleCheckImg" :src="form.imageUrl" alt="图片走丢了" width="60" height="60" /></a-descriptions-item>
              <a-descriptions-item :span="3" label="促销描述">{{ form.description || '--' }}</a-descriptions-item>
            </a-descriptions>
          </div>
        </a-card>
      </div>
      <!-- 表单 -->
      <a-card :bordered="false" class="promotionEdit-cont">
        <a-form-model
          id="promotionEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-row>
            <!-- 买产品送代金券 -->
            <div v-if="pageType=='BUY_PROD_GIVE_VALID'">
              <a-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
                <a-form-model-item label="券名称" :label-col="{span:4}" :wrapper-col="{span:16}" prop="validName">
                  <a-input
                    id="promotionEdit-validName"
                    :maxLength="20"
                    v-model.trim="form.validName"
                    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="券副标题" :label-col="{span:4}" :wrapper-col="{span:16}">
                  <a-input
                    id="promotionEdit-validTitle"
                    :maxLength="20"
                    v-model.trim="form.validTitle"
                    placeholder="请输入券副标题(最多20个字符)"
                    allowClear />
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-form-model-item label="券有效期" prop="validType">
                  <v-select
                    style="width:40%;"
                    v-model="form.validType"
                    placeholder="请选择券有效期"
                    id="promotionEdit-validType"
                    code="SHOP_PROMO_VALID_TYPE"
                    @change="handleValidType"
                    allowClear></v-select>
                  <a-range-picker
                    v-show="form.validType==='FIXED'"
                    style="width:40%;margin-left:10px;"
                    v-model="timeLimit"
                    :format="dateFormat"
                    id="promotionEdit-time"
                    @change="dateLimitChange"
                    :disabled-date="disabledDate"
                    :placeholder="['开始时间', '结束时间']" />
                  <span style="width:40%;margin-left:10px;" v-show="form.validType==='LIMIT'">
                    有效期<a-input-number
                      style="margin:0 5px;"
                      v-model="form.validDays"
                      :step="1"
                      id="promotionEdit-validDays"
                      :max="99999999"
                      :min="1"
                      :precision="0"/>天
                  </span>
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-form-model-item label="券适用范围" required>
                  全部产品
                </a-form-model-item>
              </a-col>
              <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-form-model-item label="使用说明" prop="validInfo">
                  <a-input
                    v-model="form.validInfo"
                    type="textarea"
                    id="promotionEdit-validInfo"
                    placeholder="请输入使用说明（最多50个字符）"
                    :maxLength="50" />
                </a-form-model-item>
              </a-col>
            </div>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item prop="productNum" :label="pageType==='BUY_PROD_GIVE_PROD'?'满赠规则': pageType==='PROMO_PROD'?'优惠方式':'返券产品'">
                <div class="productInfo flex-center">
                  <div style="width:80%;">
                    <!-- 买产品送产品 -->
                    <div v-if="pageType==='BUY_PROD_GIVE_PROD'">
                      同款产品买<a-input-number
                        v-model="conditionValue"
                        style="margin:0 5px;"
                        :min="1"
                        :step="1"
                        :precision="0"
                        :max="99999999"
                        id="promotionEdit-conditionValue"
                        size="small"/>赠
                      <a-input-number
                        v-model="resultValue"
                        style="margin:0 5px;"
                        :min="0"
                        :step="1"
                        :precision="0"
                        :max="99999999"
                        id="promotionEdit-resultValue"
                        size="small"/>个（数量叠加）
                      <a-button
                        type="primary"
                        id="promotionEdit-addSet-btn"
                        class="button-primary"
                        size="small"
                        @click="handleBatchAdd">批量设置</a-button>
                      <span>已选 {{ porductChooseTotal || 0 }} 项</span>
                    </div>
                    <!-- 特价产品 -->
                    <div v-if="pageType==='PROMO_PROD'">
                      <v-select
                        v-model="form.discountType"
                        ref="promoState"
                        id="promotionList-discountType"
                        code="SHOP_PROMO_DISCOUNT_TYPE"
                        size="small"
                        style="width:20%;margin-right:5px;"
                        @change="handleDiscountType"
                        placeholder="请选择"
                        allowClear></v-select>
                      <span v-if="form.discountType">{{ form.discountType==='STRAIGHT_DOWN'? '直降':'折扣' }}</span>
                      <a-input-number
                        v-model="resultValue"
                        v-if="form.discountType"
                        style="width:20%;margin:0 5px;"
                        :min="0"
                        :step="1"
                        :precision="2"
                        :max="99999999"
                        id="promotionEdit-resultValue"
                        size="small"/><span v-show="form.discountType">{{ form.discountType==='STRAIGHT_DOWN'? '元':'%' }}</span>
                      <a-button
                        type="primary"
                        id="promotionEdit-addSet-btn"
                        class="button-primary"
                        size="small"
                        @click="handleBatchAdd">批量设置</a-button>
                      <span>已选 {{ porductChooseTotal || 0 }} 项</span>
                    </div>
                    <!-- 买产品返代金券 -->
                    <div v-if="pageType=='BUY_PROD_GIVE_VALID'">
                      返券金额
                      <a-input-number
                        v-model="resultValue"
                        style="margin:0 5px;"
                        :min="0"
                        :step="1"
                        :precision="2"
                        :max="99999999"
                        id="promotionEdit-resultValue"
                        size="small"/>元
                      <a-button
                        type="primary"
                        id="promotionEdit-addSet-btn"
                        class="button-primary"
                        size="small"
                        @click="handleBatchAdd">批量设置</a-button>
                      <span>已选 {{ porductChooseTotal || 0 }} 项</span>
                    </div>
                  </div>
                  <div style="width:20%;text-align:right;" >
                    <a-button type="primary" id="promotionEdit-add-btn" @click="handleChooseProduct" size="small">选择产品</a-button>
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div style="width: 83%;margin:0 auto 10px;">
                <productTable ref="chooseProductList" @changeSel="v=>porductChooseTotal=v" :promoActiveSn="form.promoSn" :discountType="form.discountType" :activeType="pageType"></productTable>
              </div>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        type="primary"
        class="button-primary"
        :disabled="spinning"
        id="productInfoEdit-submit-btn"
        size="large"
        @click="handleSaveAll"
        style="padding: 0 60px;">保存</a-button>
    </div>
    <!-- 添加产品 -->
    <chooseProduct :propmSn="$route.params.sn" :openModal="showProModal" @ok="addProductSuccess" @close="closeProductModal"></chooseProduct>
    <!--编辑  促销活动  基础信息    -->
    <add-promotion-modal
      ref="promotionAddModal"
      :openModal="openAddModal"
      :typeVal="form.promoType"
      :chooseProductNum="form.productNum"
      :itemSn="$route.params.sn"
      @close="openAddModal=false"
      @ok="promotionAddOk" ></add-promotion-modal>
    <!-- 参与经销商 -->
    <lookUp-customers-modal ref="lookUpCustomers" :openModal="openCustomerModal" @close="openCustomerModal = false"></lookUp-customers-modal>
    <!-- 封面展示 -->
    <imgShowModal v-drag ref="checkedImg" :openModal="openCheckedImgModal" @close="openCheckedImgModal=false"></imgShowModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { VSelect, Upload } from '@/components'
import Editor from '@/components/WEeditor'
import productTable from './productTable'
import chooseProduct from './chooseProductsModal.vue'
import addPromotionModal from './addPromotionModal'
import lookUpCustomersModal from './lookUpCustomersModal'
import imgShowModal from '@/views/easyPassManagement/shoppingManagement/imgShowModal'
// 接口
import { saveChooseProduct, saveShopPromo, shopPromoDetail } from '@/api/shopPromo'
export default {
  name: 'ProductBrandEditModal',
  mixins: [commonMixin],
  components: { VSelect, Upload, Editor, productTable, chooseProduct, addPromotionModal, lookUpCustomersModal, imgShowModal },
  data () {
    return {
      spinning: false,
      // 表单 label 设置
      formItemLayout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 20 }
      },
      dateFormat: 'YYYY-MM-DD', // 促销时间显示格式
      openDealerModal: false, // 打开选择经销商弹窗
      pageType: undefined, // 促销类型
      showDetail: true, // 是否显示基础信息
      openAddModal: false, // 基础信息编辑弹窗
      openCheckedImgModal: false, // 查看图片弹窗
      // 链接配置内容
      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是
        rangeList: [], // 选择产品列表
        discountType: '', // 特价产品 - 优惠方式'
        validName: '', // 券名称
        validTitle: '', // 券副标题
        validBaseType: 'category', // 券生成方式
        validType: undefined, // 券有效期类型
        validStartDate: undefined, // 券生效时间
        validEndDate: undefined, // 券失效时间
        validDays: undefined, // 券有效期天数
        validScope: '1', // 券适用范围标记 1-全部 0-指定  死值 1
        validInfo: '', // 使用说明
        productNum: 0
      },
      conditionValue: undefined, // 买产品送产品 买
      resultValue: undefined, // 买产品送产品  赠  返券金额
      porductChooseTotal: 0, // 已选产品总数
      timeLimit: [], // 有效期
      promotionName: '', // 促销名称
      showProModal: false, // 打开产品弹窗
      openCustomerModal: false, // 打开参与经销商弹窗
      // 表单验证规则
      rules: {
        rangeList: [{ required: true, message: '请选择促销产品', trigger: 'change' }],
        validName: [{ required: true, message: '请输入券名称', trigger: ['change', 'blur'] }],
        validBaseType: [{ required: true, message: '请选择生成方式', trigger: 'change' }],
        validType: [{ required: true, message: '请选择券有效期类型', trigger: 'change' }],
        productNum: [{ required: true, message: '选择产品不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 查看封面图片
    handleCheckImg () {
      this.openCheckedImgModal = true
      const _this = this
      _this.$nextTick(() => {
        _this.$refs.checkedImg.pageInit(this.form.imageUrl)
      })
    },
    // 查看参与经销商
    handleSee () {
      this.openCustomerModal = true
      this.$nextTick(() => {
        this.$refs.lookUpCustomers.pageInit({ dealerSnList: this.form.dealerSnList || undefined })
      })
    },
    // 编辑
    handleEdit () {
      this.openAddModal = true
      this.form.productNum = this.$refs.chooseProductList.getChooseProductNum()
      this.$refs.promotionAddModal.getDetail()
    },
    promotionAddOk (type) {
      const _this = this
      // 情况产品列表
      if (type == '1') {
        _this.$refs.chooseProductList.clearTable()
      }
      _this.getDetail({ sn: _this.$route.params.sn })
    },
    // 禁用日期时间
    disabledDate (current) {
      return current && current < moment().startOf('day')
    },
    // 有效期
    dateLimitChange (date, dateStrings) {
      if (dateStrings && dateStrings[0]) {
        this.timeLimit = dateStrings
        this.form.validStartDate = date.length ? dateStrings[0] + ' 00:00:00' : ''
        this.form.validEndDate = date.length ? dateStrings[1] + ' 23:59:59' : ''
      } else {
        this.timeLimit = []
      }
    },
    // 选择优惠方式 change
    async handleDiscountType (val) {
      this.form.discountType = val
      this.resultValue = undefined
    },
    // 添加产品
    handleChooseProduct () {
      this.showProModal = true
    },
    // 添加产品成功
    addProductSuccess (list) {
      const productArr = list.map(item => {
        const obj = {
          promoSn: this.form.promoSn,
          shopProductSn: item.shopProductSn,
          productSn: item.productSn,
          productCode: item.productCode
        }
        if (this.pageType === 'PROMO_PROD') {
          obj.conditionValue = item.conditionValue ? item.conditionValue : item.shopProductPrice
        }
        return obj
      })
      saveChooseProduct(productArr).then(res => {
        if (res.status == 200) {
          if (!res.data) {
            this.showProModal = false
            // 获取产品列表 有分页
            this.$refs.chooseProductList.pageInit()
          } else {
            const tipArr = res.data ? res.data.split(';') : []
            const newTipArr = tipArr.filter(item => { return item != '' })
            const _this = this
            this.$confirm({
              title: '提示',
              content: newTipArr.map((item, i) => { return <p>{i * 1 + 1}、{item}</p> }),
              centered: true,
              okText: '知道了',
              cancelText: '取消', // 将cancelText设置为空字符串或去掉该属性可以隐藏取消按钮
              cancelButtonProps: {
                style: {
                  display: 'none' // 通过设置样式隐藏取消按钮
                }
              },
              onOk () {
                _this.showProModal = false
                // 获取产品列表 有分页
                _this.$refs.chooseProductList.pageInit()
              }
            })
          }
        }
      })
    },
    // 关闭产品弹窗
    closeProductModal () {
      this.showProModal = false
    },
    // 返回列表
    handleBack () {
      this.$router.push({ name: 'promotionalActivities', query: { closeLastOldTab: true } })
    },
    //  详情
    async getDetail (ajaxData) {
      const _this = this
      const res = await shopPromoDetail(ajaxData)
      if (res.status == 200) {
        _this.form = { ..._this.form, ...res.data }
        _this.form.productNum = 0
        if (_this.$route.params.pageType === 'edit') {
          _this.pageType = res.data.promoType
          _this.promotionName = res.data.promoName
        }
        // 买产品送代金券
        if (_this.form.promoType == 'BUY_PROD_GIVE_VALID' && _this.form.validType == 'FIXED') {
          // 固定日期
          _this.timeLimit = [res.data.validStartDate, res.data.validEndDate]
        }
        _this.$nextTick(() => {
          _this.$refs.chooseProductList.pageInit()
        })
      }
    },
    // 券有效期 change
    handleValidType (con) {
      this.form.validType = con
      if (con === 'FIXED') {
        this.form.validDays = undefined
      } else {
        this.timeLimit = []
        this.form.validStartDate = undefined
        this.form.validEndDate = undefined
      }
    },
    //  确定保存  验证必填
    handleSaveAll () {
      const _this = this
      // 验证组件必填项
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.savePartInfo()
        }
      })
    },
    // 保存
    savePartInfo (type) {
      const _this = this
      _this.form.promoType = _this.pageType
      var formData = JSON.parse(JSON.stringify(_this.form))
      if (formData.promoType === 'BUY_PROD_GIVE_VALID') {
        if (formData.validType === 'FIXED') {
          if (!formData.validStartDate || !formData.validEndDate) {
            _this.$message.warning('请输入券有效期！')
            return false
          }
        } else {
          if (!formData.validDays) {
            _this.$message.warning('请输入券有效期！')
            return false
          }
        }
      }
      formData.productNum = _this.$refs.chooseProductList.getChooseProductNum()
      if (formData.productNum && formData.productNum == 0) {
        _this.$message.warning('请先选择产品！')
        return
      }
      delete formData.productNum
      _this.spinning = true
      formData.saveType = 'all'
      saveShopPromo(formData).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.handleBack()
            _this.resetSearchForm()
          })
        } 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是
        rangeList: [], // 选择产品列表
        discountType: '', // 特价产品 - 优惠方式'
        validName: '', // 券名称
        validTitle: '', // 券副标题
        validBaseType: 'category', // 券生成方式
        validType: undefined, // 券有效期类型
        validStartDate: undefined, // 券生效时间
        validEndDate: undefined, // 券失效时间
        validDays: undefined, // 券有效期天数
        validScope: '1', // 券适用范围标记 1-全部 0-指定  死值 1
        validInfo: '', // 使用说明
        productNum: 0
      }
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
    },
    // 批量设置
    handleBatchAdd () {
      if (!this.conditionValue && !this.resultValue) {
        this.$message.warning('请输入促销优惠规则！')
        return
      }
      this.$refs.chooseProductList.editMorePrice({ conditionValue: this.conditionValue, resultValue: this.resultValue })
    },
    // 初始化
    pageInit () {
      this.form.discountType = ''
      this.getDetail({ sn: this.$route.params.sn })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less" scoped>
.promotionEdit-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    padding-bottom:51px;
    .promotionEditInfo{
      margin-bottom:10px;
    }
    .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;
    }
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    /deep/.ant-form-item{
      margin-bottom:8px;
    }
     // .ant-form-item-control
    .promotionEdit-cont{
      margin-bottom: 10px;
    }
    //  文本编辑器  工具栏样式换行
    .promotionEdit-editor{
      .w-e-toolbar{
        flex-wrap: wrap;
        z-index: 0;
      }
    }
    //  商品图片描述
    .upload-desc{
      font-size: 12px;
      color: #808695;
    }
    #promotionEdit-attachList{
      height: auto;
    }
    .box{
      border:1px solid #d9d9d9;
      border-radius:4px;
      padding:4px 11px;
      color:rgba(0, 0, 0, 0.25);
      cursor: not-allowed;
      background:#fdfdfd;
    }
    .affix{
      .ant-affix{
        z-index: 101;
        display:inline-block
      }
    }
    /deep/.ant-radio-disabled + span{
     color:#000!important;
    }
    .tip{
      margin-left:10px;
    }

    .productInfo{
      width:100%;
      display:flex;
    }
    #setPromotion-productRange{
      /deep/.ant-select-dropdown{
        max-height:30vh !important;
      }
    }
  }
</style>
