<template>
  <div class="carouselImageEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="carouselImageEdit-cont" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="carouselImageEdit-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;">促销名称：{{ form.bannerName||'--' }}</span>
        </template>
      </a-page-header>
      <!-- 表单 -->
      <a-card :bordered="false" class="carouselImageEdit-cont">
        <a-form-model
          id="carouselImageEdit-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="bannerName" :label-col="{span:4}" :wrapper-col="{span:16}">
                <a-input
                  id="carouselImageEdit-bannerName"
                  :maxLength="30"
                  :disabled="isDisabled"
                  v-model.trim="form.bannerName"
                  placeholder="请输入轮播图名称(最多30个字符)"
                  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:4}" :wrapper-col="{span:16}">
                <a-range-picker
                  v-model="form.time"
                  style="width:100%"
                  :format="dateFormat"
                  id="carouselImageEdit-time"
                  @change="dateChange"
                  :disabled="isDisabled"
                  :disabled-date="disabledDate"
                  :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:40%"
                  id="carouselImageEdit-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:98%;"
                      id="carouselImageEdit-allDealerFlag"
                      v-model="form.allDealerFlag"
                      placeholder="请选择参与经销商"
                      @change="changeDealerScope"
                      :disabled="isDisabled"
                      allowClear>
                      <a-select-option id="promotionList-dealerScope-all" value="1">全部经销商</a-select-option>
                      <a-select-option id="promotionList-dealerScope-some" value="0">部分经销商</a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :md="2" :sm="24" v-show="form.allDealerFlag && form.allDealerFlag!='1' ">
                    <a-button id="promotionList-basicInfo-dealerScope" type="primary" :loading="spinning" :disabled="isDisabled" @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="!isDisabled" v-for="con in chooseDealerList" id="promotionList-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">
              <a-form-model-item label="封面图片" prop="imageUrl">
                <Upload
                  class="upload"
                  id="carouselImageEdit-imageUrl"
                  v-model="form.imageUrl"
                  ref="imageSet"
                  :fileSize="10"
                  :maxNums="1"
                  @change="changeImage"
                  listType="picture-card"></Upload>
                <span class="upload-desc">说明：单张大小小于10Mb；建议尺寸：宽（750px）*高（300px）</span>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="内容类型" prop="contentType">
                <v-select
                  v-model="form.contentType"
                  id="carouselImageEdit-contentType"
                  code="PROMO_CONTENT_TYPE"
                  showType="radio"
                  :notIn="notShowSel"
                  :disabled="isDisabled"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <a-form-model-item label="内容" prop="content" v-show="form.contentType =='IMAGE_CONTENT'">
                <editor
                  v-show="!isDisabled"
                  id="carouselImageEdit-editor"
                  ref="editor"
                  class="carouselImageEdit-editor"
                  @on-change="editorChange"
                  :cache="false"></editor>
                <div style="border:1px solid #efefef;border-radius:8px;padding:10px 20px;" v-if="isDisabled" v-html="form.content"></div>
              </a-form-model-item>
              <a-form-model-item label="上传视频" prop="content" v-show="form.contentType =='VIDEO'">
                <Upload
                  class="upload"
                  id="carouselImageEdit-videoSet"
                  v-model="form.content"
                  fileType="video/mp4"
                  ref="videoSet"
                  :disabled="isDisabled"
                  :fileSize="100"
                  :maxNums="1"
                  @change="changeVideo"
                ></Upload>
                <span class="upload-desc">说明：文件最大100M；视频：mp4.avi.flv</span>
              </a-form-model-item>
              <a-form-model-item label="跳转链接" prop="contentLink" v-if="form.contentType =='LINK'">
                <a-input
                  style="width:50%;"
                  :disabled="isDisabled"
                  id="carouselImageEdit-contentLink"
                  :maxLength="100"
                  v-model.trim="form.contentLink"
                  placeholder="请输入跳转链接"
                  allowClear />
              </a-form-model-item>
            </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="carouselImageEdit-submit-btn"
        size="large"
        @click="handleSave('all')"
        style="padding: 0 60px;">保存</a-button>
    </div>
    <!-- 选择经销商 -->
    <chooseDealer :openModal="openDealerModal" ref="dealerChoose" :disabledList="chooseSnList" @close="closeDealerModal" @ok="addDealerOk"></chooseDealer>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { VSelect, Upload } from '@/components'
