<template>
  <view class="main">
    <textarea
      class="titleBox"
      placeholder="请输入标题"
      placeholder-style="font-size: 40rpx;line-height: 56rpx"
      auto-height
      :value="titleName"
      @input="handleGetTitle"
      :maxlength="50"
    />

    <textarea
      class="contentBox"
      placeholder="请输入正文"
      placeholder-style="font-size: 32rpx;line-height: 44rpx"
      :value="contentText"
      @input="handleGetContentText"
      :maxlength="500"
    />

    <view class="submitBox">
      <view class="imgList" v-for="(item, index) in imgList" :key="index">
        <view class="imgBox">
          <image class="img" :src="item.ImageUrl" />
          <image
            @click="handleDeleteImg(item)"
            class="deleteImg"
            src="/static/images/home/deleteImg.svg"
          />
        </view>
      </view>
      <view class="submitImg" @click="handleUpLoadImg">
        <image class="imgIcon" src="/static/images/home/addImageIcon.svg" />
      </view>
    </view>

    <!-- <view>
      {{ JSON.stringify(file) }}
    </view> -->
    <view class="labelBox">
      <span class="labelTitle">标签：</span>

      <view class="labelList">
        <view
          :class="
            selectLabel === item.value ? 'labelItem selectLabel' : 'labelItem'
          "
          v-for="(item, index) in labelList"
          :key="index"
          @click="handleChangeLabel(item.value)"
        >
          #{{ item.label }}
        </view>
      </view>
    </view>

    <view class="releaseBox" @click="handleRelease">发布</view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      titleName: "", // 输入的标题内容
      contentText: "", // 输入的正文内容
      labelList: [],
      selectLabel: 1,
      imgList: [], // 图片列表
      currentId: "", // 当前的帖子id
      detailObj: {}, // 详情
      loginType: "", // 登录类型
      file: "",
    };
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
  },
  onLoad(query) {
    let type = uni.getStorageSync("loginType");
    this.loginType = type;
    console.log("query", query);
    if (query.id) {
      this.currentId = query.id;
      this.handleGetPostDetail(query.id);
    }
    this.handleGetTypeList();
  },
  methods: {
    //   删除图片
    async handleDeleteImg(obj) {
      console.log("obj", obj);
      if (obj.ImageId) {
        const data = await this.$api.$get(
          "/EShangApiMain/Picture/DeletePicture",
          {
            ImageId: obj.ImageId,
            ImagePath: obj.ImagePath,
            TableType: 6000,
          }
        );
        console.log("data", data);
        if (data.Result_Code === 100) {
          let newList = [];
          this.imgList.forEach((item) => {
            if (item.ImageId !== obj.ImageId) {
              newList.push(item);
            }
          });
          this.imgList = newList;
          uni.showToast({
            title: data.Result_Desc || "更新成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: data.Result_Desc,
            icon: "none",
          });
        }
      } else {
        let newList = [];
        this.imgList.forEach((item) => {
          if (item.ImageUrl !== obj.ImageUrl) {
            newList.push(item);
          }
        });
        this.imgList = newList;
      }
    },
    //   查询当前这个帖子id的详情
    async handleGetPostDetail(id) {
      uni.showLoading({
        title: "加载中...",
      });
      const req = {
        POSTId: id,
      };
      const data = await this.$api.$get("/Member/GetPOSTDetail", req);
      console.log("handleGetPostDetail", data);
      this.detailObj = data.Result_Data;

      this.titleName = data.Result_Data.POST_TITLE;
      this.contentText = data.Result_Data.POST_CONTENT;
      this.selectLabel = Number(data.Result_Data.POST_TAG);
      this.imgList = data.Result_Data.ImageList;
      uni.hideLoading();
    },
    // 拿到类型枚举
    async handleGetTypeList() {
      const data = await this.$api.$get(
        "/EShangApiMain/FrameWork/GetFieldEnumTree",
        { FieldExplainField: "business_target" }
      );
      let list = this.$utils.wrapTreeNode(data.Result_Data.List);
      console.log("listlistlist", list);
      let typeList = [];
      let typeObj = {};
      // 拿到发帖的枚举
      if (list && list.length > 0) {
        list.forEach((item) => {
          if (item.value === 7000) {
            console.log("item", item);
            if (item.children && item.children.length > 0) {
              item.children.forEach((subItem) => {
                typeList.push(subItem);
              });
            }
          }
        });
      }
      this.labelList = typeList;
      this.selectLabel = typeList[0].value;
    },
    // 将 字符串中的 " 全部替换成 /"  单个'变为两个'
    handleGetNewStr(str) {
      return str.replace(/"/g, '/"').replace(/'/g, "''");
    },
    // 上传图片单拆出来的方法
    async uploadImage(imagePath, fs, data) {
      try {
        const readRes = await new Promise((resolve, reject) => {
          fs.readFile({
            filePath: imagePath.ImageUrl,
            encoding: "base64",
            success: (res) => resolve(res),
            fail: (err) => reject(err),
          });
        });

        console.log("readRes ", readRes);
        await uni.uploadFile({
          url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture", // 你的接口 URL
          filePath: imagePath.ImageUrl, // 上传文件的路径
          name: "file", // 表单中的文件字段名
          formData: {
            Tabletype: "1307", // 表单中其他数据
            TableId: data.Result_Data.POST_ID,
          },
        });
      } catch (error) {
        console.error("上传图片失败:", error);
      }
    },

    // 发布
    async handleRelease() {
      let _this = this;
      if (!this.titleName) {
        uni.showToast({
          title: "请输入标题",
          icon: "none",
        });
        return;
      }

      if (!this.contentText) {
        uni.showToast({
          title: "请输入正文",
          icon: "none",
        });
        return;
      }

      if (!this.selectLabel) {
        uni.showToast({
          title: "请选择标签",
          icon: "none",
        });
        return;
      }

      uni.showLoading({
        title: "加载中...",
      });
      console.log("titleName", this.titleName);
      console.log("contentText", this.contentText);
      console.log("imgList", this.imgList);
      console.log("user", this.user);
      let now = new this.$moment().format("YYYY-MM-DD HH:mm:ss");
      console.log("now", now);
      let req = {};
      console.log("this.detailObj", this.detailObj);
      if (this.detailObj.POST_ID) {
        req = {
          ...this.detailObj,
          POST_TITLE: this.handleGetNewStr(this.titleName),
          POST_CONTENT: this.handleGetNewStr(this.contentText),
          PUBLISH_TIME: now,
          POST_TAG: this.selectLabel,
        };
      } else {
        req = {
          AUTHOR_NAME:
            this.user.MEMBERSHIP_NAME || this.user.MEMBERSHIP_MOBILEPHONE, // 作者名称
          POST_TITLE: this.handleGetNewStr(this.titleName),
          POST_CONTENT: this.handleGetNewStr(this.contentText),
          POST_PLATFORM: "min",
          PUBLISH_TIME: now,
          POST_TAG: this.selectLabel,
          WECHATAPP_APPID: "wx4c497eddcec4a0e7",
          appId: "wx4c497eddcec4a0e7",
          weChatAppId: "wx4c497eddcec4a0e7",
          wechatAppAppId: "wx4c497eddcec4a0e7",
          POST_STATE: 1,
        };
      }
      console.log("req", req);
      const data = await this.$api.$post("/Member/SynchroPOST", req);
      console.log("datadsad", data);
      if (data.Result_Code === 100) {
        console.log("this.imgList", this.imgList);
        if (this.imgList && this.imgList.length > 0) {
          // 获取文件管理器
          let fs;
          if (this.loginType === "min") {
            // fs = uni.getFileSystemManager();
            // console.log("fs", fs);
            // for (let i = 0; i < this.imgList.length > 0; i++) {
            //   let imagePath = this.imgList[i];
            //   console.log("imagePath", imagePath);
            //   if (!imagePath.ImageId) {
            //     await this.uploadImage(imagePath, fs, data);
            //   }
            // }
            this.imgList.forEach((imagePath, index) => {
              console.log("imagePath.ImageUrl", imagePath.ImageUrl);

              if (!imagePath.ImageId) {
                uni.uploadFile({
                  url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture", // 你的接口 URL
                  filePath: imagePath.ImageUrl, // 上传文件的路径
                  name: "file", // 表单中的文件字段名
                  formData: {
                    Tabletype: "1307", // 表单中其他数据
                    TableId: data.Result_Data.POST_ID,
                    // 如果你有其他字段需要传递，也可以在这里添加
                  },
                  success: (uploadRes) => {},
                  fail: (uploadRes) => {
                    _this.file = uploadRes;
                  },
                });
              }

              // if (!imagePath.ImageId) {
              //   fs.readFile({
              //     filePath: imagePath.ImageUrl,
              //     encoding: "base64",
              //     success: (readRes) => {
              //       uni.uploadFile({
              //         url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture", // 你的接口 URL
              //         filePath: imagePath.ImageUrl, // 上传文件的路径
              //         name: "file", // 表单中的文件字段名
              //         formData: {
              //           Tabletype: "1307", // 表单中其他数据
              //           TableId: data.Result_Data.POST_ID,
              //           // 如果你有其他字段需要传递，也可以在这里添加
              //         },
              //         success: (uploadRes) => {},
              //       });
              //     },
              //   });
              // }
            });
          } else {
            fs = plus.io;
            console.log("fs", fs);
            this.imgList.forEach((imagePath, index) => {
              if (!imagePath.ImageId) {
                fs.FileReader({
                  filePath: imagePath.ImageUrl,
                  encoding: "base64",
                  success: (readRes) => {
                    uni.uploadFile({
                      url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture", // 你的接口 URL
                      filePath: imagePath.ImageUrl, // 上传文件的路径
                      name: "file", // 表单中的文件字段名
                      formData: {
                        Tabletype: "1307", // 表单中其他数据
                        TableId: data.Result_Data.POST_ID,
                        // 如果你有其他字段需要传递，也可以在这里添加
                      },
                      success: (uploadRes) => {},
                    });
                  },
                });
              }
            });
          }

          uni.showToast({
            title: data.Result_Desc || "更新成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        } else {
          uni.showToast({
            title: data.Result_Desc || "更新成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
          uni.hideLoading();
        }
      } else {
        uni.showToast({
          title: data.Result_Desc || "请求失败",
          icon: "none",
        });
        uni.hideLoading();
      }
    },
    // 拿到title的值
    handleGetTitle(e) {
      this.titleName = e.detail.value;
    },
    // 拿到正文的值
    handleGetContentText(e) {
      this.contentText = e.detail.value;
    },
    //  改变标签的选择
    handleChangeLabel(value) {
      this.selectLabel = value;
    },
    // 上传图片
    handleUpLoadImg() {
      let _this = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(rs) {
          console.log("rs", rs);
          _this.imgList.push({ ImageUrl: rs.tempFilePaths[0] });
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.main {
  width: 100vw;
  box-sizing: border-box;
  padding: 16rpx 32rpx;
  .titleBox {
    display: inline-block;
    width: 100%;
    font-size: 40rpx;
    line-height: 56rpx;
    margin-bottom: 16rpx;
  }
  .contentBox {
    display: inline-block;
    width: 100%;
    height: 900rpx;
    font-size: 32rpx;
    line-height: 44rpx;
  }

  .submitBox {
    width: 100%;
    margin-top: 16rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    .imgList {
      display: flex;
      .imgBox {
        width: 160rpx;
        height: 160rpx;
        margin-right: 16rpx;
        border-radius: 8rpx;
        margin-bottom: 16rpx;
        position: relative;
        .img {
          width: 100%;
          height: 100%;
        }
        .deleteImg {
          position: absolute;
          // top: -15rpx;
          // right: -15rpx;
          top: 0;
          right: 0;
          width: 30rpx;
          height: 30rpx;
        }
      }
    }

    .submitImg {
      display: inline-block;
      width: 160rpx;
      height: 160rpx;
      background: #f7f8f9;
      border-radius: 4rpx;
      border: 2rpx dashed #e7e7e6;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 16rpx;
      .imgIcon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .labelBox {
    width: 100%;
    margin-top: 32rpx;
    display: flex;
    align-items: center;
    .labelTitle {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #716f69;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
    }
    .labelList {
      display: flex;
      align-items: center;
      .labelItem {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #716f69;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        padding: 4rpx 6rpx;
        background: #f5f6f7;
        border-radius: 4rpx;
        margin-right: 16rpx;
      }
      .selectLabel {
        color: #ba922f;
        background: #f8f4ea;
      }
    }
  }

  .releaseBox {
    width: 100%;
    background: #ba922f;
    color: #fff;
    padding: 22rpx 0;
    border-radius: 6rpx;
    text-align: center;
    margin-top: 40rpx;
  }
}
</style>