<template>
  <view class="main">
    <div class="content">
      <div class="contentTop">
        <span class="title">您对商家/菜品满意吗？</span>
        <checkbox
          class="anonymous"
          :checked="saveMsg.isAnonymous"
          color="#CAA97F"
          @change="isAnonymous($event, saveMsg)"
        >
          <text>匿名评价</text>
        </checkbox>
      </div>
      <div class="starRate">
        <image
          class="shopImg"
          mode="aspectFit"
          lazy-load="true"
          :src="
            saveMsg.merchantsId
              ? storeMsg.MERCHANTS_LOGO ||
                'https://eshangtech.com/ShopICO/no-picture.png'
              : storeMsg.MERCHANTS_LOGO ||
                'https://eshangtech.com/ShopICO/no-picture.png'
          "
        />

        <div class="rateBox">
          <div class="shopName">
            {{
              saveMsg.merchantsId
                ? storeMsg.MERCHANTS_EN || "-"
                : proMsg.COMMODITY_NAME || "-"
            }}
          </div>
          <uni-rate
            :size="24"
            allowHalf
            v-model="saveMsg.commentScore"
            @change="changeRate($event, saveMsg)"
          />
        </div>
      </div>
      <div class="textBox">
        <textarea
          cols="30"
          rows="5"
          :placeholder="
            saveMsg.merchantsId
              ? '说说这家店的口味、环境、服务'
              : '商品满足你的期待吗？说说你的使用心得，分享给想买的他们吧'
          "
          v-model="saveMsg.commentContent"
        ></textarea>

        <view class="tip-text"> 评价文字不可少于3字 </view>
        <view class="photo-box">
          <view class="images" v-for="(item, i) in imgsList" :key="i">
            <image mode="aspectFit" :src="item" @click="seePhoto(item)"></image>
            <i @click="deleteImg(i)"></i>
          </view>
          <view class="add-photo" @click="choeseImg">
            <i></i>
            上传照片
          </view>
        </view>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submitBox">
      <div class="submit" @click="postRate">提交</div>
    </div>

    <view class="card" v-if="false">
      <view class="store-title">
        <view v-if="saveMsg.merchantsId">
          <image
            mode="aspectFit"
            lazy-load="true"
            :src="
              storeMsg.MERCHANTS_LOGO ||
              'https://eshangtech.com/ShopICO/no-picture.png'
            "
          ></image>
          <text class="name">{{ storeMsg.MERCHANTS_EN }}</text>
        </view>
        <view v-else>
          <image
            mode="aspectFit"
            lazy-load="true"
            :src="
              proMsg.IMAGE_PATH ||
              'https://eshangtech.com/ShopICO/no-picture.png'
            "
          ></image>
          <text class="name-commodity">{{ proMsg.COMMODITY_NAME }}</text>
        </view>

        <!-- uni-app 不自带 Vant 组件，可以用替代方案 -->
        <checkbox
          :checked="saveMsg.isAnonymous"
          color="#CAA97F"
          @change="isAnonymous($event, saveMsg)"
        >
          <text style="font-size: 26rpx">匿名评价</text>
        </checkbox>
      </view>

      <view class="star-box">
        <!-- 替换 van-rate 可以使用自定义评分组件 -->
        <uni-rate
          :size="32"
          allowHalf
          v-model="saveMsg.commentScore"
          @change="changeRate($event, saveMsg)"
        />
        <!-- <uni-rate
          :value="saveMsg.commentScore"
          size="32"
          allowHalf
          :color="starColor"
          @change="changeRate($event, saveMsg)"
        />
        <view class="rate-text" :style="{ color: starColor }">{{
          rateText
        }}</view> -->
      </view>

      <view class="evaluate-box">
        <textarea
          cols="30"
          rows="5"
          :placeholder="
            saveMsg.merchantsId
              ? '说说这家店的口味、环境、服务'
              : '商品满足你的期待吗？说说你的使用心得，分享给想买的他们吧'
          "
          v-model="saveMsg.commentContent"
        ></textarea>

        <view class="photo-box">
          <view class="images" v-for="(item, i) in imgsList" :key="i">
            <image mode="aspectFit" :src="item" @click="seePhoto(item)"></image>
            <i @click="deleteImg(i)"></i>
          </view>
          <view class="add-photo" @click="choeseImg">
            <i></i>
            上传照片
          </view>
        </view>

        <view class="tip-text"> 评价文字不可少于3字 </view>
      </view>
    </view>

    <view
      v-if="false"
      class="post-btn"
      :class="{ active: saveMsg.commentContent.length > 2 && noPost }"
      @click="postRate"
    >
      提交
    </view>
  </view>
