<template>
  <view class="page">
    <!-- <view class="content" v-if="showPage"> -->
    <view class="content" v-if="showPage">
      <view class="text-box">
        <view class="text-area">
          <textarea
            :value="textValue"
            style="height: 25vh"
            @input="textareaInput"
            @blur="textareaBlur"
            :placeholder="placeholder"
            maxlength="1000"
          />
        </view>
        <view class="topic-audio" v-if="showAudio&&voiceList.length > 0">
          <topic-audio
            :url="voiceList[0].url"
            :duration="voiceList[0].duration"
            @onAudioDel="handleAudioDel"
            :show-del="true"
          />
        </view>
        <view class="tools-box">
          <view class="item-box" @click="handleLocation">
            <view class="location-btn">
              <image
                mode="scaleToFill"
                src="../../static/data/images/location-icon.png"
              />
            </view>
            <view class="label">
              {{ curAddress }}
            </view>
            <view class="arrow-icon">
              <image
                mode="scaleToFill"
                src="../../static/data/images/arrow-right.png"
              />
            </view>
          </view>
          <view class="item-box">
            <view
              class="add-image"
              @click="voiceList.length > 0 ? '' : 'onTapAddVoice'"
            >
              <image
                mode="scaleToFill"
                :src="
                  '/data/images/' +
                  (voiceList.length > 0
                    ? 'voice-d.png'
                    : isVoice
                    ? 'voice-s.png'
                    : 'voice-u.png')
                "
              />
            </view>
          </view>
        </view>
      </view>
      <sound-record
        @onTapCancle="handleTapRecord"
        @onFinish="handleRecordFinish"
      />
      <view
        class="submit-btn"
        :style="'opacity:' + (isReport ? 1 : 0.3) + ';'"
        @click="report"
        >确认提交</view
      >
    </view>
  </view>
</template>

