<template>
  <!-- 一键反映 -->
  <view class="alarm">
    <custom-tabs type="c1" :value="activeTab" @change="changeTab" :defaultTextStyle="{color:'#999'}">
      <custom-tab-pane label="电话反映" name="c1_alarm1">
        <view class="content">
          <view class="phone" @tap="callPhone(item)" v-for="(item, index) in phoneList" :key="index">
            <view class="left-area">
              <image class="alarm-icon" :src="'/subPages/static/images/alarm/' + item + '.png'"></image>
              <view>
                <view class="number">{{item}}</view>
                <view class="describe">一键拨打{{item}}</view>
              </view>
            </view>
            <image class="phone-icon" src="/subPages/static/images/alarm/phone-unselected@2x.png"></image>
          </view>
        </view>
      </custom-tab-pane>
      <custom-tab-pane label="静默反映" name="c1_alarm2">
        <view class="content">
          <view class="alarm-info">
            <view class="text">
              <textarea :value="message" placeholder="请输入需要反映的内容" @input="changeMessage" />
            </view>
            <view class="attachment">
              <file-upload2 ref="files" :maxCount=4></file-upload2>
              <!-- 浙里办未开放录音能力 -->
            <!--   <view class="audio">
                <image class="audio-icon" @tap="recordAudio" :src="audioIconUrl"></image>
                <view v-if="isRecordAudio">正在录音...</view>
              </view> -->
            </view>
          </view>
          <view class="alarm-way">
            <view class="title">反映途径</view>
            <view class="btn-list">
              <button
                class="btn" :style="item === telephone ? 'opacity: 1;' : 'opacity: 0.3;'"
                v-for="(item, index) in phoneList" :key="index"
                @click="changeAlarWay(item)">
                {{ item }}
              </button>
            </view>
          </view>
          <view class="submit">
            <button class="submit-button" @tap="saveAlarm">提交</button>
          </view>
        </view>
      </custom-tab-pane>
    </custom-tabs>
    <image
      class="record-icon"
      mode="aspectFit"
      src="/subPages/static/images/common/history-unselected@2x.png"
      @tap="alarmRecord">
    </image>
  </view>
</template>

<script>
import { getDictionaryByName, uploadFile } from '@/api/system';
import { saveAlarm } from '@/api/alarm';
const recorderManager = uni.getRecorderManager();

export default {
  data() {
    return {
      userInfo: {},
      activeTab: '0',
      doorId: '',
      alarmTypeOptions: [],
      callType: 1,
      message: '',
      fileList: [],
      imageStyles: { width: 64, height: 64 },
      isRecordAudio: false,
      audioIconUrl: '/subPages/static/images/common/voice-unselected@2x.png',
      phoneList: ['110', '119', '120', '12345'],
      telephone: '110',
      fileIds: [],
    };
  },

  onLoad(options) {
    this.userInfo = uni.getStorageSync('userInfo') || {};
    const globalData = getApp().globalData;
		this.doorId = globalData.doorInfo.baseInfo.doorplateCode;
    this.getDictionaryByName();
		recorderManager.onStart(() => {
			console.log('recorder start');
		});
		recorderManager.onStop((res) => {
			console.log('recorder stop' + JSON.stringify(res));
			const fileInfo = {
				fileType: 'audio', 
				size: res.fileSize,
				duration: res.duration,
				tempFilePath: res.tempFilePath, 
				thumbTempFilePath: '/static/images/upload/type_audio.png'
			}
			uploadFile(fileInfo).then(res => {
				const fileName = '声音.aac';
				fileInfo.fileId = { type: fileInfo.fileType, name: fileName, fileId: res.data };
				this.$refs.files.fileList.push(fileInfo);
			})
		});
  },

  methods: {
    /* 切换标签页 */
    changeTab (event) {
      this.callType = event.value + 1;
    },
    
    /* 跳转到反映记录页面 */
    alarmRecord() {
      uni.navigateTo({
        url: `/subPages/pages/alarm/alarmRecord`
      });
    },

		/* 查询反映类型字典 */
		getDictionaryByName () {
			getDictionaryByName({ dicName: 'callPoliceType' }).then(res => {
				res.data.forEach(item => {
					this.alarmTypeOptions.push({value: item.code, text: item.name});
				})
			})
		},

    /* 保存反映信息 */
    saveAlarm () {
      const userInfo = uni.getStorageSync('userInfo');
      if (this.$refs.files) {
        const fileList = this.$refs.files.fileList;
        fileList.forEach(item =>{
          this.fileIds.push(item.fileId)
        })
      }
			const data = {
				callType: this.callType,
				telephone: this.telephone,
				context: this.message || '发起反映',
				placeId: this.doorId,
				fileId: this.fileIds.length===0 ? '' : JSON.stringify(this.fileIds),
				createUserId: this.userInfo.uuid,
				createUserName: userInfo.nickName,
        phone: userInfo.phoneNumber
			}
			saveAlarm(data).then(res => {
				if (res.code === 0) {
					this.message = '';
					this.fileList = [];
					this.telephone = '110';
          if (this.$refs.files) {
            this.$refs.files.fileList = [];
          }
          if (this.callType === 2) {
            uni.showToast({title: '发起反映成功',icon: 'success'});
          }
				}
			});
    },


    /* 拨打反映电话 */
    callPhone(phoneNumber) {
      var that = this;
      uni.getSystemInfo({
        success: function (res) {
          if (res.platform == 'ios') {
            uni.makePhoneCall({
              phoneNumber: phoneNumber,
              success: function () {
                that.telephone = phoneNumber;
                that.saveAlarm();
              },
              fail: function () {}
            });
          } else if (res.platform == 'android' || res.platform == 'devtools') {
            uni.showModal({
              title: '提示',
              content: `确定拨打${phoneNumber}电话吗？`,
              success(res) {
                if (res.confirm) {
                  uni.makePhoneCall({
                    phoneNumber: phoneNumber,
                    success: function () {
                      that.telephone = phoneNumber;
                      that.saveAlarm();
                    },
                    fail: function () {}
                  });
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        },
        fail: function () {
          uni.showToast({ title: '拨打电话失败', icon: 'fail'});
        }
      });
    },

		/* 求助内容改变  */
		changeMessage (event) {
			this.message = event.detail.value;
		},

    /* 改变反映途径 */
    changeAlarWay(phoneNumber) {
      this.telephone = phoneNumber;
    },

    /* 上传文件 */
		uploadFile () {
			const fileList = this.$refs.files.fileList;
			if (fileList.length > 0) {
				fileList.forEach(item => {
					uploadFile(item).then(res => {
						const fileName = item.fileType === 'video' ? '视频.mp4' : '图片.png'
						console.log(res);
						this.fileIds.push({ type: item.fileType, name: fileName, fileId: res.data });
					});
				})
			}
		},

    /* 录音功能 */
    recordAudio() {
      if (!this.isRecordAudio) {
				this.audioIconUrl = '/subPages/static/images/common/voice-selected@2x.png';
				this.isRecordAudio = true;
				recorderManager.start();
      } else {
				recorderManager.stop();
				this.audioIconUrl = '/subPages/static/images/common/voice-unselected@2x.png';
				this.isRecordAudio = false;
      }
    },
  }
};
</script>

<style>
  @import './alarmCall.css';
</style>