</template>

<script>
import uniRate from "@/uni_modules/uni-rate/components/uni-rate/uni-rate.vue";
import { mapGetters } from "vuex";
export default {
  components: {
    uniRate,
  },
  data() {
    return {
      saveMsg: {
        action_type: "AddComment",
        commentScore: 4.5,
        isAnonymous: 0,
        commentContent: "",
        // saleBillId: '',
        imageArr: [],
      },
      noPost: true,
      storeMsg: {},
      imgsList: [],
      proMsg: {}, // 商品评论的列表
    };
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
    rateText() {
      let num = Math.ceil(this.saveMsg.commentScore);
      let text = ["非常差", "差", "一般", "满意", "超满意,无可挑剔"];
      return text[num - 1];
    },
    starColor() {
      let num = Math.ceil(this.saveMsg.commentScore);
      let colors = ["#f5bd50", "#f1b84d", "#f7a750", "#f59b3a", "#f28c44"];
      return colors[num - 1];
    },
  },
  methods: {
    isAnonymous(event, item) {
      item.isAnonymous = event.mp.detail;
    },
    changeRate(event, item) {
      this.saveMsg.commentScore = event.value;
    },
    choeseImg() {
      let _this = this;
      let num = 9 - _this.imgsList.length;
      if (num === 0) {
        uni.showToast({ title: "您最多可以上传9张图", icon: "none" });
        return false;
      }

      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(rs) {
          _this.noPost = false;
          // tempFilePath可以作为img标签的src属性显示图片
          // console.log(rs.tempFiles[0].size)
          let quality = 100;
          if (rs.tempFiles[0].size > 1024 * 200) {
            quality = ((1024 * 200) / rs.tempFiles[0].size) * 100;
          }
          if (quality < 100 && rs.tempFiles[0].path.indexOf(".jpg") > -1) {
            uni.compressImage({
              src: rs.tempFilePaths[0], // 图片路径
              quality: quality, // 压缩质量
              success(res) {
                // console.log(rs.tempFilePaths[0])
                // console.log(res)
                uni.showLoading({
                  title: "图片上传中...",
                  // mask: true
                });
                uni.uploadFile({
                  url: "https://user.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=Comment",
                  filePath: res.tempFilePath,
                  fileType: "image",
                  name: "data",
                  success(res) {
                    let _data = JSON.parse(res.data);
                    _this.imgsList.push(rs.tempFilePaths[0]);
                    _this.saveMsg.imageArr.push(_data.Data.IMAGE_PATH);
                    uni.hideLoading();
                    _this.noPost = true;
                  },
                  fail(res) {
                    console.log(res);
                    _this.noPost = true;
                  },
                });
              },
              fail(error) {
                console.log(error);
                _this.noPost = true;
              },
            });
          } else {
            uni.showLoading({
              title: "图片上传中...",
              // mask: true
            });
            uni.uploadFile({
              url: "https://user.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=Comment",
              filePath: rs.tempFilePaths[0],
              fileType: "image",
              name: "data",
              success(res) {
                let _data = JSON.parse(res.data);
                _this.imgsList.push(rs.tempFilePaths[0]);
                _this.saveMsg.imageArr.push(_data.Data.IMAGE_PATH);
                uni.hideLoading();
                _this.noPost = true;
              },
              fail(res) {
                console.log(res);
                _this.noPost = true;
              },
            });
          }
        },
      });
    },
    seePhoto(item) {
      let _this = this;
      uni.previewImage({
        current: item, // 当前显示图片的http链接
        urls: _this.imgsList, // 需要预览的图片http链接列表
      });
    },
    deleteImg(index) {
      let _this = this;
      _this.$api
        .postCoop({
          action_type: "DelFile",
          filePath: _this.saveMsg.imageArr[index],
        })
        .then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.ResultCode == "100") {
            _this.imgsList.splice(index, 1);
            _this.saveMsg.imageArr.splice(index, 1);
          } else {
            uni.showToast({
              title: "删除失败请稍后重试。错误：" + res.ResultDesc,
              icon: "none",
            });
          }
        });
    },
    postRate() {
      let _this = this;
      if (_this.saveMsg.commentContent.length > 2 && _this.noPost) {
        _this.noPost = false;
        _this.postIt();
      }
    },
    postIt() {
      let _this = this;
      let data = _this.saveMsg;
      data.requestType = "application/x-www-form-urlencoded";
      data.imageArr = data.imageArr.toString();
      delete data.__newReference;

      console.log("postIt", data);
      uni.showLoading({
        title: "正在提交...",
        mask: true,
      });
      this.$api.postCoop(data).then(function (rs) {
        uni.hideLoading();
        _this.noPost = true;
        // eslint-disable-next-line eqeqeq
        if (rs.ResultCode == "100") {
          _this.$store.commit("refresh", true);
          uni.showToast({
            title: "评价成功！",
          });
          setTimeout(() => {
            let i = 2;
            if (_this.saveMsg.merchantsId) {
              i = 1;
            }
            uni.navigateBack({
              delta: i,
            });
          }, 1000);
        } else {
          uni.showToast({
            title: rs.ResultDesc,
            icon: "none",
          });
        }
      });
    },
    getShop(id) {
      let _this = this;
      this.$api
        .getCoop({
          action_type: "GetMerchantsDetails",
          merchantsId: id,
        })
        .then(function (res) {
          let _data = res.Data;

          _this.storeMsg = _data;
        });
    },
    getMallOrderDetail(obj) {
      let _this = this;
      _this.$api
        .getCoop({
          action_type: "getOrderCommodity",
          salebillId: obj.orderInternal,
          salebillChildId: obj.sellchildid || 0,
          commodityId: obj.proid,
        })
        .then((res) => {
          // console.log(res)
          if (res.ResultCode === "100") {
            let _data = res.Data;
            _this.proMsg = _data;
          }
        });
    },
  },
  onUnload() {
    this.saveMsg = {
      action_type: "AddComment",
      commentScore: 2.5,
      isAnonymous: 0,
      commentContent: "",
      // saleBillId: '',
      imageArr: [],
      // merchantsId: ''
    };
    this.noPost = true;
    this.imgsList = [];
  },
  onLoad(option) {
    if (option.saleBillId) {
      this.saveMsg.saleBillId = option.saleBillId;
    }
    if (option.merchantsId) {
      this.getShop(option.merchantsId);
      this.saveMsg.merchantsId = option.merchantsId;
      this.saveMsg.action_type = "AddComment";
    }
    if (option.proid) {
      this.getMallOrderDetail(option);
      this.saveMsg.salebillChildId = option.sellchildid;
      this.saveMsg.commodityId = option.proid;
      this.saveMsg.salebillId = option.orderInternal;
      this.saveMsg.action_type = "addMallComment";
    }
  },
};
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  height: 100vh;
  background: #f5f6f7;
  box-sizing: border-box;
  padding: 16rpx 32rpx;
  .content {
    background: #ffffff;
    border-radius: 6rpx;
    width: 100%;
    box-sizing: border-box;
    padding: 32rpx;
    .contentTop {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #130f05;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
      }
      .anonymous {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #716f69;
        line-height: 36rpx;
        text-align: left;
        font-style: normal;
      }
    }

    .starRate {
      width: 100%;
      display: flex;
      align-items: center;
      padding-bottom: 32rpx;
      border-bottom: 2rpx solid #f0f0f0;
      .shopImg {
        width: 104rpx;
        height: 104rpx;
        border-radius: 6rpx;
        overflow: hidden;
        margin-right: 24rpx;
      }
      .rateBox {
        .shopName {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 32rpx;
          color: #130f05;
          line-height: 44rpx;
          text-align: left;
          font-style: normal;
        }
      }
    }

    .textBox {
      margin-top: 24px;
      .photo-box {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .images {
          margin: 16rpx 0 16rpx 13rpx;
          position: relative;

          image {
            height: 140rpx;
            width: 140rpx;
            border-radius: 6rpx;
            background: #fff;
          }

          i {
            background: #ea4848;
            height: 30rpx;
            width: 30rpx;
            border-radius: 50%;
            position: absolute;
            top: -15rpx;
            right: -10rpx;

            &:after {
              content: " ";
              height: 4rpx;
              width: 18rpx;
              display: block;
              background: #fff;
              margin-top: 14rpx;
              margin-left: 6rpx;
              border-radius: 4rpx;
            }
          }
        }

        .add-photo {
          height: 138rpx;
          width: 138rpx;
          border: 2rpx dashed #e7e7e6;
          margin-left: 24rpx;
          text-align: center;
          color: #ba9b6f;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: #f7f8f9;
          border-radius: 6rpx;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: #ba922f;
          line-height: 36rpx;
          text-align: left;
          font-style: normal;

          i {
            margin-bottom: 12rpx;
            width: 42rpx;
            height: 36rpx;
            background: url("/static/images/pic.png") no-repeat center;
            background-size: contain;
          }
        }
      }

      .tip-text {
        display: inline-block;
        width: 100%;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #b8b7b4;
        line-height: 36rpx;
        text-align: right;
        font-style: normal;
      }
    }
  }

  .submitBox {
    width: 100%;
    padding: 16rpx 40rpx 68rpx;
    background: #fff;
    position: fixed;
    box-sizing: border-box;
    bottom: 0;
    left: 0;
    .submit {
      width: 100%;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 32rpx;
      color: #ffffff;
      line-height: 44rpx;
      text-align: center;
      font-style: normal;
      background: #ba922f;
      border-radius: 6rpx;
      padding: 22rpx 0;
    }
  }
}

