<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
    <seller-base :show="false" class="scroll-view-wrapper">
    <view class="scroll-view-wrapper scroll-view div container live-apply-form">
        <view class="div common-header-wrap">
            <view :style="'height:'+navHeight+'px'"></view>
            <view class="common-header-holder"></view>
            <view class="common-header-fixed">
            <title-header />
            <uni-nav-bar :title="getTitle" class="common-header" left-icon="back" @clickLeft="goBack">
            </uni-nav-bar>
        </view>
        </view>
        <view class="div main-content">
            <flex-line class="field-line menu-item" :show-border="true"><text class="span field-name">直播标题</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="live_apply_info.live_apply_name" /></view></flex-line>
            <flex-line class="pt-5" :show-border="true">
                <text class="span">直播封面</text>
                <view class="div" slot="right">
                    <view class="div user-avatar-wrapper">
                        <view class="div user-avatar">
                              <uni-file-picker class="common-avatar" v-model="image" fileMediatype="image" mode="grid" :limit="1"
                      :auto-upload="false" @select="uploadImage" :image-styles="{
                        width:'160px',
                        height:'160px',
                        }"></uni-file-picker>
                    </view>
                    </view>
                </view>
            </flex-line>
            <view class="div">
            <flex-line :is-link="true" :show-border="true">
            <text class="span line-name">直播时间</text>
            <view class="span" slot="right">
          <uni-datetime-picker class="common-datetime-picker" type="datetime" v-model="live_apply_info.live_apply_play_time"
            :start="$moment().format('YYYY-MM-DD HH:mm')"></uni-datetime-picker>
          </view>
            </flex-line>
            </view>
            <view class="div" @click="showPopup('popupSelect')">
                <flex-line :is-link="true" :show-border="true"><text class="span line-name">选择商品</text><text class="span" slot="right">{{selectGoodsId.length?('已选' + selectGoodsId.length + '件'):''}}</text></flex-line>
            </view>
            <flex-line class="field-line menu-item" :show-border="true"><text class="span field-name">申请备注</text><view class="div field-line-right" slot="right"><input class="field-input" type="textarea" rows="4" v-model="live_apply_info.live_apply_remark" /></view></flex-line>
            <view class="div pt-10 pb-10"><view class="div common-btn ds-button-large"  @click="submit">保存</view></view>
        </view>

        <uni-popup background-color="#fff" ref="popupSelect" type="right">
            <view :style="'width:'+screenWidth+'px'" class="common-popup-wrapper">
            <view class="div common-header-wrap">
                <view :style="'height:'+navHeight+'px'"></view>
                <view class="common-header-holder"></view>
                <view class="common-header-fixed">
                <title-header />
                <uni-nav-bar title="选择商品" class="common-header" left-icon="back" @clickLeft="hidePopup('popupSelect')">
                </uni-nav-bar>
            </view>
            </view>
            <view class="scroll-view-wrapper scroll-view div common-popup-content">
                <scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" class="scroll-view div" @scrolltolower="loadMore" scroll-y="true">
                    <view class="div select-goods" v-if="selectGoodsList">
                        <view class="ul" v-if="selectGoodsList.length">
                            <view class="li" v-for="item in selectGoodsList" v-bind:key="item.goods_commonid" :class="{'active':selectGoodsId.indexOf(item.goods_commonid)>-1}" @click="selectedGoods(item)">
                                <view class="div p-img">
                                    <image mode="aspectFit" class="img" :src="item.goods_image"/>
                                </view>
                                <view class="div p-info">
                                    <view class="p name">{{item.goods_name}}</view>
                                    <view class="p price">{{item.goods_price}}</view>
                                </view>
                            </view>
                        </view>
                        <empty-record v-else></empty-record>
                    </view>
                </scroll-view>
            </view>
        </view>
        </uni-popup>
        <tui-picture-cropper v-if="cropperOption.imgUrl" :width="cropperOption.autoCropWidth" :height="cropperOption.autoCropHeight" :imageUrl="cropperOption.img" @ready="cropReady" @cropper="useCrop" @back="cropBack"></tui-picture-cropper>
    </view>