<script>
import soundRecord from "@/components/sound-record/sound-record";
import topicAudio from "@/components/topic-audio/topic-audio";
import { qqmapKey } from "../../utils/global";
import * as userTools from "../../utils/user";
import * as CustomerApi from "../../utils/api/customerApi";
const app = getApp();
export default {
  components: {
    // amIcon,
    // popup,
    soundRecord,
    topicAudio,
  },
  data() {
    return {
      userInfo: null,
      gridInfo: null,
      textValue: "",
      placeholder:
        "请详细填写您的诉求，力求文字简练，内容清楚，我们会将您的诉求通过一定的程序向有关责任单位交办和转办，并尽快向您反馈处理结果。",
      curAddress: "",
      locations: null,
      voiceList: [],
      showAudio: false,

      // voiceList: [
      //   {
      //     url:
      //       "https://epmet-dev.elinkservice.cn/epmet-oss-01/20220921/da45c0a8f15d4a1799d32f0a4969be84.ogg",
      //     duration: 10
      //   }
      // ],
      isReport: false,

      recorderManager: null,
      isVoice: true,
      systemInfo: null,
      contentHeight: 0,
      textBoxHeight: 0,
      textAreaHeight: 0,
      animationInfo: {},
      recordHeight: 0,
      KeyboardHeight: 0,
      showPage: true,
      url: "",
      duration: "",
    };
  },
  onLoad(options) {
    let _this = this;
    const token =
      process.env.NODE_ENV == "development"
        ? "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJhcHAiOiJyZXNpIiwiY2xpZW50IjoibGFuX3R1IiwiZXhwIjoxODA3OTMyMTM0LCJ1c2VySWQiOiIxNTUwMDA2MTc2ODI0MTcyNTQ1IiwiaWF0IjoxNzEzMzI0MTM0fQ.xHIy-gC0QRSgDGfgDxneQwKPyeBe3i1krKmCiIxjFaSLxr09O1mXdflkRa4WuiJbkpxUrvYH4H7J--VEFXeOpw"
		    : options.token;
    const gridId =
      process.env.NODE_ENV == "development"
        ? "1536616298755194882"
        : options.gridId;

    userTools.setStoreUserInfo(
      JSON.stringify({
        authorization: token,
      })
    );
    userTools.setStoreGridInfo(
      JSON.stringify({
        gridId: gridId,
      })
    );
    _this.init();
  },
  methods: {
    init() {
      let userInfo = userTools.getStoreUserInfo();
      let gridInfo = userTools.getStoreGridInfo();
      this.setData(
        {
          userInfo,
          gridInfo,
          systemInfo: app.globalData.systemInfo,
        },
        () => {
          this.computedViewHeight();
        }
      );
      if (!this.locations) {
        this.getLocation();
      } else {
        this.setData({
          showPage: true,
        });
      }
      setTimeout(() => {
        this.setData({
          showAudio: true,
        });
      }, 1000);
    },

    // 事件上报
    async fetchIcEventReprot() {
      let {
        images,
        textValue,
        locations,
        curAddress,
        voiceList,
        userInfo,
        gridInfo,
      } = this;
      let params = {
        content: textValue,
        gridId: userInfo.gridId || gridInfo.gridId,
        address: curAddress || "",
        longitude: locations.lng || "",
        latitude: locations.lat || "",
        voiceList,
      };
      uni.showLoading();
      let result = await CustomerApi.fetchIcEventReprot(params);
      let { code } = result;
      if (code == 0) {
        uni.hideLoading();
        uni.showToast({
          type: "success",
          title: "您的信息已收到，社区会及时处理",
        });
        this.setData(
          {
            textValue: "",
            voiceList: [],
            isReport: false,
          },
          () => {
            this.computedViewHeight();
          }
        );
      }
    },

    // 文本输入
    textareaInput(event) {
      let val = event.detail.value;
      this.setData({
        isReport: this.voiceList.length > 0 || val ? true : false,
      });
    },

    textareaBlur(event) {
      let val = event.detail.value;
      this.setData({
        textValue: val,
        isReport: this.voiceList.length > 0 || val ? true : false,
      });
    },

    onKeyboardShow(res) {
      this.setData({
        KeyboardHeight: res.data.height,
      });
    },

    computedViewHeight() {
      let { isVoice, voiceList, systemInfo } = this;
      let textBoxHeight =
        voiceList.length > 0
          ? parseInt(systemInfo.windowHeight * 0.77) + 30
          : !isVoice
          ? parseInt(systemInfo.windowHeight * 0.77) + 30
          : parseInt(systemInfo.windowHeight * 0.55) + 30;
      let textAreaHeight =
        voiceList.length > 0
          ? parseInt(textBoxHeight * 0.8) - 60
          : isVoice
          ? parseInt(textBoxHeight * 0.7)
          : parseInt(textBoxHeight * 0.8);
      var animation = uni.createAnimation({
        duration: 300,
        timeFunction: "ease",
      });
      this.animation = animation;
      animation.step();
      this.setData({
        contentHeight: systemInfo.windowHeight + 30,
        textBoxHeight,
        textAreaHeight,
        animationInfo: animation.export(),
      });
    },

    onTapAddVoice() {
      this.setData(
        {
          isVoice: !this.isVoice,
        },
        () => {
          this.computedViewHeight();
        }
      );
    },

    // 录音管理器
    initRecorderManager() {
      if (uni.canIUse("getRecorderManager")) {
        // 端上支持
        const recorderManager = uni.getRecorderManager();
        this.setData({
          recorderManager,
        });
      } else {
        // 端上不支持
        uni.alert({
          title: "请升级钉钉版本至4.5.18以支持录音功能",
        });
      }
    },

    // 取消录音
    handleTapRecord() {
      this.setData(
        {
          isVoice: !this.isVoice,
        },
        () => {
          this.computedViewHeight();
        }
      );
    },

    // 删除录音
    handleAudioDel() {
      this.setData(
        {
          voiceList: [],
        },
        () => {
          this.computedViewHeight();
        }
      );
    },

    handleRecordFinish(obj) {
      console.log(obj);
      let url = obj.url;
      let duration = obj.duration;
      let voiceList = [{
        url: url,
        duration: duration,
        format: "webm",
        type: "voice",
      }];
      // });
      this.setData(
        {
          voiceList,
          isReport: voiceList.length > 0 || this.textValue ? true : false,
          isVoice: !this.isVoice,
        },
        () => {
          this.computedViewHeight();
        }
      );
    },

    // 提交上报
    report() {
      this.fetchIcEventReprot();
    },

    // 选择定位
    handleLocation() {
      if (!this.locations) {
        uni.confirm({
          title: "温馨提示",
          content: "提交随手拍需要获取您的位置信息",
          confirmButtonText: "确定",
          success: (result) => {
            if (result.confirm) {
              this.getLocation();
            }
          },
        });
        return;
      }
      uni.navigateTo({
        url: `../map/index?locations=${JSON.stringify(this.locations)}`,
      });
    },

    // 定位
    getLocation() {
      uni.showLoading();
      let _this = this;
      const url =
        process.env.NODE_ENV !== "development"
          ? "https://lantu.ytyanhuo.com"
          : "";
      uni.getLocation({
        type: "gcj02",
        geocode: true,
        success(res) {
          _this.setData({
            curAddress: res.address,
            locations: {
              lng: res.longitude,
              lat: res.latitude,
            },
            showPage: true,
          });
          let params = {
            locations: `${res.latitude},${res.longitude}`,
          };
          uni.request({
            url: `${url}/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&referer=myapp&key=${qqmapKey}`,
            // 拼接请求地址
            method: "GET",
            // 请求方式
            data: params,
            dataType: "json",
            success: (res1) => {
              uni.hideLoading();
              _this.setData({
                curAddress: res1.data.result.address,
              });
            },
          });
        },
        fail() {
          uni.showModal({
            title: "温馨提示",
            content: "提交随手拍需要获取您的位置信息",
            confirmText: "确定",
            success: (result) => {
              if (result.confirm) {
                this.getLocation();
              }
            },
            fail() {
              uni.hideLoading();
              uni.alert({
                title: "事件上报需要您的位置,请打开定位。",
              });
            },
          });
        },
      });
      //   uni.showLoading();
      //   let _this = this;
      //   uni.getLocation({
      //     success(res) {
      //       uni.hideLoading();
      //       // console.log(res);
      //       _this.setData({
      //         curAddress: res.address,
      //         locations: {
      //           lng: res.longitude,
      //           lat: res.latitude,
      //         },
      //         showPage: true,
      //       });
      //     },
      //     fail() {
      //       uni.hideLoading();
      //       uni.alert({
      //         title: "事件上报需要您的位置,请打开定位。",
      //       });
      //     },
      //   });
    },
  },
};
</script>
<style>
.page {
  width: 100%;
  height: calc(100vh - 44px);
  /* justify-content: center; */
}

