<!--
 * @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.pageType === '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.pageType === 'view'"
          />
        </u-form-item>
        <u-form-item label="照片" prop="photoType" required>
          <uni-file-picker
            v-model="photoType"
            :auto-upload="false"
            ref="files"
            limit="9"
            @select="selectImg"
            @delete="deleteImg"
            :readonly="opt.pageType === '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.pageType === 'edit' && opt.status === '已保存'"
        type="primary"
        shape="circle"
        @click="changeStatus(2)"
      >
        转违章
      </u-button>
      <u-button
        class="btn"
        v-if="opt.pageType === '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'] }]
        // photoType: [{ required: true, message: '请添加照片', trigger: ['blur', 'change'] }]
      },
      photoType: []
    }
  },
  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.pageType === 'edit' || this.opt.pageType === 'view') {
      this.formData = this.opt
      // this.formData.photoType = []
      this.photoType = JSON.parse(opt.params).photoList

      if (this.photoType.length > 0) {
        this.photoType.forEach(item => {
          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)
      // })

      this.upload(e.tempFiles[0].path)
    },
    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('上传成功-----', res)
          // console.log(decryptCBC(JSON.parse(res.data).data))

          const data = JSON.parse(res.data).data[0]

          console.log('data-----', data)
          // this.formData.photoType.push(JSON.parse(res.data).data[0])

          // console.log(this.formData.photoType, ' this.formData.photoType')
          this.photoType.push({
            ...data,
            url: config.fileUrl + data.filePath
          })
          this.formData.photoList.push({
            ...data,
            url: config.fileUrl + data.filePath
          })
          // console.log('🚀 ~ upload ~ this.formData.photoType:', this.formData.photoType)
        },
        fail: err => {
          console.log('🚀 ~ upload ~ err:', err)

          uni.showToast({
            title: '上传失败',
            icon: 'none',
            duration: 500
          })
        }
      })
    },
    deleteImg(e) {
      console.log(e, '删除----')
      // this.formData.photoType.splice(e.index, 1)
      // this.formData.photoType = this.formData.photoType.filter(item => item.uuid !== e.uuid)

      this.photoType = this.photoType.filter(item => item.filePath !== e.tempFile.filePath)
      this.formData.photoList = this.formData.photoList.filter(item => item.filePath !== e.tempFile.filePath)

      // console.log(this.formData.photoType, '删除----')
    },
    async submitForm() {
      if (!this.photoType.length) {
        uni.showToast({
          title: '请添加照片',
          icon: 'none',
          duration: 1500
        })
        return
      }
      this.isLoading = true
      this.$refs.uForm
        .validate()
        .then(async valid => {
          // this.formData.photoType = []
          this.submit()
          // 调用上传
          // 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.pageType === 'edit') {
          this.formData.id = this.opt.id
        }
        const params = JSON.parse(JSON.stringify(this.formData))
        params.photoType = params.photoList

        console.log('提交参数---', params)
        const res = await addSnapshotForm(params)
        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>