</seller-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import TitleHeader from '../../TitleHeader'
import SellerBase from '../SellerBase'
import tuiPictureCropper from "@/components/thorui/tui-picture-cropper/tui-picture-cropper"
import { getLiveApplyInfo, saveLiveApply, uploadInfoFile } from '../../../api/sellerLiveApply'
import { getGoodsList } from '../../../api/sellerGoods'
import EmptyRecord from '../../EmptyRecord'
import flexLine from '../../flexLine'
export default {
  components:{
    TitleHeader,
    SellerBase,
    flexLine,
    EmptyRecord,
    tuiPictureCropper
  },
  props: {
    ifComponent: {
      type: Boolean,
      default: false
    },
    query: {
      type: Object,
      default: function () {
        return { action: 'add', live_apply_id: 0 }
      }
    }
  },
  computed:{
    fontSize(){
      return getFontSize()
    },
    isAddMode () {
      let mode = this.ifComponent ? this.query.action : this.action
      // add: 添加地址，edit: 编辑地址
      if (mode === 'add') {
        return true
      } else {
        return false
      }
    },
    getTitle () {
      if (this.isAddMode) {
        return '新增直播'
      } else {
        return '修改直播'
      }
    }

  },
  data(){
    return {
    navHeight: 0,
    image:[],
      screenWidth:0,
	  action:'',
      cropperOption: {
        img: '',
        canMove: false,
        autoCrop: true,
        autoCropWidth: 100,
        autoCropHeight: 100,
        maxImgSize: 500,
        outputType: 'png'
      },
      live_apply_info: {},
      params: { 'page': 0, 'per_page': 10 },
      loading: false, // 是否加载更多
      isMore: true, // 是否有更多
      selectGoodsList: false,
      selectGoodsId: [],
      keyword: '',
      goods_type: '',
      search_type: '',
      showimage: '',
      isshow: false
    }
  },
  onLoad: function (option) {
	this.action = option.action
    this.initLive()
	this.loadMore()
  },
  watch: {
    query: function (val) {
      this.live_apply_id = val.live_apply_id
      this.initLive()
    }
  },
  mounted(){
    // #ifdef  MP-WEIXIN
    this.navHeight = uni.getMenuButtonBoundingClientRect().height
    // #endif
    this.screenWidth=uni.getSystemInfoSync().screenWidth
  },
  methods:{
    showPopup(id){
      this.$refs[id].open()
    },
    hidePopup(id){
      this.$refs[id].close()
    },
    goBack () {
      if (this.ifComponent) {
        this.$emit('closeLiveApplyForm')
      } else {
        uni.navigateBack({delta:1})
      }
    },
    initLive () {
      if (!this.isAddMode) {
        getLiveApplyInfo(this.live_apply_id).then(res => {
          var live_apply_info = res.result.live_apply_info
          this.live_apply_info = live_apply_info
          if(this.live_apply_info.live_apply_cover_image){
          this.image=[{
            name:'live_apply_cover_image',
            extname:'jpg',
            url:this.live_apply_info.live_apply_cover_image_url
          }]
          }else if(this.live_apply_info.live_apply_cover_video){
          this.image=[{
            name:'live_apply_cover_video',
            extname:'mp4',
            url:this.live_apply_info.live_apply_cover_video_url
          }]
          }
        }).catch(function (error) {
          uni.showToast({icon:'none',title: error.message})
        })
      }
    },
    submit () {
      saveLiveApply(Object.assign({}, this.live_apply_info, { goods_ids: this.selectGoodsId })).then(res => {
        if (this.ifComponent) {
          this.$emit('saveLiveApply')
        } else {
          uni.navigateTo({url:'/pages/seller/live_apply/LiveApplyList'})
        }
      }).catch(error => {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    loadMore () {
      this.loading = true
      this.params.page = ++this.params.page
      if (this.isMore) {
        this.loading = false
        this.getSelectGoodsList(true)
      }
    },
    reload () {
      // 重新加载数据
      this.params.page = 0
      this.isMore = true
      this.selectGoodsList = []
      this.loadMore()
    },
    // 获取商品列表 用于设置产品分佣
    getSelectGoodsList () {
      getGoodsList('Sellergoodsonline', this.params, this.keyword, this.goods_type, this.search_type).then(res => {
        if (this.selectGoodsList) {
          this.selectGoodsList = this.selectGoodsList.concat(res.result.goods_list)
        } else {
          this.selectGoodsList = res.result.goods_list
        }
        if (res.result.hasmore) {
          this.isMore = true
        } else {
          this.isMore = false
        }
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    // 选择商品
    selectedGoods (item) {
      var index = this.selectGoodsId.indexOf(item.goods_commonid)
      if (index > -1) {
        this.selectGoodsId.splice(index, 1)
      } else {
        if (this.selectGoodsId.length >= 10) {
		  uni.showToast({icon:'none',title: '最多选10件商品'})
          return
        }
        this.selectGoodsId.push(item.goods_commonid)
      }
    },
    openImage (src) {
      this.showimage = src
      this.isshow = true
    },
    dropImage () {
      this.live_apply_info.live_apply_cover_image = ''
      this.live_apply_info.live_apply_cover_video = ''
      this.$forceUpdate()
    },
    useCrop (res) {
        var formdata={
          filePath:res.url,
          name:'file',
          id:'file'
        }
          uni.showLoading({ title: '加载中' })
        uploadInfoFile(formdata).then(res => {
          if (res.result.file_type == 'image') {
            this.live_apply_info.live_apply_cover_video = ''
            this.live_apply_info.live_apply_cover_video_url = ''
            this.live_apply_info.live_apply_cover_image = res.result.file_name
            this.live_apply_info.live_apply_cover_image_url = res.result.file_path
            this.image=[{
              name:'live_apply_cover_image',
              extname:'jpg',
              url:res.result.file_path
            }]
          } else {
            this.live_apply_info.live_apply_cover_image = ''
            this.live_apply_info.live_apply_cover_image_url = ''
            this.live_apply_info.live_apply_cover_video = res.result.file_name
            this.live_apply_info.live_apply_cover_video_url = res.result.file_path
            this.image=[{
              name:'live_apply_cover_video',
              extname:'mp4',
              url:res.result.file_path
            }]
          }
      
          uni.hideLoading()
          this.cropperOption.imgUrl=''
          this.$forceUpdate()
        }).catch(function (error) {
          uni.showToast({icon:'none',title: error.message})
          uni.hideLoading()
          this.cropperOption.imgUrl=''
          this.$forceUpdate()
        })
      
    },
      cropReady(){
        this.cropperOption.img = this.cropperOption.imgUrl
      },
	  cropBack(){
	    this.cropperOption.imgUrl=''
	    this.$forceUpdate()
	  },
    uploadImage (event) {
      let that = this
      let file = event.tempFiles[0]
          that.cropperOption.imgUrl = file.path
          that.cropperOption.autoCropWidth = uni.getSystemInfoSync().windowWidth
          that.cropperOption.autoCropHeight = uni.getSystemInfoSync().windowWidth
          that.cropperOption.maxImgSize = uni.getSystemInfoSync().windowHeight - 40
          that.$forceUpdate()
    }
  }
}
</script>
<style lang="scss" scoped>
.scroll-view-wrapper{display: flex;flex-direction: column;}
.scroll-view{flex:1}
.common-header{
        .btn{background: #000;color: #fff;box-shadow: 0px 2px 4px #d2d2d2;}
    }
    .main-content{padding:0 $pageSpace;background: #fff;}
    .select-goods .li{height:3rem;padding:.6rem;display:flex;}
    .select-goods .li.active{background: rgba(255, 203, 203, 0.5) }
    .select-goods .li .p-img{}
    .select-goods .li .p-img .img{width:3rem;height: 3rem;}
    .select-goods .li .p-info{margin-left:1rem;}
    .select-goods .li .p-info .p{line-height:1rem;}
    .select-goods .li .p-info .price{font-size:$fontSize;color:$primaryColor;height:2rem;overflow: hidden}
    .select-goods .li .p-info .name{font-size:$subFontSize;}
    .common-avatar{text-align: right;}
</style>