.card {
  // margin 32rpx
  background: #fff;
  // border 1rpx solid #ddd
  // border-radius 8rpx
  // box-shadow 0 0 8rpx 2rpx #ececec
  // box-shadow 2rpx 2rpx 2rpx #eee
  padding: 24rpx 0;
  font-size: 28rpx;
}

.store-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;

  image {
    height: 80rpx;
    width: 80rpx;
  }

  .name {
    flex: 6;
    font-size: 32rpx;
    margin-left: 20rpx;
  }

  .name-commodity {
    flex: 6;
    font-size: 28rpx;
    margin-left: 16rpx;
    max-width: 400rpx;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .isNoName {
    flex: 3;
    font-size: 26rpx;
    text-align: right;
  }
}

.star-box {
  width: 100%;
  display: flex;
  justify-content: center;
  text-align: center;
  padding-top: 48rpx;

  .rate-text {
    margin-top: 24rpx;
    color: #ee8c45;
    font-size: 28rpx;
  }
}

.evaluate-box {
  background-color: #fafafa;
  margin-top: 32rpx;
  // border 1rpx solid #ececec
  // border-radius 4rpx
  padding: 20rpx 0;

  textarea {
    width: 660rpx;
    color: #333;
    height: 160rpx;
    padding: 20rpx;
  }

  .tip-text {
    margin-top: 16rpx;
    color: #646464;
    text-align: right;
    padding-right: 20rpx;

    .tip-color {
      color: #ba9b6f;
    }
  }

  .photo-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .images {
      margin: 16rpx 0 16rpx 13rpx;
      position: relative;

      image {
        height: 140rpx;
        width: 140rpx;
        border-radius: 6rpx;
        background: #fff;
      }

      i {
        background: #ea4848;
        height: 30rpx;
        width: 30rpx;
        border-radius: 50%;
        position: absolute;
        top: -15rpx;
        right: -10rpx;

        &:after {
          content: " ";
          height: 4rpx;
          width: 18rpx;
          display: block;
          background: #fff;
          margin-top: 14rpx;
          margin-left: 6rpx;
          border-radius: 4rpx;
        }
      }
    }

    .add-photo {
      height: 138rpx;
      width: 138rpx;
      border-radius: 6rpx;
      background: #f7f8f9;
      border: 2rpx solid #e7e7e6;
      margin-left: 24rpx;
      text-align: center;
      color: #ba9b6f;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      i {
        margin-bottom: 12rpx;
        width: 42rpx;
        height: 36rpx;
        background: url("/static/images/pic.png") no-repeat center;
        background-size: contain;
      }
    }
  }
}

.post-btn {
  background: #e5e5e5;
  width: 690rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 6rpx;
  font-size: 30rpx;
  text-align: center;
  color: #898989;
  margin-left: 30rpx;
  margin-top: 100rpx;
}

&.active {
  background-color: #333;
  color: #fff;
}
</style>