.content {
  display: flex;
  /* width: 100%; */
  position: relative;
  flex-direction: column;
  align-items: center;
}
.text-box {
  width: 94%;
  /* height: 65%; */
  /* padding: 40rpx 20rpx 0; */
  margin-top: 44rpx;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0px 2rpx 18rpx 0px rgba(63, 63, 63, 0.1);
  border-radius: 10rpx;
}

.text-area {
  /* height: 1200rpx; */
  display: flex;
  align-items: center;
  justify-content: center;
}
.text-area textarea {
  background-color: #f7f7f7;
  padding: 0;
  border-radius: 10rpx;
  font-size: 26rpx;
  margin: 20rpx;
  box-sizing: border-box;
}

.text-area .a-textarea {
  width: 94% !important;
}
.tools-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.item-box {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  width: 92%;
}

.item-box:first-child {
  /* justify-content: space-between; */
  border-bottom: 2rpx solid #e7eeee;
}
.location-btn {
  display: flex;
  align-items: center;
}
/* .location-btn {
  display: flex;
  align-items: center;
  height: 48rpx;
  background: #ffffff;
  border: 2rpx solid #999999;
  border-radius: 24rpx;
  padding: 0 20rpx 0 0;
} */

.location-btn image {
  width: 24rpx;
  height: 30rpx;
  margin: 0 10rpx;
}
.label {
  color: #015eea;
  flex: 1;
  /* width: calc(100% - 34rpx); */
  font-size: 28rpx;
}

.location-btn label {
  color: #999999;
}

.arrow-icon {
  width: 36rpx;
  height: 36rpx;
}
.arrow-icon image {
  width: 100%;
  height: 100%;
}

.image-d {
  position: absolute;
  width: 30rpx;
  height: 30rpx;
  top: 5rpx;
  right: 5rpx;
  border-radius: 50%;
  /* background-color: rgba(#707070, 0.8); */
  background-color: rgba(112, 112, 112, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-image {
  width: 50rpx;
  height: 50rpx;
}
.add-image image {
  width: 100%;
  height: 100%;
}

.submit-btn {
  /* position: fixed;
  bottom: 150rpx; */
  margin-top: 60rpx;
  width: 50%;
  height: 80rpx;
  background: #22BDF0;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.amd-popup-mask {
  display: none;
  pointer-events: all !important;
}
.amd-popup {
  pointer-events: none;
  /* position: none; */
  height: var(--textBoxHeight * 2) rpx im !important;
  position: absolute !important;
}

.record-card {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  /* animation: shutter-in-bottom; */
  pointer-events: none;
  display: flex;
  flex-direction: column;
  /* align-items: flex-end; */
  justify-content: flex-end;
}

@keyframes shutter-in-bottom {
  0% {
    transform: rotateX(100deg);
    transform-origin: bottom;
    opacity: 0;
  }
  100% {
    transform: rotateX(0);
    transform-origin: bottom;
    opacity: 1;
  }
}
</style>
