<template>
<!--<import src="../../../component/rater/rater.wxml"></import>-->

<view id="order-comment">
    <view class="order-items">
        <view class="order-item" v-for="(item, index) in orderData.items" :key="index">
            <view class="order-info mx-1px-bottom">
                <view class="image">
                    <image :src="item.item_meta.image"></image>
                </view>
			

                <view class="texts">
                    <view class="name">{{item.item_name}}</view>
                    <view class="spec">{{item.item_meta.specs_text}}</view>
                    <view class="content">
                        <view class="item_start">
                          
						     <uni-rate size="18" active-color="red"  value="5" @change="changeStar"></uni-rate>
							

                        </view>
						
				
                    </view>
                </view>
            </view>
             
            <view class="comment-content mx-1px-bottom">
                <view class="content">
                    <textarea @input="changeEvaluate" :data-index="index" :value="item.comment" placeholder="请输入您对该商品的想法"></textarea>
                    <view class="number">还可以输入{{500 - length}}字</view>
                </view>
            </view>

            <view class="uploading-box">
                <view class="img-item uploading-item" v-for="(itemVal,idx) in item.upload_images" :key="idx">
                    <view class="img">
                        <image mode="widthFix" :src="itemVal"></image>
                    </view>
                    <span class="delete" :data-index="index" :data-idx="idx" :data-images="item.upload_images" @tap="deleteImg($event,item.upload_images)">
                        x
                    </span>
                </view>
                <view class="uploading uploading-item" @tap="upload" v-if="item.upload_images.length<5" :data-index="index">
                    <view class="uploading-input">
                    </view>
                </view>
            </view>
        </view>
    </view>

    <view class="submit" :disabled="disabled" @tap="submit">提交评价</view>
</view>


</template>
<script>

import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';
import uniRate from "@/components/score/uni-rate/uni-rate.vue"

export default {
  data() {
    return {
      orderData:'',
      minLength: 5,
      disabled: true,
      order_no: '',
      length: '',
	  star:5
    };
  },
  
  components:{  
	 uniRate 
  },

  onLoad(e) {
    console.log(e);
    var no = e.no;
    this.initOrderComment(no);
    this.setData({
      order_no: no
    });
  },
  methods: {
    upload(e) {
      var index = e.currentTarget.dataset.index;
      var that = this;
      wx.chooseImage({
        count: 1,
        // 默认9
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
		 
          var token = that.$cookieStorage.get('user_token');
          /* that.$http.uploadFile({
            header: {
              'content-type': 'multipart/form-data',
              Authorization: token
            },
            api: 'api/users/upload/avatar',
            //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'avatar_file'
          }).then(res => {
            var result = JSON.parse(res.data);
            var arr = that.orderData.items[index].upload_images;
            arr.push(result.data.url);
            var uploadData = `orderData.items[${index}]`;
			
	
			that.orderData.items[index].upload_images=arr;
			
          }); */
			uni.uploadFile({
				header: {
					Authorization: token
				},
				url: config.GLOBAL.baseUrl + 'api/users/upload/avatar',
				filePath: tempFilePaths[0],
				fileType: 'image',
				name: 'avatar_file',
				success: res => {
					var result = JSON.parse(res.data);
					var arr = that.orderData.items[index].upload_images;
					arr.push(result.data.url);
					var uploadData = `orderData.items[${index}]`;
					
						
					that.orderData.items[index].upload_images=arr;
				}
			})
        }
      });
    },

    changeEvaluate(e) {
      var len = e.detail.value;
      var index = e.currentTarget.dataset.index;

      if (e.detail.value.length > 500) {
        wx.showModal({
          title: '提示',
          content: '超出字数限制'
        });
        len = len.slice(0, 500);
      }

      // this.setData({
      //   [`orderData.items[${index}].comment`]: len,
      //   length: e.detail.value.length
      // });
	  
	  this.length=e.detail.value.length;
	  this.orderData.items[index].comment=len;
	  
	  
    },

    deleteImg(e,images) {
      var index = e.currentTarget.dataset.index;
      var idx = e.currentTarget.dataset.idx;
      // #ifndef H5
      
      // #endif
	  // #ifdef H5
	 images = images
	  // #endif
      images.splice(idx, 1);
      // this.setData({
      //   [`orderData.items[${index}].upload_images`]: images
      // });
	  
	  	this.orderData.items[index].upload_images=images;
	  
    },


    allowComment() {
		
      if (this.orderData.items && this.orderData.items.length) {
        for (let item of this.orderData.items) {
          if (item.comment.length < this.minLength) return false;
        }

        return true;
      } else {
        return false;
      }
    },

    submit() {
      if (this.allowComment()) {
        var no = this.order_no;
        var comments = [];
        var data = this.orderData.items;
	
        var rater = this.star;
         data.forEach((item,index) => {
             comments.push({
                 order_no: no,
                 order_item_id: item.id,
                 contents: item.comment,
                 point: rater,
                 images:item.upload_images
             })
         });
        this.postSubmit(comments);
      } else {
        wx.showModal({
          content: "请填写完成",
          showCancel: false
        });
      }
    },
	
	changeStar(e){
		this.star=e.value;
	},
	
    postSubmit(comments) {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      var data = {};
      comments.forEach((comment, index) => {
        data[index] = comment;
      });
	 
      this.$http.post({
        api: 'api/shopping/order/review',
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        },
        data: data
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status 
		    && comments.length
		  ) {
			   console.log(23423423);
            wx.showModal({
              content: '评价成功',
              showCancel: false,
              success: res => {
                if (res.confirm || !res.cancel && !res.confirm) {
                  wx.redirectTo({
                    url: '/pages/order/comment/comment'
                  });
                }
              }
            });
          } else {
            wx.showModal({
              content: res.message || "请求失败",
              showCancel: false
            });
          }

          wx.hideLoading();
        } else {
          wx.showModal({
            content: "请求失败",
            showCancel: false
          });
          wx.hideLoading();
        }
      });
    },

    initOrderComment(id) {
      wx.showLoading({
        title: "加载中",
        mask: true
      });
      this.$http.get({
        api: 'api/order/' + id,
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            // var start = Rater;
            var data = res.data;
            data.items.forEach((v, index) => {
              /*  start.init(index, {
                    value: 5
                })*/
              v.score = '';
              v.comment = '';
              v.upload_images = [];
            });
            this.setData({
              orderData: data
            });
          } else {
            wx.showModal({
              content: res.message || "请求失败",
              showCancel: false
            });
          }

          wx.hideLoading();
        } else {
          wx.showModal({
            content: "请求失败",
            showCancel: false
          });
          wx.hideLoading();
        }
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less">
    @import "evaluate";
</style>