<template>
  <view class="fillLog">
    <header></header>
    <view class="form">
      <view class="main">
        <div class="textarea">
          <div class="color-333"><span class="color-red">*</span>活动总结</div>
          <textarea
            type="textarea"
            placeholder="填写本次活动参与心得体会（200字以内）"
            v-model="baseInfo.content"
            adjust-position="false"
            maxlength="200"
          ></textarea>
        </div>
        <view class="uni-uploader">
          <view class="title-box title-box-margin">
            <text class="title">活动照片（最多9张）</text>
          </view>
          <view class="uni-uploader-body">
            <view class="uni-uploader__files">
              <block v-for="(image, index) in imageList" :key="index">
                <view class="uni-uploader__file">
                  <image
                    class="uni-uploader__img"
                    :src="image.accessUrl"
                    :data-index="index"
                    @tap="previewImage"
                  ></image>
                  <AiUniIcon
                    type="clear"
                    class="icon"
                    color="#8f8f94"
                    size="20"
                    @click="deleteImage(index)"
                  ></AiUniIcon>
                </view>
              </block>
              <view
                class="pre-view"
                @tap="chooseImageType"
                v-if="imageList.length < 9"
              >
                <text class="pre-label">+</text>
                <text class="add-image">添加照片</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="report" @click="report()">提交</view>
  </view>
</template>

