<template>
  <view>
    <view class="detail_container">
      <view v-if="IllegalShow" class="content">
        <!--        违法时间-->
        <view class="step_box" style="margin-top: 0;">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">{{ '违法时间' }}</view>
          </view>
          <view class="report_title">
            <input
              :maxlength="20"
              :placeholder="'违法时间'"
              :value="$u.timeFormat(IllegalForm.illegal_time, 'yyyy-mm-dd hh:MM:ss')"
              readonly
              disabled
              class="title_input"
              @click="showIllegalTime = true"
            />
            <!--            <view class="clear">-->
            <!--              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.illegal_time.length }}/{{ maxWord }}</text>-->
            <!--              <image v-if="IllegalForm.illegal_time" @click="IllegalForm.illegal_time = ''" 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_didian@2x.png" />
            <view class="one">{{ activeMap.address }}</view>
          </view>
          <view class="photo_list">
            <view v-if="address === '点击授权获取位置信息'" class="address" @click="getAddress">{{ address }}</view>
            <view v-else class="address2" @click="getAddress">{{ address }}</view>
            <view v-if="address === '点击授权获取位置信息'" class="address_tip">{{ !showActive ? null : `提示：请授权获取位置信息后${uploadTitle}` }}</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">{{ '号牌种类' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'号牌种类'" v-model="IllegalForm.number_plate" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.number_plate.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.number_plate" @click="IllegalForm.number_plate = ''" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />
            </view>
          </view>
        </view>
        -->

        <view class="report_box" style="margin-top: 50rpx;">
          <view class="report_one" @click="selectNumberPlatesShow = true">
            <view class="report_left">
              <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_zhixing@2x.png" />
              <view class="one">号牌种类</view>
            </view>
            <view class="report_right">
              <view class="report_name">{{ numberPlateText }}</view>
              <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_neirong@2x.png" />
            <view class="one">{{ '号牌号码' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'号牌号码'" v-model="IllegalForm.license_plate" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.license_plate.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.license_plate" @click="IllegalForm.license_plate = ''" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />
            </view>
          </view>
        </view>

        <!--        上报类型-->
        <view class="report_box" style="margin-top: 52rpx;">
          <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">{{ '上报类型' }}</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 v-if="activeItem" class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">示例</view>
          </view>
          <view class="example">
            <u-parse :content="activeItem.desc" />
          </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">{{ '所属辖区' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'所属辖区'" v-model="IllegalForm.jurisdiction" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.jurisdiction.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.jurisdiction" @click="IllegalForm.jurisdiction = ''" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />
            </view>
          </view>
        </view>
        -->

        <!--        上传照片-->
        <view v-for="option of uploadActionsOptions" 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 : getUploadTitle(option) }}</view>
          </view>
          <view class="photo_wrapper">
            <view class="photo_list">
              <view class="photo_item" bindtap="preview" v-for="(item, index) in photoList.filter(v => v.type === option.type)" :key="item.id">
                <view v-if="item.status === 'loading'" class="photo_item--loading"> </view>
                <view v-else @click="previewVideo(item, index)">
                  <!-- <image mode="aspectFill" class="upload_img" src="{{item}}" /> -->
                  <image mode="aspectFill" v-if="item.type === 'image'" :src="getThumbnail(item.url)" style="display: block; width: 168rpx; height: 168rpx; border-radius: 16rpx" />

                  <view v-else class="play-wrapper">
                    <video :controls="video.fullscreen" :object-fit="videoFit" :id="`myVideo${index}`" class="upload_img" :src="item.url" @fullscreenchange="onVideoFullscreenChange" />
                    <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>
              <view v-if="getUploadVisible(option)" class="photo_upload" @click="upload(option)">
                <image mode="aspectFill" class="upload_icon" src="/static/icon/upload_icon@2x.png" />
              </view>
            </view>
            <!--
            <view class="tip">{{ '需反应车型、停车位置和环境参照物' }}</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">{{ '违法类型' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'违法类型'" v-model="IllegalForm.IllegalType" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.IllegalType.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.IllegalType" @click="IllegalForm.IllegalType = ''" 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">{{ '违法行为描述' }}</view>
          </view>
          <view class="photo_list2">
            <textarea v-model="IllegalForm.content" :placeholder="'具体描述（最少10个字）'" class="write_box" />
          </view>
        </view>

        <!--        实名上报-->
        <view class="step_box">
          <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-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="getCertificateType(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>
            </view>
          </view>
        </view>

        <view class="step_box">
          <button type="submit" @click="submitReview" class="btn">{{ '上报' }}</button>
        </view>
      </view>

      <view v-else 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 v-if="activeItem" class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">示例</view>
          </view>
          <view class="example">
            <u-parse :content="activeItem.desc" />
          </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 : activeMap.address }}</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 : `提示：请授权获取位置信息后${uploadTitle}` }}</view>
          </view>
        </view>

        <view v-for="option of uploadActionsOptions" 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 : getUploadTitle(option) }}</view>
          </view>
          <view class="photo_wrapper">
            <view class="photo_list">
              <view class="photo_item" bindtap="preview" v-for="(item, index) in photoList.filter(v => v.type === option.type)" :key="item.id">
                <view v-if="item.status === 'loading'" class="photo_item--loading"></view>
                <view v-else @click="previewVideo(item, index)">
                  <!-- <image mode="aspectFill" class="upload_img" src="{{item}}" /> -->
                  <image mode="aspectFill" v-if="item.type === 'image'" :src="getThumbnail(item.url)" style="display: block; width: 168rpx; height: 168rpx; border-radius: 16rpx" />

                  <view v-else class="play-wrapper">
                    <video :controls="video.fullscreen" :object-fit="videoFit" :id="`myVideo${index}`" class="upload_img" :src="item.url" @fullscreenchange="onVideoFullscreenChange" />
                    <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>
              <view v-if="getUploadVisible(option)" class="photo_upload" @click="upload(option)">
                <image mode="aspectFill" class="upload_icon" src="/static/icon/upload_icon@2x.png" />
              </view>
            </view>
            <!--
            <view class="tip">{{ '实例照片（带车牌照、有倾倒行为过程）实地照片、视频' }}</view>
            -->
          </view>
        </view>

        <!--        违法类型-->
        <!--
        <view v-if="isIncivility" class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">{{ '违法类型' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'违法类型'" v-model="IllegalForm.IllegalType" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.IllegalType.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.IllegalType" @click="IllegalForm.IllegalType = ''" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />
            </view>
          </view>
        </view>
        -->

        <!--        车牌号码-->
        <view v-if="isDispersion" class="step_box">
          <view class="tep_one">
            <image mode="aspectFill" class="tep_icon" src="/static/icon/ic_rw_neirong@2x.png" />
            <view class="one">{{ '涉事车牌号牌' }}</view>
          </view>
          <view class="report_title">
            <input :maxlength="20" :placeholder="'涉事车辆号牌'" v-model="IllegalForm.license_plate" class="title_input" />
            <view class="clear">
              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.license_plate.length }}/{{ maxWord }}</text>
              <image v-if="IllegalForm.license_plate" @click="IllegalForm.license_plate = ''" 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">{{ activeMap.time }}</view>
          </view>
          <view class="report_title">
            <input
              :maxlength="20"
              :placeholder="activeMap.time"
              :value="$u.timeFormat(IllegalForm.illegal_time, 'yyyy-mm-dd hh:MM:ss')"
              readonly
              disabled
              class="title_input"
              @click="isIncivility ? '' : showIllegalTime = true"
            />
            <!--            <view class="clear">-->
            <!--              <text style="float: right; font-size: 28rpx; font-weight: 400; color: #656565; margin-right: 5px">{{ IllegalForm.illegal_time.length }}/{{ maxWord }}</text>-->
            <!--              <image v-if="IllegalForm.illegal_time" @click="IllegalForm.illegal_time = ''" mode="aspectFill" class="tep_icon" src="/static/icon/ic_bt_del@2x.png" />-->
            <!--            </view>-->
          </view>
        </view>

        <!--
        <view v-if="!isIncivility" 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 : activeMap.content }}</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>{{ activeMap.realNameTitle }}</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="getCertificateType(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" :actionsOptions="uploadActionsOptions" :success="onUpload" />
      <CertificateTypeActionSheet ref="certificateTypeActionSheet" :success="onCertificateTypeChange" />
      <u-datetime-picker
        :show="showIllegalTime"
        v-model="IllegalForm.illegal_time"
        mode="datetime"
        closeOnClickOverlay
        @close="showIllegalTime = false"
        @cancel="showIllegalTime = false"
        @confirm="onIllegalTimeConfirm"
      />
      <u-action-sheet
        :actions="numberPlates"
        :show="selectNumberPlatesShow"
        cancelText="取消"
        safeAreaInsetBottom
        round="32rpx"
        @close="selectNumberPlatesShow = false"
        @select="onSelectNumberPlate"
        />
    </view>
  </view>
