<template>
  <div class="sjp-addOrEditPrize">
      <Upload
          class="sjp-rich-upload"
          v-show="false"
          :show-upload-list="false"
          :on-success="handleSuccess"
          :format="['jpg','jpeg','png']"
          :max-size="2048"
          type="drag"
          :action="url + 'overlord_prize/common/upload_pic'"
          style="display: inline-block;width:58px;">
          <div style="width: 100px;height:100px;line-height: 100px;">
            <Icon type="ios-cloud-upload-outline" size="30" />
          </div>
      </Upload>
      <div>
          <Form ref="prizeForm" :model="prizeForm" :rules="ruleValidate"  :label-width="80">
            <position  :positionObj="prizeForm" label="抽奖商圈" prop="belongProvince" width="150"></position>
            <FormItem  label="c端预热展示开始时间" prop="warmUpTime"  :label-width="130">
              <DatePicker type="datetime"  :options="options"  v-model="prizeForm.warmUpTime"  placeholder="开始时间" style="width: 200px"></DatePicker>
            </FormItem>
            <FormItem  label="报名抽奖时间" prop="joinStartTime" :label-width="100">
              <DatePicker type="datetimerange" :options="options" v-model="signTime"  placeholder="选择开始时间和结束时间" style="width: 300px"></DatePicker>
            </FormItem>
             <FormItem  label="奖品名称" prop="prizeName" :label-width="80">
                  <Input v-model="prizeForm.prizeName" placeholder="请输入奖品名称" :maxlength="100" style="width: 200px"/>
            </FormItem>
            <FormItem class="sjp-prize_form_item"  prop="prizePics"  label="奖品图片" :label-width="60">
                <sjp-upload :imageList="prizeForm.prizePics"></sjp-upload>
            </FormItem>
            <FormItem label="奖品说明" prop="prizeContent" class="sjp-prize_form_item"  :label-width="60">
                <quill-editor ref="myQuillEditor" @change="alertValue($event,prizeForm.prizeContent,5000)" v-model="prizeForm.prizeContent" class="myQuillEditor" :options="editorOption" />
            </FormItem>
            <FormItem  label="奖品价值" prop="prizeAmount" :label-width="90">
                  <Input v-model="prizeForm.prizeAmount" @on-blur="prizeInter(prizeForm.prizeAmount)"  placeholder="请输入奖品价值" style="width: 200px"/> 元
            </FormItem>
            <FormItem  label="中奖名额" prop="prizeWinQuantity" :label-width="90">
                  <Input v-model="prizeForm.prizeWinQuantity" placeholder="请输入中奖金额" style="width: 200px"/> 个
            </FormItem>
            <FormItem  label="使用时间" prop="prizeUseStartTime" :label-width="90">
              <DatePicker type="datetimerange" v-model="useTime"  placeholder="选择开始时间和结束时间" style="width: 300px"></DatePicker>
            </FormItem>
            <FormItem  label="是否需要预约" prop="isReserve" :label-width="100">
                <RadioGroup v-model="prizeForm.isReserve">
                  <Radio :label="1" >是</Radio>
                  <Radio :label="0" >否</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem  label="适用商户" prop="businessIds" :label-width="90">
                <Button type="primary"  @click="addShop">添加可用商户</Button>
            </FormItem>
            <FormItem  label="开奖时间" prop="prizeTime" :label-width="90">
              <DatePicker   type="datetime" v-model="prizeForm.prizeTime" placeholder="开奖时间" style="width: 200px"></DatePicker>
            </FormItem>
        </Form>
      </div>
       <Modal
        v-model="visibleModal"
        width="75%"
        class-name="shopdialog"
         @on-cancel="saveHandle"
        :title="titleObj[titleStatus]"
        >
        <div class="shop-detail">
            <Form ref="shopForm" :model="shopForm"  :label-width="80">
              <FormItem  label="商户名称" :label-width="90">
                    <Input v-model.number="shopForm.searchName" placeholder="请输入商户名搜索" style="width: 200px"/>
              </FormItem>
              <Form-item label="所属行业"  :label-width="90">
                <Select :model.sync="shopForm.province" class="sjp-select__item">
                  <Option :value="item.id" v-for="(item, index) of firstData" :key="index" >{{item.name}}</Option>
                </Select>
              </Form-item>
               <Form-item :label-width="90">
                 <Button type="primary" size="large"  @click="search">搜索</Button>
              </Form-item>
          </Form>
            <Tabs active-key="key1" @on-click="clickHandle">
              <Tab-pane label="已加入" key="key1">
                <Table stripe :columns="hasJoinColumns" :data="renderJoinList"></Table>
                <Page style="margin-top: 20px" :total="joinList.length" :current.sync="joinCurrent" :page-size.sync="joinPageSize" @on-change="pageJoinChange" @on-page-size-change="pageJoinSizeChange" show-total show-sizer></Page>
              </Tab-pane>
              <Tab-pane label="未加入" key="key2">
                <Table stripe :columns="notJoinColumns" :data="notJoinList"></Table>
                <Page style="margin-top: 20px" :total="total" :current.sync="shopForm.currentPage" :page-size.sync="shopForm.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" show-total show-sizer></Page>
              </Tab-pane>
          </Tabs>
          </div>
          <div slot="footer" style="text-align: center;">
              <Button type="default" size="large"  @click="saveHandle">确定</Button>
          </div>
      </Modal>
  </div>
