<template>
  <view class="main">
    <view class="formBox">
      <!-- 服务区名称 -->
      <view>
        <view class="formItem">
          <view class="itemTitle">服务区名称</view>
          <view class="itemValue" @click="handleChangeService">
            <view class="selectBox">
              <view class="picker" style="font-size: 28rpx"
                >{{
                  detailObj && detailObj.SERVERPART_NAME
                    ? detailObj.SERVERPART_NAME
                    : nowServerpart.SERVERPART_NAME || ""
                }}
              </view>
            </view>

            <image
              class="moreIcon"
              src="https://eshangtech.com/wanmeiyizhanImg/home/rightArrow.png"
            />
          </view>
        </view>
        <view class="formItem">
          <view class="itemTitle">服务区热线</view>
          <view class="itemValue">{{ showServicePhone || "" }} </view>
        </view>

        <!-- <view class="formItem">
          <view class="itemTitle">失物类型</view>
          <view class="itemValue">
            <view class="foundTypeBox">
              <picker
                bindchange="bindPickerChange"
                :value="lostTypeIndex"
                :range="lostTypeList"
                range-key="label"
              >
                <view class="picker"
                  >{{ lostTypeList[lostTypeIndex].label || "" }}
                </view>
              </picker>
            </view>
            <image class="moreIcon" src="https://eshangtech.com/wanmeiyizhanImg/home/rightArrow.png" />
          </view>
        </view> -->

        <view class="formItem" style="align-items: flex-start">
          <view class="itemTitle">
            {{
              addType === 1000 || detailObj.WECHAT_OPENID === "1000"
                ? "失物描述"
                : addType === 2000 || detailObj.WECHAT_OPENID === "2000"
                ? "招领描述"
                : ""
            }}</view
          >
          <view class="itemValue">
            <textarea
              :placeholder="
                addType === 1000
                  ? '请描述一下丢失物品'
                  : addType === 2000
                  ? '请描述一下招领物品'
                  : ''
              "
              :auto-height="true"
              style="font-size: 28rpx"
              placeholderStyle="font-size:28rpx;color: #B8B7B4;"
              v-model="shopName"
              :disabled="isDetail"
            />
          </view>
        </view>

        <view class="formItem">
          <view class="itemTitle">{{
            addType === 1000 || detailObj.WECHAT_OPENID === "1000"
              ? "丢失时间"
              : addType === 2000 || detailObj.WECHAT_OPENID === "2000"
              ? "拾得时间"
              : ""
          }}</view>
          <view
            class="itemValue"
            style="font-size: 28rpx"
            v-if="detailObj && detailObj.SUGGESTION_CREATEDATE"
            >{{ detailObj.SUGGESTION_CREATEDATE || "" }}</view
          >
          <view class="itemValue" v-else>
            <time-picker @update="onTimeUpdate" />
          </view>
        </view>

        <view class="formItem">
          <view class="itemTitle">联系电话</view>
          <view class="itemValue">
            <input
              style="font-size: 28rpx"
              placeholder="请输入手机号码"
              type="number"
              maxlength="11"
              v-model="phone"
              :disabled="isDetail"
            />
          </view>
        </view>

        <view class="formItem" style="align-items: flex-start">
          <view class="itemTitle">附件图片</view>
          <view
            class="itemValue"
            style="
              display: flex;
              flex-wrap: wrap;
              align-items: center;
              justify-content: flex-start;
            "
          >
            <view
              class="imgList"
              style="flex-wrap: wrap"
              v-if="imgList && imgList.length > 0"
            >
              <view
                class="imgBox"
                v-for="(item, index) in imgList"
                :key="index"
                @click="handlePreview(imgList, index)"
              >
                <image class="img" :src="item.ImageUrl" />
                <image
                  v-if="!isDetail"
                  @click="handleDeleteImg(item)"
                  class="deleteImg"
                  src="https://eshangtech.com/wanmeiyizhanImg/home/deleteImg.svg"
                />
              </view>
            </view>
            <view class="submitImg" @click="handleUpLoadImg" v-if="!isDetail">
              <image
                class="imgIcon"
                src="https://eshangtech.com/wanmeiyizhanImg/home/addImageIcon.svg"
              />
            </view>
          </view>
        </view>
      </view>
      <!-- v-if="!isDetail" -->
      <view class="btnBox">
        <button class="submitBox" type="primary" @click="formSubmit">
          {{ detailObj ? "保存" : "新增"
          }}{{ addType === 1000 ? "失物" : addType === 2000 ? "招领" : "" }}
        </button>
        <button
          v-if="showDeleteBtn"
          class="deleteBox"
          type="primary"
          @click="handleDelete"
        >
          删除失物
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import TimePicker from "./components/time-picker.vue";