</template>

<script>
import { actionsOptions, week } from '@/pages/record-content/mock';
import UploadActionSheet from '@/pages/record-content/UploadActionSheet';
import CertificateTypeActionSheet from '@/pages/record-content/CertificateTypeActionSheet';
import { baseEncode, getImageInfo } from '@/utils/util';

const maxUploadVideoSizeM = 50 // M
const maxUploadVideoSize = maxUploadVideoSizeM * 1000 * 1000 // 单位 B，参考 macOS 用 1000 计算
let mustUploadImageCount = '-'

const typeMap = {
  illegality: '交通违法举报',
  incivility: '城市管理违法举报', // '城市不文明行为举报',
  fault: '交通设施故障上报',
  dispersion: '渣土运输车辆未覆盖或沿途泄露、抛撒'
}

const numberPlateMap = new Map([
  ['1', '大型汽车（黄底黑字）'],
  ['2', '小型汽车（蓝底白字）'],
  ['3', '大型新能源汽车（黄绿双拼色底黑字）'],
  ['4', '小型新能源汽车（渐变绿底黑字）'],
  ['5', '轻便摩托车（蓝底白字）'],
  ['6', '普通摩托车（黄底黑字）'],
  ['7', "电动自行车（绿牌白字）"],
])

const uploadSourceTypeMap = {
  1: ['camera', 'album'],
  2: ['camera'],
  3: ['album']
}

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,
      checked: true,
      realForm: {
        name: '',
        phone: '',
        certificateType: '',
        certificateText: '',
      },
      // 上传照片或视频类型
      // mediaType: ['image', 'video'],
      showActive: true,

      actionsOptions,

      showIllegalTime: false,
      IllegalShow: true,
      IllegalForm: {
        jurisdiction: '', // 所属辖区
        IllegalType: '', // 违法类型
        illegal_time: Number(new Date()), // 违法时间
        content: '', // 违法行为描述
        number_plate: '', // 号牌种类
        license_plate: '', // 车牌号码
      },
      selectNumberPlatesShow: false,
      numberPlateMap,
      numberPlates: [...numberPlateMap.entries()].map(([value, name]) => ({
        name,
        value
      })),

      mustUploadImageCount,
      map: {
        [typeMap.illegality]: {
           address: '违法地点',
        },
        [typeMap.incivility]: {
          realNameTitle: '举报人信息',
          content: '涉事行为描述',
          time: '涉事时间',
          address: '涉事地点',
        },
        [typeMap.fault]: {
          content: '申报行为描述',
          realNameTitle: '申报人信息',
          time: '申报时间',
          address: '拍摄地点',
        }
      },

      video: {
        ctx: null,
        fullscreen: false
      }
    };
  },

  computed: {
    activeItem() {
      return this.typeList.find(v => v.id === this.id)
    },
    activeParent() {
      return this.activeItem?.parent
    },
    activeMap() {
      return this.map[this.activeParent?.name] || {}
    },
    uploadedImages() {
      return this.photoList.filter(({ type }) => type === 'image')
    },
    isIllegality() {
      return this.activeParent?.name === typeMap.illegality
    },
    isIncivility() {
      return this.activeParent?.name === typeMap.incivility
    },
    isFault() {
      return this.activeParent?.name === typeMap.fault
    },
    isDispersion() {
      return this.activeItem.name === typeMap.dispersion
    },
    uploadActionsOptions() {
      const { activeItem = {} } = this
      const actionsOptions = [
        {
          name: '照片',
          type: 'image',
        },
        {
          name: '视频',
          type: 'video',
        }
      ]

      const res = []
      if (activeItem.upload_image === 1) {
        res.push(actionsOptions[0])
      }
      if (activeItem.upload_video === 1) {
        res.push(actionsOptions[1])
      }
      return res
    },
    isOnlyAllowUploadOneType() {
      return this.uploadActionsOptions.length === 1
    },
    isOnlyAllowUploadImages() {
      const { isOnlyAllowUploadOneType, uploadActionsOptions: options } = this
      return isOnlyAllowUploadOneType && options[0].type === 'image'
    },
    isAllowUploadImagesAndVideos() {
      return this.uploadActionsOptions.length === 2
    },
    isAllowUploadImages() {
      return this.isOnlyAllowUploadImages || this.isAllowUploadImagesAndVideos
    },
    uploadTitle() {
      return `上传${this.uploadActionsOptions.map(v => v.name).join('/')}`
    },
    videoFit() {
      return this.video.fullscreen ? 'contain' : 'cover'
    },
    numberPlateText() {
      const name = this.numberPlateMap.get(this.IllegalForm.number_plate)
	  console.log(name);
      return name && name.slice(0, name.indexOf('（')) || '请选择'
    }
  },

  watch: {
    activeItem(v) {
      this.mustUploadImageCount = mustUploadImageCount = v?.image_num
    }
  },

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

  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.IllegalShow = list.every(({ parent }) => parent.name === '交通违法举报');
      this.id = +this.query.detail_id;
    },

    async fetchUserInfo() {
      const {
        detail: {
          name,
          phone,
          certificates: certificateType,
          ID_number: certificateText
        }
      } = await uni.$u.http.get('/api/user_center/detail')

      this.realForm = {
        name,
        phone,
        certificateType,
        certificateText
      }
    },

    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;
    },

    onSelectNumberPlate({ value }) {
		console.log(value);
      this.IllegalForm.number_plate = value
    },

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

      uni.chooseLocation({
        success: (result) => {
          console.log(result);
          this.longitude = result.longitude;
          this.latitude = result.latitude;
          this.address = result.address;
        },
      });
    },

    /**
     * 打开选择 上传图片或视频 操作菜单
     * @returns {Promise<void>}
     */
    async upload(option) {
      if (this.address === '' || this.address === '点击授权获取位置信息') {
        uni.showModal({
          title: '提示',
          content: `请获取地点后上传${option.name}`,
          showCancel: false,
        });
        return;
      }
      this.onUpload(option)
      /* 上传类型分开后直接打开
      if (this.isOnlyAllowUploadOneType) {
        // 跳过选择上传照片还是视频
        this.onUpload(this.uploadActionsOptions[0])
        return
      }
      this.$refs.uploadActionSheet.show = true;
      */
    },

    /**
     * 上传图片或视频
     * @param item
     * @returns {Promise<void>}
     */
    async onUpload(item) {
      const upLoad = async (file, type = 'image', tempFilePath) => {
        const media = {
          id: uni.$u.guid(),
          type,
          url: '',
          status: 'loading',
        };
        this.photoList.push(media);
        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 { isIncivility, activeMap } = this

        const myAddress = `${isIncivility ? activeMap.address : '拍摄地点'}:  ${this.address}`;
        const myDay = `${isIncivility ? activeMap.time : '拍摄时间'}:  ${uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')}`;

        const { key } = JSON.parse(res);

        // 水印文字大小，单位: 缇，等于1/20磅，默认值是240缇，参考DPI为72。
        // 240 缇约等于 12px
        // 1px => 20 缇

        const isImage = type === 'image'
        const tPerPx = 20
        let scale = 1
        let imageWidth = 0
        if (isImage) {
          const { width, height } = await getImageInfo(tempFilePath)
          // 以宽度作参考
          const ref = width
          const phoneWidth = 375
          scale = ref / phoneWidth
          imageWidth = width
        }
        const getRealSize = value => ~~(value * scale) // 数值只支持整数
        // 参考文本
        const refText = myAddress
        const dx = getRealSize(15)
        const availableContentWidth = imageWidth - (dx * 2)
        const smallSizeChars = refText.match(/\w|\s/g)
        const realCharCount = refText.length - (smallSizeChars.length / 2)
        const availableFontSize = ~~(availableContentWidth / realCharCount * tPerPx)
        const normalFontSize = getRealSize(16 * tPerPx)
        const fontSize = Math.min(availableFontSize, normalFontSize)
        const timeDy = getRealSize(10)
        const addressLineHeight = 1.3
        const addressDy = ~~((timeDy + (fontSize / tPerPx)) * addressLineHeight)

        media.url =
          type === 'image'
            ? `${data.qn_domain}${key}?imageMogr/auto-orient|watermark/3/text/${baseEncode(myAddress)
                .replace(/\+/g, '-')
                .replace(/\//g, '_')}/font/5b6u6L2v6ZuF6buR/fontsize/${fontSize}/fill/I0ZGRkZGRg==/dissolve/100/gravity/SouthWest/dx/${dx}/dy/${addressDy}/text/${baseEncode(myDay)
                .replace(/\+/g, '-')
                .replace(/\//g, '_')}/font/5b6u6L2v6ZuF6buR/fontsize/${fontSize}/fill/I0ZGRkZGRg==/dissolve/100/gravity/SouthWest/dx/${dx}/dy/${timeDy}`
            : `${data.qn_domain}${key}`;
        media.status = 'finish';

        if (type === 'video') {
          this.photoList = this.photoList.map((value, index) => ({
            ...value,
            // videoContext: uni.createVideoContext(`myVideo${index}`),
          }));
        }
      };

      const { activeItem } = this

      switch (item.type) {
        case 'image':
          if (this.isAllowUploadImages && this.uploadedImages.length === mustUploadImageCount) {
            return uni.$u.toast(`照片只能上传 ${mustUploadImageCount} 张`)
          }
          uni.chooseImage({
            sourceType: uploadSourceTypeMap[activeItem.upload_mode],
            success: (result) => {
              result.tempFiles.forEach((value, index) => {
                upLoad(value, undefined, result.tempFilePaths[index]);
              });
            },
            fail: (result) => {
              console.log(result);
            },
          });
          break;
        case 'video':
          uni.chooseVideo({
            success: (result) => {
              const { size } = result
              if (size > maxUploadVideoSize) {
                uni.$u.toast(`上传的视频大小不能超过 ${maxUploadVideoSizeM}M`)
                return
              }
              upLoad(result.tempFile, 'video');
            },
            fail: (result) => {
              console.log(result);
            },
          });
          break;
      }
    },

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

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

    /**
     * 上报按钮
     * @returns {Promise<void>}
     */
    async submitReview() {
      const t = (text = '') => uni.$u.toast(text);
      const { activeMap, isIncivility, isFault, isDispersion } = this
      if (this.IllegalShow) {
        if (!this.IllegalForm.illegal_time) return t('请输入违法时间');
        if (!this.longitude) return t('请选择位置');
        if (!this.IllegalForm.number_plate) return t('请输入号牌种类');
        if (!this.IllegalForm.license_plate) return t('请输入号牌号码');
        // if (!this.IllegalForm.jurisdiction) return t('请输入所属辖区');
        // if (!this.IllegalForm.IllegalType) return t('请输入违法类型');
        if (!this.IllegalForm.content) return t('请输入违法行为描述');
        if (!this.photoList.length) return t(`请${this.uploadTitle}`);
        if (!this.realForm.name) return t('请输入真实姓名');
        if (!this.realForm.phone) return t('请输入电话号码');
        if (!this.realForm.certificateType) return t('请选择证件类型');
        if (!this.realForm.certificateText) return t('请输入证件号码');
      } else {
        if (!this.id) return t('请选择上报类型');
        if (!this.longitude) return t('请选择位置');
        if (!this.photoList.length) return t(`请${this.uploadTitle}`);
        if (!this.IllegalForm.illegal_time) return t(`请输入${activeMap.time}`);
        if (isIncivility) {
          // if (!this.IllegalForm.IllegalType) return t('请输入违法类型');
        }
        if (isDispersion) {
          if (!this.IllegalForm.license_plate) return t('请输入涉事车辆号牌');
        }
        // if (!this.title && !this.isIncivility) return t('请输入标题');
        if (!this.content) return t('请输入' + activeMap.content);
        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('请输入证件号码');
        }
      }

      try {
        const images = this.photoList.filter(({ type }) => type === 'image')
        if (this.isAllowUploadImages) {
          if (images.length !== mustUploadImageCount) {
            return t(`请上传 ${mustUploadImageCount} 张照片`)
          }
        }
        await uni.$u.http.post('/api/photo_task/create', {
          title: this.title,
          type_id: this.id,
          image_list: images
            .map(({ url }) => url)
            .join(),
          video_list: this.photoList
            .filter(({ type }) => type === 'video')
            .map(({ url }) => url)
            .join(),
          is_real: this.checked,
          name: this.realForm.name,
          phone: this.realForm.phone,
          certificates: this.realForm.certificateType,
          card_number: this.realForm.certificateText,
          longitude: this.longitude,
          latitude: this.latitude,
          position: this.address,

          ...this.IllegalForm,
          content: this.IllegalShow ? this.IllegalForm.content : this.content,
          illegal_time: uni.$u.timeFormat(this.IllegalForm.illegal_time, 'yyyy-mm-dd hh:MM'),
        });

        uni.$u.toast('上报成功');

        uni.$u.route({ url: 'pages/record-finish/index', type: 'redirectTo' });
      } finally {
      }
    },

    // 预览视频
    previewVideo(item, index) {
      if (item.type === 'video') {
        const ctx = this.video.ctx = uni.createVideoContext(`myVideo${index}`)
        ctx.play()
        // HACK: iOS 需要延迟一下才能全屏
        setTimeout(() => {
          ctx.requestFullScreen()
        }, uni.$u.os() === 'ios' ? 300 : 0)
      }
      if (item.type === 'image') {
        uni.previewImage({
          urls: [item.url],
        });
      }
    },

    cancel(item, index) {
      this.photoList.splice(this.photoList.indexOf(item), 1);
    },

    onIllegalTimeConfirm(value) {
      this.IllegalForm.illegal_time = value;
      this.showIllegalTime = false;
    },

    getCertificateType(value) {
      if (!value) return '';
      return this.actionsOptions.find(({ id }) => id === value).name;
    },

    getUploadTitle({ name, type }) {
      return `上传${name}${type === 'image' ? `（${mustUploadImageCount}张）` : ''}`
    },

    getThumbnail(url, width = 168, height = 168) {
      return `${url}|imageView2/1/w/${width}/h/${height}/interlace/1`
    },

    getUploadVisible({ type }) {
      // 视频目前不限上传数量
      if (type === 'video') return true
      return this.mustUploadImageCount > this.uploadedImages.length
    },

    onVideoFullscreenChange(e) {
      const { fullScreen } = e.detail
      this.video.fullscreen = fullScreen

      if (!fullScreen) {
        this.video.ctx.pause()
      }
    }
  },
};
</script>

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

.example {
  margin-top: 16rpx;
  font-size: 28rpx;
}

::v-deep .uni-video-container {
  // iOS 要在 video 父元素上设置才生效
  border-radius: 16rpx;
}

// HACK: 上面的 :controls="false" 不生效
::v-deep .uni-video-cover {
  display: none;
}

::v-deep .u-action-sheet__item-wrap {
  max-height: 80vh;
  overflow: auto;
}

.report_one {
  gap: 30rpx;
  align-items: flex-start;
}

.report_left {
  flex: 0 0 auto;
}

.report_right {
  text-align: justify;
}
</style>
