<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-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 notice">
            <text class="span">主播微信号需要通过人脸认证</text>
            <view class="div common-btn ds-button-small btn" @click="showPopup('showQrcode')"><text class="span">认证</text></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" :disabled="minipro_live_info.minipro_live_room_id" v-model="minipro_live_info.minipro_live_name" /></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="datetimerange" v-model="timeRange"
              :start="$moment().format('YYYY-MM-DD HH:mm')"></uni-datetime-picker>
            </view>
            </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" :disabled="minipro_live_info.minipro_live_room_id" v-model="minipro_live_info.minipro_live_nickname" /></view></flex-line>
            <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" :disabled="minipro_live_info.minipro_live_room_id" v-model="minipro_live_info.minipro_live_wxid" /></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="imageValue['feedsImg']" fileMediatype="image" mode="grid" :limit="1"
                        :auto-upload="false" @select="uploadImage('feedsImg',$event)" @delete="dropImage('feedsImg')" :image-styles="{
                        width:'160px',
                        height:'160px',
                        }"></uni-file-picker>
                                    </view>
                    </view>
                </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="imageValue['coverImg']" fileMediatype="image" mode="grid" :limit="1"
                        :auto-upload="false" @select="uploadImage('coverImg',$event)" @delete="dropImage('coverImg')" :image-styles="{
                        width:'160px',
                        height:'160px',
                        }"></uni-file-picker>
                                    </view>
                    </view>
                </view>
            </flex-line>
            <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>
            <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':item.minipro_live_goods_info && selectGoodsId.indexOf(item.minipro_live_goods_info.minipro_live_goods_result_id)>-1,'disable':!item.minipro_live_goods_info || item.minipro_live_goods_info.minipro_live_goods_state!=2 || item.minipro_live_goods_info.minipro_live_goods_close==1}" @click="selectedGoods(item)">
                                <view class="div p-img">
                                    <image mode="aspectFit" class="img" :src="item.goods_image_url"/>
                                </view>
                                <view class="div p-info">
                                    <view class="p name">{{item.goods_name}}</view>
                                    <view class="p price">{{item.goods_price}}</view>
                                </view>
                                <view v-if="item.minipro_live_goods_info && item.minipro_live_goods_info.minipro_live_goods_close==1" class="div state">
                                    <text class="span">已关闭</text>
                                </view>
                                <view v-else class="div state">
                                    <text class="span" v-if="!item.minipro_live_goods_info || !item.minipro_live_goods_info.minipro_live_goods_state">审核中</text>
                                    <text class="span" v-if="item.minipro_live_goods_info && item.minipro_live_goods_info.minipro_live_goods_state==2">已通过</text>
                                    <text class="span" v-if="item.minipro_live_goods_info && item.minipro_live_goods_info.minipro_live_goods_state==3">未通过</text>
                                </view>
                            </view>
                        </view>
                        <empty-record v-else></empty-record>
                    </view>
                </scroll-view>
            </view>
        </view>
        </uni-popup>
        <!--认证小程序码-->
        <uni-popup background-color="#fff" ref="showQrcode" 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('showQrcode')">
                </uni-nav-bar>
            </view>
            </view>
            <view class="div common-popup-content" style="text-align: center">
				<scroll-view style="position: absolute;top:0;right:0;left:0;bottom:0" scroll-y="true">
                <image mode="aspectFit" class="img refer_qrcode_logo" src="../../../static/image/minipro_live_verify.png">
				</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 { getRoomInfo, addRoom, uploadMedia, getGoodsList, importRoomGoods } from '../../../api/sellerMiniproLive'
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', minipro_live_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,
    imageValue:{},
      screenWidth:0,
	  action:'',
      cropperOption: {
        img: '',
        canMove: false,
        autoCrop: true,
        autoCropWidth: 100,
        autoCropHeight: 100,
        maxImgSize: 500,
        outputType: 'png'
      },
      cropType: '',
      timeRange: [],
      minipro_live_info: {},
      params: { 'page': 0, 'per_page': 10 },
      loading: false, // 是否加载更多
      isMore: true, // 是否有更多
      selectGoodsList: false,
      selectGoodsId: [],
      keyword: '',
      showimage: '',
      isshow: false
    }
  },
  onLoad: function (option) {
	this.action = option.action
    this.initLive()
	this.loadMore()
  },
  watch: {
    query: function (val) {
      this.minipro_live_id = val.minipro_live_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) {
        getRoomInfo(this.minipro_live_id).then(res => {
          var minipro_live_info = res.result.minipro_live_info
          this.timeRange = [minipro_live_info.minipro_live_start_time,minipro_live_info.minipro_live_end_time]
          this.minipro_live_info = minipro_live_info
          
          if(this.minipro_live_info.feedsImg){
            this.imageValue['feedsImg']=[{
              name:'feedsImg',
              extname:'jpg',
              url:this.minipro_live_info.feedsImgUrl
            }]
          }
          if(this.minipro_live_info.coverImg){
            this.imageValue['coverImg']=[{
              name:'coverImg',
              extname:'jpg',
              url:this.minipro_live_info.coverImgUrl
            }]
          }
        
        }).catch(function (error) {
          uni.showToast({icon:'none',title: error.message})
        })
      }
    },
    submit () {
      uni.showLoading({ title: '加载中' })
      var data=Object.assign({},this.minipro_live_info)
      if(this.timeRange.length){
        data=Object.assign({minipro_live_start_time:this.timeRange[0],minipro_live_end_time:this.timeRange[1]},this.minipro_live_info)
      }
      addRoom(data).then(res => {
        this.minipro_live_info.minipro_live_room_id = res.result.roomId
        if (this.selectGoodsId.length) {
          this.importRoomGoods(res.result.roomId)
        } else {
          this.finish()
        }
        uni.hideLoading()
      }).catch(error => {
        uni.hideLoading()
        uni.showToast({icon:'none',title: error.message})
      })
    },
    finish () {
      uni.hideLoading()
      if (this.ifComponent) {
        this.$emit('addRoom')
      } else {
        uni.navigateTo({url:'/pages/seller/minipro_live/MiniproLiveList'})
      }
    },
    importRoomGoods (roomId) {
      importRoomGoods({ roomId: roomId, ids: this.selectGoodsId }).then(res => {
        this.finish()
      }).catch(error => {
        uni.hideLoading()
        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(this.params).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) {
      if (item.minipro_live_goods_info && item.minipro_live_goods_info.minipro_live_goods_state == 2 && item.minipro_live_goods_info.minipro_live_goods_close != 1) {
        var index = this.selectGoodsId.indexOf(item.minipro_live_goods_info.minipro_live_goods_result_id)
        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.minipro_live_goods_info.minipro_live_goods_result_id)
        }
      }
    },
    openImage (src) {
      this.showimage = src
      this.isshow = true
    },
    dropImage (type) {
      if (type == 'feedsImg') {
        this.minipro_live_info.feedsImg = ''
      } else {
        this.minipro_live_info.coverImg = ''
      }
      this.$forceUpdate()
    },
    useCrop (res) {
      let type = this.cropType
        var formdata={
          filePath:res.url,
          name:'file',
          id:'file'
        }
        if (type == 'feedsImg') {
          formdata['save']=1
        }
        uni.showLoading({ title: '加载中' })
        uploadMedia(formdata).then(res => {
          if (type == 'feedsImg') {
            this.minipro_live_info.feedsImg = res.result.media_id
            this.minipro_live_info.minipro_live_image = res.result.file_name
            
          this.imageValue[index]=[{
            name:index,
            extname:'jpg',
            url:res.result.file_path
          }]
          } else {
            this.minipro_live_info.coverImg = res.result.media_id
          }
		  this.hidePopup('showCrop')
          this.cropperOption.imgUrl=''
          this.$forceUpdate()
          uni.hideLoading()
        }).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 (type, event) {
      let that = this
      this.cropType = type
      let file = event.tempFiles[0]
      if (type == 'feedsImg') {
          that.minipro_live_info.feedsImgUrl = file.path
        } else {
          that.minipro_live_info.coverImgUrl = file.path
        }
      
          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;flex:1}
    .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;}
    .select-goods .li .state{font-size:$subFontSize}
    .select-goods .li.disable{position: relative;opacity: .5}
    .user-avatar-wrapper{display: inline-block;vertical-align: top;margin-right: .5rem;margin-bottom:.5rem}
    .user-avatar-wrapper .del-btn{position:absolute;bottom:.2rem;right:.2rem}
    
    .notice{font-size:$subFontSize;padding:.5rem;background:#FCF8E3;color:#C09853;line-height: 1.65rem;
        .red{color:#F00}
        .btn{float:right}
    }
    .refer_qrcode_logo{width:60%;top:30%;position: relative;}
</style>