export default {
  data() {
    return {
      nowServerpart: {},
      lostTypeIndex: 0,
      lostTypeList: [],
      shopName: "", // 商品名称
      phone: "", // 联系电话
      thisTime: "", // 当前时间
      addType: "", //  1000 失物  2000 招领
      imgList: [], // 图片列表
      isDetail: false, // 判断是不是来查看到
      detailObj: {}, // 详情
      loginType: "",
      showServicePhone: "", // 服务区热线
      showDeleteBtn: false, // 是否显示删除按钮
    };
  },
  components: {
    TimePicker,
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
  },
  onLoad(query) {
    console.log("user", this.user);
    console.log("query", query);
    let type = uni.getStorageSync("loginType");
    this.loginType = type;
    if (query.addType) {
      this.addType = Number(query.addType);
    }

    if (query.id) {
      this.isDetail = true;
      this.handleGetDetail(query.id);
    }
    uni.setNavigationBarTitle({
      title: `${query.id ? "编辑" : "新增"}${
        Number(query.addType) === 1000 ? "失物" : "招领"
      }`,
    });

    this.handleGetDefaultTime();
    // 先去拿枚举值
    this.handleGetTypeList();
    if (query.id) {
    } else {
      this.phone = this.user.MEMBERSHIP_MOBILEPHONE;
    }
  },
  onShow() {
    let currentService = uni.getStorageSync("addContact");
    console.log("addContact", currentService);
    if (currentService) {
      this.nowServerpart = currentService;
      this.detailObj.SERVERPART_NAME = currentService.SERVERPART_NAME;
      this.handleGetServiceDetail(currentService.SERVERPART_ID);
    } else {
      let nearService = uni.getStorageSync("nearService");
      this.nowServerpart = nearService;
      this.handleGetServiceDetail(nearService.SERVERPART_ID);
    }
  },
  onUnload() {
    uni.setStorageSync("addContact", null);
  },
  methods: {
    async handleGetServiceDetail(id) {
      const req = {
        ServerpartId: id,
      };

      let detailData = await this.$api.$get(
        "/CommercialApi/BaseInfo/GetServerpartInfo",
        req
      );
      console.log("detailData", detailData);
      let obj = detailData.Result_Data;
      this.showServicePhone = obj.SERVERPART_TEL;
    },
    // 预览
    handlePreview(imgList, index) {
      console.log("imgList", imgList);
      console.log("index", index);
      let list = [];
      if (imgList && imgList.length > 0) {
        imgList.forEach((item) => {
          list.push(item.ImageUrl);
        });
      }
      uni.previewImage({
        current: list[index], // 当前显示图片的http链接
        urls: list, // 需要预览的图片http链接列表
      });
    },
    // 查看失物招领详情
    async handleGetDetail(id) {
      const req = {
        SUGGESTIONId: id,
      };
      const data = await this.$api.$get(
        "/EShangApiMain/SiteManage/GetSUGGESTIONDetail",
        req
      );
      console.log("handleGetDetail", data);
      this.detailObj = data.Result_Data;
      this.shopName = data.Result_Data.SUGGESTION_TITLE;
      this.imgList = data.Result_Data.ImageList;
      this.phone = data.Result_Data.PHONE_NUMBER;
      this.showDeleteBtn =
        this.user.MEMBERSHIP_ID === data.Result_Data.MEMBERSHIP_ID &&
        data.Result_Data.WECHAT_OPENID === "1000";
    },
    //   删除图片
    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;
      }
    },
    // 上传图片
    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] });
        },
      });
    },
    //   获取当前的默认时间
    handleGetDefaultTime() {
      const date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let h = date.getHours();
      let min = date.getMinutes();
      if (m < 10) {
        m = "0" + m;
      }
      if (d < 10) {
        d = "0" + d;
      }
      if (h < 10) {
        h = "0" + h;
      }
      if (min < 10) {
        min = "0" + min;
      }
      this.thisTime = `${y}-${m}-${d} ${h}:${min}`;
    },
    //   更新时间
    onTimeUpdate(e) {
      console.log("e", e);
      this.thisTime = `${e.date} ${e.time}`;
    },
    // 删除
    handleDelete() {
      uni.showModal({
        title: "提示",
        content: "确认删除？",
        success: async (res) => {
          if (res.confirm) {
            let req = {
              ...this.detailObj,
              SUGGESTION_STATE: 0,
            };
            const data = await this.$api.$post(
              "/EShangApiMain/SiteManage/SynchroSUGGESTION",
              req
            );
            if (data.Result_Code === 100) {
              uni.showToast({
                title: "删除成功！",
                icon: "none",
              });
              uni.setStorageSync("contactReload", true);

              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 1000);
            }
          }
        },
      });
    },
    async formSubmit() {
      if (!this.nowServerpart.SERVERPART_ID) {
        uni.showToast({
          title: "请选择服务区！",
          icon: "none",
        });
        return;
      }

      // if (
      //   (this.lostTypeList && this.lostTypeList.length > 0) ||
      //   this.lostTypeList[this.lostTypeIndex].value
      // ) {
      // } else {
      //   uni.showToast({
      //     title: "请选择失物类型！",
      //     icon: "none",
      //   });
      //   return;
      // }

      if (!this.shopName) {
        uni.showToast({
          title: "请描述一下丢失物品",
          icon: "none",
        });
        return;
      }
      console.log("this.phone", this.phone);
      if (!this.phone) {
        uni.showToast({
          title: "请输入联系电话",
          icon: "none",
        });
        return;
      } else {
        const phonePattern = /^1[3-9]\d{9}$/; // 中国大陆手机号校验规则
        if (!phonePattern.test(this.phone)) {
          uni.showToast({
            title: "手机号格式不正确",
            icon: "none",
          });
          return;
        }
      }

      let req = {};
      if (this.detailObj.SUGGESTION_ID) {
        req = {
          ...this.detailObj,
          SERVERPART_ID: this.nowServerpart.SERVERPART_ID,
          SUGGESTION_TITLE: this.shopName,
          PHONE_NUMBER: this.phone,
          DISPOSITION_PERSON: this.user.MEMBERSHIP_NAME,
          SERVERPART_NAME: this.nowServerpart.SERVERPART_NAME,
          SUGGESTION_REASON: this.showServicePhone,
        };
      } else {
        req = {
          SERVERPART_ID: this.nowServerpart.SERVERPART_ID,
          // ENUM_LABEL: this.lostTypeList[this.lostTypeIndex].value,
          SUGGESTION_TITLE: this.shopName,
          PHONE_NUMBER: this.phone,
          PROVINCE_CODE: "340000",
          SUGGESTION_CREATEDATE: this.thisTime,
          SUGGESTION_STATE: 1,
          SUGGESTION_TYPE: 4000,
          SUGGESTION_NAME: this.user.MEMBERSHIP_NAME,
          SERVERPART_NAME: this.nowServerpart.SERVERPART_NAME,
          WECHAT_OPENID: this.addType,
          SUGGESTION_REASON: this.showServicePhone,
        };
      }

      const data = await this.$api.$post(
        "/EShangApiMain/SiteManage/SynchroSUGGESTION",
        req
      );
      console.log("data", data);
      if (data.Result_Code === 100) {
        if (this.imgList && this.imgList.length > 0) {
          // 获取文件管理器
          let fs;
          if (this.loginType === "min") {
            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: "1306", // 表单中其他数据
                    TableId: data.Result_Data.SUGGESTION_ID,
                    // 如果你有其他字段需要传递，也可以在这里添加
                  },
                  success: (uploadRes) => {},
                  fail: (uploadRes) => {
                    _this.file = uploadRes;
                  },
                });
              }
            });
          } else {
            fs = plus.io;
            console.log("fs", fs);
            console.log("this.imgList", this.imgList);
            this.imgList.forEach((imagePath, index) => {
              console.log("imagePath", imagePath);
              if (!imagePath.ImageId) {
                fs.resolveLocalFileSystemURL(
                  imagePath.ImageUrl,
                  function (entry) {
                    entry.file(function (file) {
                      var reader = new plus.io.FileReader();
                      reader.onloadend = function (e) {
                        console.log("readRes", e.target.result);
                        const filePath = plus.io.convertLocalFileSystemURL(
                          imagePath.ImageUrl
                        );
                        uni.uploadFile({
                          url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture",
                          filePath: filePath, // 绝对路径
                          name: "file",
                          formData: {
                            Tabletype: "1306",
                            TableId: data.Result_Data.SUGGESTION_ID,
                          },
                          success: (uploadRes) => {
                            console.log("上传成功", uploadRes);
                          },
                          fail: (err) => {
                            console.error("上传失败", err);
                          },
                        });
                      };
                      reader.readAsDataURL(file);
                    });
                  },
                  function (error) {
                    console.log("文件读取失败", error);
                  }
                );
              }
            });
          }
        }
        uni.showToast({
          title: data.Result_Desc,
          icon: "success",
        });
        uni.setStorageSync("contactReload", true);
        setTimeout(() => {
          uni.navigateBack({
            delta: 1,
          });
        }, 1000);
      } else {
        uni.showToast({
          title: data.Result_Desc,
          icon: "error",
        });
      }
    },
    // 点击跳转改变服务区
    handleChangeService() {
      uni.navigateTo({ url: "/pages/newMap/index/index?comeForm=addContact" });
      return;
      if (this.detailObj) {
      } else {
        uni.navigateTo({ url: "/pages/newMap/index/index" });
      }
    },
    // 拿到类型枚举
    async handleGetTypeList() {
      const data = await this.$api.$get(
        "/EShangApiMain/FrameWork/GetFieldEnumTree",
        { FieldExplainField: "business_target" }
      );
      let list = this.$utils.wrapTreeNode(data.Result_Data.List);
      let res = [];
      if (list && list.length > 0) {
        list.forEach((item) => {
          if (item.value === 6000) {
            let typeList = item.children;
            if (typeList && typeList.length > 0) {
              typeList.forEach((typeItem) => {
                if (typeItem.children && typeItem.children.length > 0) {
                  typeItem.children.forEach((subItem) => {
                    res.push({ label: subItem.label, value: subItem.value });
                  });
                }
              });
            }
          }
        });
      }
      console.log("resresresresres", res);
      this.lostTypeList = res;
    },
  },
};
</script>
<style scoped lang="less">
.main {
  width: 100%;
  height: 100vh;
  background: #f7f7f7;
  box-sizing: border-box;
  // padding: 16px;
  .formBox {
    width: 100%;
    height: 100%;
    background: #fff;
    box-sizing: border-box;
    // padding: 12px 16px;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .formItem {
      width: 100%;
      display: flex;
      align-items: center;
      padding: 36rpx 32rpx;
      border-bottom: 1px solid #f5f6f7;
      box-sizing: border-box;
      // padding: 12px 0;
      .itemTitle {
        width: 30%;
        font-family: "PingFangSC";
        font-weight: 400;
        font-size: 28rpx;
        color: #130f05;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
      }
      .itemValue {
        width: 70%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        font-family: "PingFangSC";
        font-weight: 400;
        font-size: 28rpx;
        color: #130f05;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        .selectBox {
          width: 100%;
        }
        .foundTypeBox {
        }

        .moreIcon {
          width: 24rpx;
          height: 24rpx;
        }

        .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;
          }
        }
      }
    }
    .btnBox {
      width: 100%;
      box-sizing: border-box;
      padding: 0 40rpx;
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);
      .submitBox {
        background-color: #ba922f;
        font-family: "PingFangSC";
        font-weight: 400;
        font-size: 32rpx;
        color: #ffffff;
        line-height: 44rpx;
        text-align: center;
        font-style: normal;
        padding: 22rpx 0;
      }
      .deleteBox {
        font-family: "PingFangSC";
        font-weight: 400;
        font-size: 32rpx;
        color: #ba922f;
        line-height: 44rpx;
        text-align: center;
        font-style: normal;
        border: 1px solid #ba922f;
        background: transparent;
        padding: 22rpx 0;
        margin-top: 16rpx;
      }
    }
  }
}
</style>