<script>
import settings from "@/utils/config"
import {mapState} from 'vuex'
export default {
  name: "fillLog",
  data() {
    return {
      reportId: "",
      baseInfo: {
        content: "",
        fileIds: [],
        reportId: "",
        id: "",
      },
      imageList: [],
      sourceTypeIndex: 2,
      sourceType: [
        // 图片来源类型
        ["camera"],
        ["album"],
      ],
    };
  },
  onLoad(options) {
    uni.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#e60012",
    });
    this.baseInfo.reportId = options.reportId;
    this.baseInfo.id = options.signupId;
    options.signupContent ? this.logReport() : null;
  },
  computed: {
    ...mapState(['user']),
  },
  methods: {
    // 选择照片类型
    chooseImageType() {
      let that = this;
      uni.showActionSheet({
        itemList: ["拍照", "从相册选择"],
        success: function (res) {
          that.sourceTypeIndex = res.tapIndex;
          that.chooseImage();
        },
      });
    },
    showModel(title) {
      uni.showModal({
        title: "温馨提示",
        content: title,
        showCancel: false,
        confirmColor: "#135AB8",
      });
    },
    chooseImage: async function () {
      let that = this;
      if (that.imageList.length === 9) {
        let isContinue = await that.isFullImg();
        if (!isContinue) {
          return;
        }
      }
      uni.chooseImage({
        // 从相册选择或相机拍摄
        sourceType: that.sourceType[that.sourceTypeIndex],
        // 最多可以选择的图片数量
        count: 9,
        success: (res) => {
          // 图片的本地文件路径列表
          that.tempFilePaths = res.tempFilePaths;
          // console.log(res.tempFilePaths)
          for (let i = 0; i < that.tempFilePaths.length; i++) {
            let str = "";
            let token = uni.getStorageSync("token");
            // console.log('token',token)
            let params = {
              token: token,
            };
            // url String 是 开发者服务器 url
            // files Aarry 否 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。 5+App
            // filePath String 是 要上传文件资源的路径。
            // name String 是 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
            // header Object 否 HTTP 请求 Header, header 中不能设置 Referer
            // formData Object 否 HTTP 请求中其他额外的 form data
            // success Function 否 接口调用成功的回调函数
            // fail Function 否 接口调用失败的回调函数
            // complete Function 否 接口调用结束的回调函数（调用成功、失败都会执行）
            uni.uploadFile({
              url: settings.baseUrl + "/admin/file/add",
              filePath: that.tempFilePaths[i],
              name: "file",
              // formData:params,
              header: {
                "Content-Type": "multipart/form-data",
                access_token: token,
                Authorization: token,
              },
              success(res) {
                str = JSON.stringify(JSON.parse(res.data).data[0]).replace(
                  /\"/g,
                  ""
                );
                var temp = {
                  fileId: str.split(";")[1],
                  accessUrl: str.split(";")[0],
                };
                that.imageList = that.imageList.concat(temp);
                if (that.imageList.length > 9) {
                  that.imageList = that.imageList.slice(0, 9);
                  uni.showToast({
                    title: "图片最多只能上传9张",
                    icon: "none",
                  });
                }
                that.imgUrl = JSON.stringify(that.imageList);
              },
              fail(res) {
                console.log("error", res);
              },
            });
          }
        },
      });
    },
    // 预览图片(大图预览)
    previewImage: function (e) {
      let that = this;
      var current = e.target.dataset.index;

      var tempList = [];
      for (var i in that.imageList) {
        tempList.push(that.imageList[i].accessUrl);
      }

      uni.previewImage({
        // 当前图片的索引、链接
        current: tempList[current],
        urls: tempList,
        longPressActions: {
          itemList: ["发送给朋友", "保存图片", "收藏"],
          success: function (data) {
            // console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
          },
          fail: function (err) {
            console.log(err.errMsg);
          },
        },
      });
    },
    // 删除照片
    deleteImage(index) {
      this.imageList.splice(index, 1);
    },
    report() {
      let arr = [];
      if (!this.baseInfo.content) {
        this.showModel("请填写活动总结");
        return false;
      }
      this.imageList.map((e) => {
        arr.push(e.fileId);
      });
      this.baseInfo.fileIds = arr;
      this.$instance
        .post(`/app/apppartyreport/log-add`, this.baseInfo)
        .then((res) => {
          if (res.code == 0) {
            this.$u.toast('提交成功')
            setTimeout(() =>{
              uni.navigateBack({
                delta: 1,
              });
            }, 500)
          }
        })
        .catch((err) => {
          this.$u.toast('提交失败')
        });
    },

    logReport() {
      this.$instance
        .post(
          `/app/apppartyreport/log-report?partyId=${this.user.partyId}&reportId=${this.baseInfo.reportId}`
        )
        .then((res) => {
          if (res.code == 0 && res.data) {
            this.baseInfo.content = res.data.content;
            this.baseInfo.fileIds = res.data.fileIds;
            res.data.files.map((e) => {
              this.imageList.push({ accessUrl: e.accessUrl, fileId: e.id });
            });
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.fillLog {
  width: 100%;
  height: 100%;
  header {
    width: 100%;
    height: 112rpx;
    background-color: #e60012;
  }
  .form {
    width: 100%;
    padding: 32px 32px 120px 32px;
    box-sizing: border-box;
    margin-top: -100rpx;
    .main {
      background-color: #fff;
      border-radius: 8rpx;
      padding: 16rpx;
      box-sizing: border-box;

      .textarea {
        width: 100%;
        textarea {
          width: 100%;
        }
      }
    }
    .basic-item {
      font-size: 32rpx;
      justify-content: space-between;
      width: 100%;
      height: 112rpx;
      padding: 32rpx 32rpx 32rpx 12rpx;
      box-sizing: border-box;
      background-color: #fff;
      border-bottom: 1rpx solid #eee;
      input {
        text-align: right;
      }
      .wid-110 {
        width: 214rpx;
      }
      .skill-text {
        max-width: 432rpx;
        text-align: right;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 30rpx;
      }
      .picker {
        justify-content: flex-end;
        align-items: center;
        color: #999999;
        font-size: 32rpx;
        background-color: #ffffff;
      }
      .picker > .AiArea {
        background-color: #fff !important;
      }
      .image {
        width: 32rpx;
        height: 32rpx;
        vertical-align: middle;
      }
      .wei-text {
        width: 40%;
      }
      .msg-value {
        width: 60%;
      }
      .msg-btn {
        width: 160px;
        text-align: right;
        background-color: #fff !important;
      }

      button {
        font-size: 28rpx;
        background-color: #fff;
        line-height: 48rpx;
        padding: 0;
      }

      button::after {
        border: 0;
      }

      .button-hover {
        background-color: #fff;
      }

      button[disabled] {
        background-color: #fff !important;
        font-size: 28rpx;
        border-radius: 0;
      }
    }
    /* 上传照片 */
    .uni-uploader {
      flex: 1;
      flex-direction: column;
    }
    .uni-uploader-head {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
    .uni-uploader-info {
      color: #b2b2b2;
    }
    .uni-uploader-body {
      margin-top: 16rpx;
    }
    .uni-uploader__files {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    .uni-uploader__file {
      margin-right: 10rpx;
      margin-bottom: 20rpx;
      width: 30%;
      height: 200px;
      position: relative;
    }
    .uni-uploader__img {
      display: block;
      width: 100%;
      height: 100%;
    }
    .pre-label {
      font-size: 80rpx;
      color: #dddddd;
    }
    .add-image {
      color: #dddddd;
      font-size: 24rpx;
    }
    .pre-view {
      width: 30%;
      height: 200px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      border-radius: 8rpx;
      border: 2rpx solid #dddddd;
    }
    .icon {
      position: absolute;
      top: -15rpx;
      right: -10rpx;
    }
  }
  .report {
    position: fixed;
    left: 0;
    bottom: 0;
    height: 112rpx;
    line-height: 112rpx;
    font-size: 32rpx;
    text-align: center;
    background: rgba(230, 0, 18, 1);
    color: #fff;
  }
}
</style>