<template>
  <view>
    <view class="detail_container">
      <view class="content">
        <view class="report_box">
          <view class="report_one" @click="choice">
            <view class="report_left">
              <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_zhixing@2x.png" />
              <view class="one">{{ !showActive ? null : '上报类型' }}</view>
            </view>
            <view class="report_right">
              <template v-for="(item, index) in typeList">
                <view v-if="id === item.id" class="report_name" :key="item.id">{{ item.name }}</view>
              </template>
              <image mode="aspectFill" class="arrow_right" src="/static/icon/arrow_right@2x.png" />
            </view>
          </view>
        </view>

        <view class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_didian@2x.png" />
            <view class="one">{{ !showActive ? null : '拍摄地点' }}</view>
          </view>
          <view class="photo_list">
            <view v-if="address === '点击授权获取位置信息'" class="address" @click="getAddress">{{ !showActive ? null : address }}</view>
            <view v-else class="address2" @click="getAddress">{{ !showActive ? null : address }}</view>
            <view v-if="address === '点击授权获取位置信息'" class="address_tip">{{ !showActive ? null : '提示：请授权获取位置信息后上传照片或视频' }}</view>
          </view>
        </view>

        <view class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_zp@2x.png" />
            <view class="one">{{ !showActive ? null : '上传照片/视频' }}</view>
            <view class="tip">{{ !showActive ? null : '照片至少上传1张/视频20M以下' }}</view>
          </view>
          <view class="photo_list">
            <view class="photo_item" bindtap="preview" v-for="(item, index) in photoList" :key="item.id" @click="previewVideo(item, index)">
              <!-- <image mode="aspectFill" class="upload_img" src="{{item}}" /> -->
              <image mode="aspectFill" v-if="item.type === 'image'" :src="item.url" style="display: block; width: 168rpx; height: 168rpx; border-radius: 16rpx" />

              <view v-else class="play-wrapper">
                <video :id="`myVideo${index}`" class="upload_img" :src="item.url" />
                <image src="/static/icon/ic_sj_bf@2x.png" mode="aspectFill" class="play-icon" />
              </view>
              <!--              <video class="upload_img" v-else :src="item.url" :show-fullscreen-btn="false" :show-play-btn="false" :show-center-play-btn="false" />-->
              <!--              <image v-if="item.type === 'video'" src="/static/icon/ic_sj_bf@2x.png" mode="aspectFill" class="play-icon" />-->

              <image @click.native.stop="cancel(item, index)" mode="aspectFill" class="upload_del" src="/static/icon/ic_zp_del@2x.png" />
            </view>
            <view class="photo_upload" @click="upload">
              <image mode="aspectFill" class="upload_icon" src="/static/icon/upload_icon@2x.png" />
            </view>
          </view>
        </view>

        <view class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">{{ !showActive ? null : '上报标题' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="!showActive ? '' : '标题'" v-model="title" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ title.length }}/{{ maxWord }}</text>
              <image v-if="title !== '' && showDel" bindtap="delTitle" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />
            </view>
          </view>
        </view>

        <view class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">{{ !showActive ? null : '上报内容' }}</view>
          </view>
          <view class="photo_list2">
            <textarea v-model="content" :placeholder="!showActive ? '' : '具体描述（最少10个字）'" class="write_box" bindinput="content" />
          </view>
        </view>

        <!-- 实名上报 -->
        <view class="step_box" v-if="showActive">
          <view class="real">
            <view class="real-header">
              <image src="/static/icon/ic_smsb@2x.png" />
              <view>实名上报</view>
            </view>
            <view class="real-content">
              <view class="real-content-switch">
                <view class="title">是否选择实名上报？</view>
                <u-switch v-model="checked" active-color="#8176f9" inactive-color="#dedbfe" :size="22" />
              </view>
              <view class="real-content-point"> 注：实名上报不会展示实名在随手拍世界，仅供平台收集上报可信度。 </view>
              <template v-if="checked">
                <view class="real-content-input">
                  <view>{{ '真实姓名' }}</view>
                  <input v-model="realForm.name" type="text" placeholder="请填写真实姓名" placeholder-class="input-placeholder" />
                </view>
                <view class="real-content-input">
                  <view>{{ '电话号码' }}</view>
                  <input v-model="realForm.phone" type="text" placeholder="请填写电话号码" placeholder-class="input-placeholder" :maxlength="11" />
                </view>
                <view class="real-content-input">
                  <view>{{ '证件类型' }}</view>
                  <view @click="openSelectCertificateType">
                    <u-input
                      :value="realForm.certificateType"
                      type="text"
                      placeholder="请选择证件类型"
                      class="input"
                      placeholder-class="input-placeholder"
                      readonly
                      suffixIcon="arrow-right"
                    />
                  </view>
                </view>
                <view class="real-content-input">
                  <view>{{ '证件号码' }}</view>
                  <input v-model="realForm.certificateText" type="text" placeholder="请填写证件号码" placeholder-class="input-placeholder" :disabled="!realForm.certificateType" />
                </view>
              </template>
            </view>
          </view>
        </view>

        <view class="step_box">
          <button type="submit" @click="submitReview" class="btn">{{ !showActive ? null : '上报' }}</button>
        </view>
      </view>
      <!--      <van-action-sheet :show="show" :actions="typeList" bind:close="onClose" cancel-text="取消" bind:select="onSelect" />-->
      <u-action-sheet :actions="typeList" :show="show" cancelText="取消" safeAreaInsetBottom round="32rpx" @close="onActionSheetClose" @select="onActionSheetSelect" />
      <UploadActionSheet ref="uploadActionSheet" :success="onUpload" />
      <CertificateTypeActionSheet ref="certificateTypeActionSheet" :success="onCertificateTypeChange" />
    </view>
  </view>
