<!--
 * @Author: zhangtq 2452618307@qq.com
 * @Date: 2024-12-04 10:04:22
 * @LastEditors: zhangtq 2452618307@qq.com
 * @LastEditTime: 2024-12-16 10:51:11
 * @FilePath: pages/randomlySnapPicture/addSnapPhoto.vue
 * @Description: 这是默认设置,可以在设置》工具》File Description中进行配置
 -->
<template>
  <view>
    <Navbar title="随手拍" />
    <div class="content">
      <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="70px">
        <u-form-item label="工程名称" prop="proName" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.proName"
              isLink
              :label="formData.proName ? '' : '请选择工程名称'"
              @click="showPicker1 = true"
              :disabled="opt.type === 'view'"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="问题描述" prop="description" required>
          <u-textarea v-model="formData.description" clearable placeholder="请输入问题描述" @blur="filter"  :disabled="opt.type === 'view'"/>
        </u-form-item>
        <u-form-item label="照片" prop="photoList">
          <uni-file-picker
            v-model="formData.photoList"
            :auto-upload="false"
            ref="files"
            limit="9"
            @select="selectImg"
            @delete="deleteImg"
            :readonly="opt.type === 'view'"
          />
        </u-form-item>
      </u-form>
      <u-button class="btn" type="primary" shape="circle" v-if="opt.type !== 'view'" @click="submitForm">
        提交
      </u-button>
      <u-button class="btn" v-if="opt.type === 'edit' && opt.status === '已保存'" type="primary" shape="circle" @click="changeStatus(2)">
        转违章
      </u-button>
      <u-button class="btn" v-if="opt.type === 'edit' && opt.status === '已保存'" type="primary" shape="circle" @click="changeStatus(3)">
        转隐患
      </u-button>
    </div>

    <!-- 检查级别 -->
    <u-picker
      :show="showPicker1"
      :columns="proOptions"
      keyName="label"
      @cancel="showPicker1 = false"
      @confirm="confirm1"
    ></u-picker>
    <u-loading-page :loading="isLoading" icon-size="39" style="z-index: 99999"></u-loading-page>
  </view>
</template>

<script>
import config from '../../config'
import { getProOptions } from '../../api/project'
import { filterInput } from '../../utils/regular'
import { addSnapshotForm, updateSnapshotStatus } from '../../api/snapshot'
import UniFilePicker from '../../uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker.vue'
import { encryptCBC, decryptCBC } from '../../utils/aescbc'
export default {
  components: { UniFilePicker },
  data() {
    return {
      isLoading: false,
      actionUrl: config.baseUrl + '/app/videoSurveillance/singleUploadFile',
      token: '',
      opt: {},
      showPicker1: false,
      formData: {
        proName: '', // 工程名称
        proId: '', // 工程id
        description: '', // 检查级别-显示
        photoList: [], // 照片
        photoType: [] // 照片-上传
      },
      // 工程-下拉
      proOptions: [],
      rules: {
        proName: { required: true, message: '请输入检查标题', trigger: ['blur'] },
        description: [{ required: true, message: '请输入问题描述', trigger: ['blur', 'change'] }],
      },
    }
  },
  onLoad(opt) {
    this.opt = JSON.parse(opt.params)
    console.log('🚀 ~ onLoad ~ this.opt:', this.opt)
    this.token = uni.getStorageSync('App-Token')
    this.getProOptions()
    if (this.opt.type === 'edit' || this.opt.type === 'view') {
      this.formData = this.opt
      this.formData.photoList.forEach(item => {
        item.filePath = item.url = config.fileUrl + item.filePath
      })
    }
  },
  methods: {
    filter() {
      this.formData.description = filterInput(this.formData.description)
    },
    async getProOptions() {
      try {
        const params = {}
        const res = await getProOptions(params)
        console.log('🚀 ~ 工程下拉 ~ res:', res)
        this.proOptions = [res.data]
      } catch (error) {
        console.log('获取工程-下拉失败', error)
      }
    },
    confirm1(e) {
      console.log('🚀 ~ confirm1 ~ e:', e)
      this.formData.proId = e.value[0].value
      this.formData.proName = e.value[0].label
      this.showPicker1 = false
    },
    selectImg(e) {
      console.log('🚀 ~ selectImg ~ e:', e)
      e.tempFiles.forEach(item => {
        this.formData.photoList.push(item)
      })
    },
    upload(path) {
      console.log('🚀 ~ upload ~ path:', path)
      console.log('🚀 ~ upload ~ actionUrl:', this.actionUrl)
      console.log('🚀 ~ upload ~ token:', this.token)
      uni.uploadFile({
        url: this.actionUrl,
        filePath: path,
        name: 'photoType',
        header: {
          Authorization: this.token,
          tokenType: 'APP'
        },
        success: res => {
          console.log('🚀 ~ upload ~ res:', res)
          console.log(decryptCBC(JSON.parse(res.data).data))
          this.formData.photoType.push(JSON.parse(res.data).data[0])
          console.log('🚀 ~ upload ~ this.formData.photoType:', this.formData.photoType)
        },
        fail: err => {
          console.log('🚀 ~ upload ~ err:', err)
        }
      })
    },
    deleteImg(e) {
      this.formData.photoList.splice(e.index, 1)
    },
    async submitForm() {
      if (!this.formData.photoList.length) {
        uni.showToast({
          title: '请添加照片',
          icon: 'none',
          duration: 1500
        })
        return
      }
      this.isLoading = true
      this.$refs.uForm
        .validate()
        .then(async valid => {
          this.formData.photoType = []
          // 调用上传
          const uploadPromises = this.formData.photoList.map(item => {
            console.log('🚀 ~ submitForm ~ item:', item)
            if (item.uuid) {
              return this.upload(item.path)
            }
            return Promise.resolve()
          })

          Promise.all(uploadPromises)
            .then(() => {
              // 所有上传操作完成后再提交
              setTimeout(() => {
                this.submit()
              }, 800)
            })
            .catch(error => {
              // 处理上传失败的情况
              console.error('上传失败', error)
              this.isLoading = false
              this.formData.photoType = []
            })
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    // 提交
    async submit() {
      console.log('🚀 ~ submit ~ this.formData:', this.formData)
      try {
        if (this.opt.type === 'edit') {
          this.formData.id = this.opt.id
        }
        const res = await addSnapshotForm(this.formData)
        console.log('🚀 ~ submit ~ res:', res)
        this.isLoading = false
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500
        })
        uni.navigateBack()
      } catch (error) {
        console.log('🚀 ~ submit ~ error:', error)
        this.isLoading = false
      }
    },
    changeStatus(type) {
      let code = type === 2 ? '违章' : '隐患'
      const res = updateSnapshotStatus({ snapshotId: this.opt.snapshotId, status: type })
      uni.showToast({
        title: '转' + code +  '成功',
        icon: 'success',
        duration: 1500
      })
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.content {
  padding: 0 20px;
  .btn {
    margin-top: 20px;
  }
}
</style>