</template>

<script>
import sjpUpload from './../../../components/upload'
import position from './../../../components/position'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import http from './../../service/statics'
import shopinfo from './../../service/shopinfo'
export default {
  name: 'addOrEditPrize',
  components: { sjpUpload,quillEditor,position },
  props:['prizeId'],
  data() {
    let validateBelong = (rule, value, callback) => {
      let result = false
      let arr = ['belongProvince','belongCity','belongRegion']
      arr.forEach((item)=>{
        if(!this.prizeForm[item]){
          result = true
        }
      })
      if (result) {
        return callback(new Error('请选择抽奖活动所在商圈'));
      }
      callback();
    };
    let validateWarmUpTime = (rule, value, callback) => {
      let result = true
      if(this.prizeForm.warmUpTime && this.prizeForm.joinStartTime){
        result =  new Date(this.prizeForm.joinStartTime) - new Date(this.prizeForm.warmUpTime) > 0
      }
      if (!result) {
        callback(new Error('展示开始时间需早于报名开始时间'));
      } else if(new Date(this.prizeForm.warmUpTime) - new Date() < 0){
        callback(new Error('不能早于当前时间'));
      } else {
        callback();
      }
    };
    let validateSignTime = (rule, value, callback) => {
      if(this.signTime[0] &&  this.signTime[1]){
        this.prizeForm['joinStartTime'] = this.signTime[0]
        this.prizeForm['joinEndTime'] = this.signTime[1]
        if(new Date(this.prizeForm.joinStartTime) - new Date() < 0){
          callback(new Error('不能早于当前时间'));
        } else {
          callback();
        }
      } else{
        callback(new Error('请输入报名抽奖开始时间、结束时间'))
      }
    };
    let validateUseTime = (rule, value, callback) => {
      if(this.useTime[0] &&  this.useTime[1]){
        this.prizeForm['prizeUseStartTime'] = this.useTime[0]
        this.prizeForm['prizeUseEndTime'] = this.useTime[1]
        if(new Date(this.prizeForm.prizeUseStartTime) - new Date() < 0){
          callback(new Error('不能早于当前时间'));
        } else {
          callback();
        }
      } else{
        callback(new Error('请输入奖品使用开始时间、结束时间'))
      }
    };
    let validatePrizePics = (rule, value, callback) => {
      if(this.prizeForm.prizePics.length > 0){
        callback();
      } else{
        callback(new Error('请至少添加一张图片'))
      }
    };
    let validateBusinessIds = (rule, value, callback) => {
      if(this.prizeForm.businessIds.length > 0){
        callback();
      } else{
        callback(new Error('请至少添加一个商户'))
      }
    };
    let validateNumber = (rule, value, callback) =>{
      if(typeof value === 'number' && value){
        callback()
      } else {
        callback(new Error(rule.message))
      }
    }
    let validatePrizeTime = (rule, value, callback) =>{
      let result = true
      if(this.prizeForm.joinEndTime && value){
        result = new Date(this.prizeForm.joinEndTime) - new Date(value) > 0
      }
      if(!value){
        callback(new Error('请输入开奖时间'))
      } else if(result){
        callback(new Error('开奖时间不能早于报名抽奖结束时间'))
      } else if(new Date(this.prizeForm.joinEndTime) - new Date() < 0){
          callback(new Error('不能早于当前时间'));
      }else {
        callback()
      }
    }
    
    
    return {
      //省市商圈信息
      url: process.env.VUE_APP_API,
      options: {
          disabledDate (date) {
              return date && date.valueOf() < Date.now() - 86400000;
          }
      },
      visibleModal: false,
      titleStatus:'add',
      titleObj:{
        add:'选择可用商户',
        edit: '编辑可用商户'
      },
      editorOption:{
        modules:{
            toolbar:{
              handlers:{
                'image':function(value){
                  if(value){
                    document.querySelector('.sjp-rich-upload input').click()
                  } else {
                    this.quill.format('image',false)
                  }
                }
              },
              container: [
                ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
                ['blockquote', 'code-block'],     //引用，代码块
    
    
                [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],     //列表
                [{ 'script': 'sub'}, { 'script': 'super' }],   // 上下标
                [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
                [{ 'direction': 'rtl' }],             // 文本方向
    
    
                [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
    
    
                [{ 'color': [] }, { 'background': [] }],     // 字体颜色，字体背景颜色
                [{ 'font': [] }],     //字体
                [{ 'align': [] }],    //对齐方式
    
    
                ['clean'],    //清除字体样式
                ['image']    //上传图片、上传视频
    
              ]
            },
          },
          theme:'snow'
      },
      total:100,
      joinCurrent:1,
      joinPageSize: 10,
      notJoinColumns:[
         {
            type: 'index',
            width: 60,
            align: 'center'
        },
        {
            title: '商户名称',
            key: 'name'
        },
        {
            title: '商户ID',
            key: 'id'
        },
        {
            title: '操作',
            key: 'action',
            render: (h, params) => {
              return h('div', [h('Button', {
                      props: {
                          type: 'primary',
                          size: 'small'
                      },
                      style: {
                              marginRight: '5px'
                          },
                      on: {
                        click: () => {
                          let result = this.joinList.some((item) => {
                            return item.id === params.row.id
                          })
                          if(!result){
                            this.joinList.push(params.row)
                          }
                        }
                      }
                  }, '加入')]);
            }
        }
      ],
      notJoinList:[],
      renderJoinList:[], // 渲染在页面的数据
      hasJoinColumns:[{
            type: 'index',
            width: 60,
            align: 'center'
        },
        {
            title: '商户名称',
            key: 'name'
        },
        {
            title: '商户ID',
            key: 'id'
        },
        {
            title: '操作',
            key: 'action',
            render: (h, params) => {
              return h('div', [h('Button', {
                      props: {
                          type: 'primary',
                          size: 'small'
                      },
                      style: {
                              marginRight: '5px',
                              background: '#ccc'
                          },
                      on: {
                        click: () => {
                          let id = params.row.id
                          let idx = this.joinList.findIndex((item) => {return item.id === id})
                          this.joinList.splice(idx,1)
                          this.refreshData();
                        }
                      }
                  }, '删除')]);
            }
        }],
      joinList:[],
      shopForm:{
        currentPage:1,
        pageSize: 10,
        searchName:'',
      },
      signTime:[],
      useTime: [],
      ruleValidate:{
        belongProvince: [
          { validator: validateBelong,required: true, trigger: 'blur' }
        ],
        
        warmUpTime: [
          { validator: validateWarmUpTime, trigger: 'change' }
        ],
        joinStartTime: [
          { validator: validateSignTime,required: true, trigger: 'change' }
        ],
        prizePics: [
          { validator: validatePrizePics,required: true, trigger: 'blur' }
        ],
        prizeContent: [
              { required: true,  message: '奖品说明不能为空', trigger: 'blur' }
        ],
        prizeName: [
              { required: true, message: '请输入奖品名称，100字以内', trigger: 'blur' }
        ],
        prizeAmount: [
              { required: true, validator: validateNumber, message: '请输入奖品价值，0-9999999之间', trigger: 'blur' }
        ],
        prizeWinQuantity: [
              { required: true, validator: validateNumber, message: '请输入奖品中奖名额，1-999999之间', trigger: 'blur' }
        ],
        prizeUseStartTime: [
          { validator: validateUseTime,required: true, trigger: 'change' }
        ],
        businessIds: [
          { validator: validateBusinessIds,required: true, trigger: 'blur' }
        ],
        isReserve: [
              { required: true, validator: validateNumber, message: '预约状态不能为空', trigger: 'blur' }
        ],
        prizeTime: [
              { required: true, validator: validatePrizeTime, trigger: 'change' }
        ],
      
      },
      prizeForm:{
        belongProvince:'',
        belongCity:'',
        belongRegion:'',
        warmUpTime:'',
        joinStartTime:'',
        joinEndTime:'',
        prizeName:'',
        prizeAmount:'',
        prizeWinQuantity:'',
        prizeUseStartTime:'',
        prizeUseEndTime:'',
        prizeTime:'',
        businessIds:[],
        isReserve: 1,
        prizePics:[],
        prizeContent:'',
        prizeCreateUserId:'',
      },
      firstData:[],
    }
  },
  created() {
    // 获取行业分类列表
   shopinfo.getAllFirstData()
   .then(res => {
     this.firstData = res.data || []
   })

   if(this.prizeId){
     http.manageDetail({id:this.prizeId})
     .then((res)=>{
      this.prizeForm = res.data || {}
       this.signTime = [this.prizeForm.joinStartTime,this.prizeForm.joinEndTime];
       this.useTime = [this.prizeForm.prizeUseStartTime,this.prizeForm.prizeUseEndTime]
       this.prizeForm.prizePics = this.prizeForm.prizePics.split(',')
       this.$nextTick(()=>{
           this.$emit('initForm',this.$refs.prizeForm,this.prizeForm)
       })
     })
     this.initShopData()
   } else{
      this.$nextTick(()=>{
           this.$emit('initForm',this.$refs.prizeForm,this.prizeForm)
       })
   }
  },
  methods:{
    prizeInter(a,b){
      console.log(a,b)
    },
    handleSuccess(res){
        var dt = res.data
        let quill = this.$refs.myQuillEditor.quill
        // 如果上传成功
        if (res.code === "0") {
          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片 dt为服务器返回的图片地址
          quill.insertEmbed(length, 'image', dt)
          // 调整光标到最后
          quill.setSelection(length + 1)
        } else {
          this.$message.error('图片插入失败')
        }
    },
    alertValue(e,strValue,decimalNum){
          e.quill.deleteText(decimalNum,1,strValue);//保留 strValue 的 前 decimalNum 位字符，
    },
    clickHandle(key){
      if(key === 1) {
        this.search()
      } else if(key === 0){
        this.refreshData()
      }
    },
    
    saveHandle(){

      let ids = this.joinList.map((item) => {return item.id})
      
      this.prizeForm.businessIds = ids

      this.visibleModal = false
    },
    pageJoinChange(){
      this.refreshData()
    },
    pageJoinSizeChange(val){
      this.joinPageSize = val;
      this.refreshData()
    },
    pageChange(){
      this.search()
    },
    pageSizeChange(val){
      this.shopForm.pageSize = val
      this.search()
    },
    refreshData(){
      this.renderJoinList = this.joinList.slice(10*(this.joinCurrent - 1), 10)
    },
    search(){
      shopinfo.getShops(
        this.shopForm
      ).then((res) => {
        this.notJoinList = res.data || []
      })
    },
    initShopData(){
        if(this.prizeForm.businessIds && this.prizeForm.businessIds.length) {
          shopinfo.getShops({
            shopIds:this.prizeForm.businessIds,
            pageSize: this.prizeForm.businessIds.length,
            currentPage: 1,
          })
          .then((res => {
            this.joinList = res.data || []
          }))
        }
    },
    addShop(){
      this.visibleModal = true
      this.titleStatus = 'add'
    },
    handleBeforeUpload(){
      
    }
  },
  mounted(){
  
  }
}
</script>

<style lang="less" scoped>
  .sjp-addOrEditPrize{
    
  }
 
</style>
<style >
  .sjp-select__item{
    width: 150px;
    margin-right: 10px;
  }
  .sjp-prize_form_item .ivu-form-item-label{
      float: none;
    }
  .ivu-form-item-content{
    margin-left: 10px !important;
  }
  .myQuillEditor .ql-editor{
        min-height: 300px;
  }
  .sjp-freedetail::-webkit-scrollbar {
      display: none;
  }
  .shop-detail{
    height: calc(93vh - 200px);
    overflow-y: auto;
  }
  .shopdialog .ivu-modal{
    top: 7%;
  }
  
</style>