</template>

<script>
import { typeList, week } from '@/pages/record-content/mock';
import UploadActionSheet from '@/pages/record-content/UploadActionSheet';
import CertificateTypeActionSheet from '@/pages/record-content/CertificateTypeActionSheet';

export default {
  components: { CertificateTypeActionSheet, UploadActionSheet },
  data() {
    return {
      query: {},
      list: [],

      week,
      typeList: [],
      type: '请选择上报类型',
      show: false,
      category: null,
      address: '点击授权获取位置信息',
      latitude: '',
      longitude: '',
      showDel: false,
      photoList: [],
      req: [],
      content: '',
      title: '',
      id: null,
      thisDay: '',
      currentWord: 0,
      maxWord: 20,
      weekday: '',
      checked: false,
      realForm: {
        name: '',
        phone: '',
        certificateType: '',
        certificateText: '',
      },
      // 上传照片或视频类型
      mediaType: ['image', 'video'],
      showActive: true,
    };
  },

  onLoad(query) {
    console.log(query);
    this.query = query;
    this.fetchPhotoTaskTypeData();
  },

  methods: {
    async fetchPhotoTaskTypeData() {
      const { list } = await uni.$u.http.get('/api/app/phototasktype/list', { params: { parent_id: this.query.parent_id } });
      this.typeList = list;
      this.id = +this.query.detail_id;
    },

    async choice() {
      this.show = !this.show;
    },

    /**
     * 选择上报类型关闭
     * @returns {Promise<void>}
     */
    async onActionSheetClose() {
      this.show = false;
    },

    /**
     * 选择上报类型回调
     * @returns {Promise<void>}
     */
    async onActionSheetSelect(item) {
      console.log('onActionSheetSelect', item);
      this.id = item.id;
    },

    /**
     * 获取地理位置
     * @returns {Promise<void>}
     */
    async getAddress() {
      // uni.openLocation({
      //   latitude: 0,
      //   longitude: 0,
      //   success: (result) => {
      //     console.log('success', result);
      //   },
      //   fail: (result) => {
      //     console.log('fail', result);
      //   },
      // });
      uni.getLocation({
        isHighAccuracy: true,
        success: (result) => {
          console.log('success', result);
        },
        fail: (result) => {
          console.log('fail', result);
        },
      });
    },

    /**
     * 打开选择 上传图片或视频 操作菜单
     * @returns {Promise<void>}
     */
    async upload() {
      if (this.address === '' || this.address === '点击授权获取位置信息') {
        // uni.showModal({
        //   title: '提示',
        //   content: '请获取拍摄地点后上传照片',
        //   showCancel: false,
        // });
        // return;
      }
      this.$refs.uploadActionSheet.show = true;
    },

    /**
     * 上传图片或视频
     * @param item
     * @returns {Promise<void>}
     */
    async onUpload(item) {
      const upLoad = async (file, type = 'image') => {
        const [_temp0, { data }] = await uni.request({ url: '/api/qiniu/token' });
        const [_temp1, { data: res }] = await uni.uploadFile({
          url: data.upload_url,
          formData: {
            token: data.upload_token,
            file,
          },
        });
        const { key } = JSON.parse(res);
        this.photoList.push({
          id: uni.$u.guid(),
          type,
          url: `${data.qn_domain}${key}`,
        });
        if (type === 'video') {
          this.photoList = this.photoList.map((value, index) => ({
            ...value,
            videoContext: uni.createVideoContext(`myVideo${index}`),
          }));
        }
      };

      switch (item.type) {
        case 'image':
          uni.chooseImage({
            success: (result) => {
              console.log(result);
              result.tempFiles.forEach((value) => {
                upLoad(value);
              });
            },
            fail: (result) => {
              console.log(result);
            },
          });
          break;
        case 'video':
          uni.chooseVideo({
            success: (result) => {
              console.log(result);
              upLoad(result.tempFile, 'video');
            },
            fail: (result) => {
              console.log(result);
            },
          });
          break;
      }
    },

    async openSelectCertificateType() {
      this.$refs.certificateTypeActionSheet.show = true;
    },

    async onCertificateTypeChange(item) {
      this.realForm.certificateType = item.name;
    },

    /**
     * 上报按钮
     * @returns {Promise<void>}
     */
    async submitReview() {
      const t = (text = '') => uni.$u.toast(text);
      if (!this.id) return t('请选择上报类型');
      if (!this.photoList.filter(({ type }) => type === 'image').length) return t('请上传图片');
      if (!this.title) return t('请输入标题');
      if (!this.content) return t('请输入内容');
      if (this.checked) {
        if (!this.realForm.name) return t('请输入真实姓名');
        if (!this.realForm.phone) return t('请输入电话号码');
        if (!this.realForm.certificateType) return t('请选择证件类型');
        if (!this.realForm.certificateText) return t('请输入证件号码');
      }

      await uni.$u.http.post('/api/photo_task/create', {
        title: this.title,
        type_id: this.id,
        image_list: this.photoList.filter(({ type }) => type === 'image').join(),
        video_list: this.photoList.filter(({ type }) => type === 'video').join(),
        content: this.content,
        is_real: this.checked,
        name: this.realForm.name,
        phone: this.realForm.phone,
        certificates: this.realForm.certificateType,
        card_number: this.realForm.certificateText,
      });
    },

    // 预览视频
    previewVideo(item, index) {
      if (item.type === 'video') {
        this.photoList.at(index).videoContext.requestFullScreen();
      }
      if (item.type === 'image') {
        uni.previewImage({
          urls: [item.url],
        });
      }
    },

    cancel(item, index) {
      this.photoList.splice(index, 1);
    },
  },
};
</script>

<style scoped lang="scss">
@import 'index.scss';
</style>