import Editor from '@/components/WEeditor'
import chooseDealer from './chooseDealer'
// 接口
import { saveShopBanner, shopBannerDetail } from '@/api/shopBanner'

export default {
  name: 'CarouselImageEdit',
  mixins: [commonMixin],
  components: { VSelect, Upload, Editor, chooseDealer },
  data () {
    return {
      spinning: false,
      // 表单 label 设置
      formItemLayout: {
        labelCol: { span: 2 },
        wrapperCol: { span: 20 }
      },
      chooseDealerList: [], // 已选经销商数据
      openDealerModal: false, // 打开选择经销商弹窗
      isDisabled: false,
      // 链接配置内容
      form: {
        bannerSn: undefined, // 轮播图sn
        bannerName: '', // 轮播图名称
        time: [], // 轮播时间
        bannerStartDate: undefined,
        bannerEndDate: undefined,
        sort: undefined, // 排序
        allDealerFlag: '1', // 参与经销商 0 部分 1全部
        dealerSnList: [], // 已选经销商sn列表
        imageUrl: '', // 图片
        contentType: 'LINK', // 内容类型
        content: '', // 内容
        contentLink: '', // 内容链接
        state: 'UNPUBLISH'// 发布状态
      },
      chooseSnList: [],
      dateFormat: 'YYYY-MM-DD', // 有效期时间格式
      notShowSel: ['PROMO_LINK'], // 是否显示促销活动选择按钮
      // 表单验证规则
      rules: {
        bannerName: [{ 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' }],
        contentType: [{ required: true, message: '请选择内容类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入对应内容', trigger: ['blur', 'change'] }],
        contentLink: [{ required: true, message: '请输入对应内容', trigger: ['blur', 'change'] }]
      }
    }
  },
  methods: {
    // 部分经销商  选择经销商成功
    addDealerOk (list) {
      const dealerArr = list.map(item => {
        return {
          dealerName: item.dealerName,
          dealerSn: item.dealerSn
        }
      })
      this.chooseDealerList = dealerArr
      this.openDealerModal = false
    },
    // 禁用日期时间
    disabledDate (current) {
      return current && current < moment().startOf('day')
    },
    // 轮播时间
    dateChange (date, dateString) {
      this.form.time = date
      if (dateString[0] != '' && dateString[1] != '') {
        this.form.bannerStartDate = dateString[0] + ' 00:00:00'
        this.form.bannerEndDate = dateString[1] + ' 23:59:59'
      }
    },
    // 打开 选择经销商弹窗
    handleDealerModal () {
      console.log('111111111111:', this.chooseDealerList)
      this.chooseSnList = this.chooseDealerList.map(item => item.dealerSn)
      this.openDealerModal = true
    },
    // 关闭 选择经销商弹窗
    closeDealerModal () {
      this.chooseSnList = []
      this.openDealerModal = false
    },
    // 部分经销商 删除
    delBuyerName (row) {
      const pos = this.chooseDealerList.findIndex(item => item.dealerSn == row.dealerSn)
      if (pos > 0) {
        this.chooseDealerList.splice(pos, 1)
      }
      console.log('222222:', pos, this.chooseDealerList)
    },
    // 参与经销商 change
    changeDealerScope (val) {
      this.form.allDealerFlag = val
      if (val == '1') {
        this.chooseDealerList = []
      }
    },
    // 返回列表
    handleBack () {
      this.$router.push({ name: 'carouselImageList', query: { closeLastOldTab: true } })
    },
    //  详情
    getDetail () {
      const _this = this
      shopBannerDetail({ bannerSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          if (res.data.bizType && res.data.bizType === 'SHOP_PROMO') {
            _this.isDisabled = true
          }
          if (res.data.contentType == 'IMAGE_CONTENT') {
            _this.$refs.editor.setHtml(res.data.content)
          } else if (res.data.contentType == 'VIDEO') {
            _this.$refs.videoSet.setFileList(res.data.content)
          } else if (res.data.contentType == 'LINK') {
            res.data.contentLink = res.data.content
          }
          if (res.data.allDealerFlag == '0') {
            this.chooseDealerList = res.data.dealerList
          }
          _this.$refs.imageSet.setFileList(res.data.imageUrl)
          _this.form = res.data
          _this.form.time = [res.data.bannerStartDate, res.data.bannerEndDate]
        }
      })
    },
    //  确定保存  验证必填
    handleSave (type) {
      const _this = this
      if (_this.form.contentType === 'LINK') {
        _this.form.content = _this.form.contentLink
      }
      // 验证组件必填项
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.savePartInfo(type)
        }
      })
    },
    // 保存
    savePartInfo (type) {
      const _this = this
      if (_this.form.allDealerFlag == '0') {
        if (_this.chooseDealerList && _this.chooseDealerList.length == 0) {
          _this.$message.warning('请选择参与经销商！')
          return
        }
        _this.form.dealerSnList = _this.chooseDealerList.map(con => con.dealerSn)
      }
      _this.form.bannerSn = _this.$route.params.sn || undefined
      var formData = JSON.parse(JSON.stringify(_this.form))
      delete formData.time
      delete formData.contentLink
      _this.spinning = true
      saveShopBanner(formData).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$nextTick(() => {
            _this.handleBack()
            _this.resetSearchForm()
          })
          _this.spinning = false
        } else {
          _this.spinning = false
        }
      })
    },
    //  图片上传
    changeImage (file) {
      this.form.imageUrl = file
    },
    // 视频上传
    changeVideo (file) {
      this.form.content = file
    },
    //  文本编辑器
    editorChange (html, text) {
      this.form.content = html
    },
    // 重置
    resetSearchForm () {
      this.$refs.imageSet.setFileList('')
      if (this.contentType === 'VIDEO') {
        this.$refs.videoSet.setFileList('')
      }
      if (this.contentType === 'IMAGE_CONTENT') {
        this.$refs.editor.setHtml('')
      }
      this.form = {
        bannerSn: undefined, // 轮播图sn
        bannerName: '', // 轮播图名称
        time: [], // 轮播时间
        bannerStartDate: undefined, // 轮播图活动开始时间
        bannerEndDate: undefined, // 轮播图活动结束时间
        sort: undefined, // 排序
        allDealerFlag: '1', // 参与经销商 0 部分 1全部
        dealerSnList: [], // 已选经销商sn列表
        imageUrl: '', // 图片
        contentType: 'LINK', // 内容类型
        content: '', // 内容
        contentLink: '',
        state: 'UNPUBLISH'
      }
      this.isDisabled = false
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
    },
    // 初始化
    pageInit () {
      if (this.$route.params.sn) {
        this.getDetail()
        if (this.$route.params.bizType && this.$route.params.bizType === 'SHOP_PROMO') {
          this.notShowSel.splice(0, 1)
        }
      }
    }
  },
  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>
.carouselImageEdit-wrap{
    position: relative;
    height: 100%;
    box-sizing: border-box;
    padding-bottom:51px;
    >.ant-spin-nested-loading{
      overflow-y: scroll;
      height: 100%;
    }
    /deep/.ant-form-item{
      margin-bottom:8px;
    }
    .carouselImageEdit-cont{
      margin-bottom: 10px;
    }
    .upload{
      width: 100%!important;
    }
    //  文本编辑器  工具栏样式换行
    .carouselImageEdit-editor{
      .w-e-toolbar{
        flex-wrap: wrap;
        z-index: 0;
      }
    }
    .buyerBox{
      border:1px solid #d9d9d9;
      margin-top:10px;
      border-radius:4px;padding:4px 10px;
      background:#f2f2f2;max-height:130px;
      overflow-y:scroll;
    }
    //  商品图片描述
    .upload-desc{
      font-size: 12px;
      color: #808695;
    }
    #carouselImageEdit-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{
      display:flex;
      justify-content: space-between;
    }
    #setPromotion-productRange{
      /deep/.ant-select-dropdown{
        max-height:30vh !important;
      }
    }
  }
</style>
