<template>
  <view>
    <Navbar :title="opt.title" />
    <div class="content">
      <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="70px">
        <u-form-item label="检查标题" prop="title" required>
          <u-input
            v-model="formData.title"
            placeholder="请输入检查标题"
            border="bottom"
            clearable
            :disabled="opt.isDetail"
          ></u-input>
        </u-form-item>
        <u-form-item label="检查记录编号" prop="recordCode" labelWidth="100px" v-if="!opt.isAdd">
          <u-input v-model="formData.recordCode" placeholder="请输入检查记录编号" border="bottom" disabled></u-input>
        </u-form-item>
        <u-form-item label="检查级别" prop="inspectLevelLabel" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.inspectLevelLabel"
              isLink
              :label="formData.inspectLevelLabel ? '' : '请选择检查级别'"
              @click="showPicker1 = true"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="排查类型" prop="checkType" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.checkTypeLabel"
              isLink
              :label="formData.checkTypeLabel ? '' : '请选择排查类型'"
              @click="showPicker2 = true"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="检查时间" prop="checkTime" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.checkTime"
              isLink
              :label="formData.checkTime ? '' : '请选择检查时间'"
              @click="showPicker3 = true"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="照片" prop="photoList">
          <uni-file-picker
            v-model="photoList"
            :auto-upload="false"
            ref="files"
            limit="9"
            @select="selectImg"
            @delete="deleteImg"
            :disabled="opt.isDetail"
            :readonly="opt.isDetail ? true : false"
          />
        </u-form-item>
        <u-form-item label="附件" prop="attachmentList" v-if="opt.isDetail">
          <Preview :dataList="formData.attachmentList" />
        </u-form-item>
      </u-form>

      <u-button v-if="opt.isAdd || opt.isEdit" class="btn" type="primary" shape="circle" @click="submitForm">
        提交
      </u-button>
    </div>

    <!-- 检查级别 -->
    <u-picker
      :show="showPicker1"
      :columns="inspectLevelOpts"
      keyName="label"
      @cancel="showPicker1 = false"
      @confirm="confirm1"
    ></u-picker>
    <!-- 排查类型 -->
    <u-picker
      :show="showPicker2"
      :columns="checkTypeOpts"
      keyName="label"
      @cancel="showPicker2 = false"
      @confirm="confirm2"
    ></u-picker>
    <!-- 检查事件 -->
    <u-datetime-picker
      :show="showPicker3"
      v-model="dataTime"
      mode="datetime"
      :min-date="minDate"
      :max-date="maxDate"
      @cancel="showPicker3 = false"
      @confirm="confirm3"
    ></u-datetime-picker>
    <u-loading-page :loading="isLoading" icon-size="39" style="z-index: 99999"></u-loading-page>
  </view>
</template>

<script>
import { dictTableOption } from '@/api/tool/select'
import { addSecurityCheckRecord, getSecurityCheckRecordForm, uploadFileUrl } from '@/api/hiddenDangerViolation'
import { encryptCBC, decryptCBC } from '@/utils/aescbc'
import config from '@/config'

export default {
  data() {
    return {
      isLoading: false,
      actionUrl: uploadFileUrl,
      token: '',
      opt: {},
      showPicker1: false,
      showPicker2: false,
      showPicker3: false,
      dataTime: Number(new Date()),
      formData: {
        id: '',
        title: '', // 检查标题
        recordCode: '', // 检查记录编号
        inspectLevel: '', // 检查级别
        inspectLevelLabel: '', // 检查级别-显示
        checkType: '', // 排查类型
        checkTypeLabel: '', // 排查类型-显示
        checkTime: '', // 检查时间
        photoList: [], // 照片
        attachmentList: [], // 附件
        fileId: [], // 删除的图片/附件id
        photoType: [] // 图片
      },
      photoList: [], // 照片
      // 检查级别-下拉
      inspectLevelOpts: [],
      // 排查类型-下拉
      checkTypeOpts: [],
      rules: {
        title: { required: true, message: '请输入检查标题', trigger: ['blur'] },
        inspectLevelLabel: [{ required: true, message: '请选择检查级别', trigger: ['blur', 'change'] }],
        checkType: [{ required: true, message: '请选择排查类型', trigger: 'blur' }],
        checkTime: [{ required: true, message: '请选择检查时间', trigger: 'blur' }]
      },
      minDate: 0,
      maxDate: 0
    }
  },
  onLoad(opt) {
    this.opt = JSON.parse(opt.params)
    console.log('🚀 ~ onLoad ~ this.opt:', this.opt)
    this.token = uni.getStorageSync('App-Token')
    this.getCheckLevelType()
    this.handleDataTime()
    setTimeout(() => {
      if (this.opt.isEdit || this.opt.isDetail) {
        this.getFormData()
      }
    }, 200)
  },
  methods: {
    handleDataTime() {
      // minDate 今天往前10年, maxDate 为今天
      // 获取今天的日期
      let today = new Date()
      // 获取10年前的日期
      let tenYearsAgo = new Date()
      tenYearsAgo.setFullYear(today.getFullYear() - 10)
      // 获取今天和10年前日期的时间戳
      this.maxDate = today.getTime() // 当前时间戳
      this.minDate = tenYearsAgo.getTime() // 10年前的时间戳
    },
    async getCheckLevelType() {
      try {
        const params = {
          dictType: 'yh_inspect_level',
          dictValue: ''
        }
        const params2 = {
          dictType: 'yh_check_type',
          dictValue: ''
        }
        const res = await dictTableOption(params)
        console.log('🚀 ~ 检查级别 ~ res:', res)
        this.inspectLevelOpts = [res.data]
        const res2 = await dictTableOption(params2)
        console.log('🚀 ~ 排查类型 ~ res2:', res2)
        this.checkTypeOpts = [res2.data]
      } catch (error) {
        console.log('获取检查级别-下拉失败', error)
      }
    },
    // 详情/编辑-表单回显
    async getFormData() {
      try {
        const res = await getSecurityCheckRecordForm({ id: this.opt.id })
        console.log('🚀 ~ getFormData ~ res:', res)
        this.formData = { ...this.formData, ...res.data }
        // 根据 checkType 查询 checkTypeLabel
        const checkType = this.checkTypeOpts[0].find(item => item.value == this.formData.checkType)
        this.formData.checkTypeLabel = checkType.label
        // 根据 inspectLevel 查询 inspectLevelLabel
        const inspectLevel = this.inspectLevelOpts[0].find(item => item.value == this.formData.inspectLevel)
        this.formData.inspectLevelLabel = inspectLevel.label

        // 处理照片
        if (this.formData.photoList.length > 0) {
          this.formData.photoList.forEach(item => {
            item.filePath = config.fileUrl + item.filePath
            item.url = item.filePath
          })
        }
        this.photoList = this.formData.photoList

        // 处理附件
        if (this.formData.attachmentList.length > 0) {
          this.formData.attachmentList.forEach(item => {
            item.url = item.filePath
          })
        }
        console.log('🚀 ~ --> ~ this.formData:', this.formData)
      } catch (error) {
        console.log('🚀 ~ getFormData ~ error:', error)
      }
    },
    // 确认选择-检查级别
    confirm1(e) {
      console.log('🚀 ~ confirm1 ~ e:', e)
      this.formData.inspectLevel = e.value[0].value
      this.formData.inspectLevelLabel = e.value[0].label
      this.showPicker1 = false
    },
    // 确认选择-排查类型
    confirm2(e) {
      console.log('🚀 ~ confirm2 ~ e:', e)
      this.formData.checkType = e.value[0].value
      this.formData.checkTypeLabel = e.value[0].label
      this.showPicker2 = false
    },
    // 确认选择-检查时间
    confirm3(e) {
      console.log('🚀 ~ confirm3 ~ e:', e)
      this.formData.checkTime = this.formatTimestamp(e.value)
      this.showPicker3 = false
    },
    // 将时间戳转换为日期格式 yyyy-MM-dd
    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      const second = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    },
    selectImg(e) {
      console.log('🚀 ~ selectImg ~ e:', e)
      e.tempFiles.forEach(item => {
        this.formData.photoList.push(item)
      })
    },
    upload(path) {
      uni.uploadFile({
        url: this.actionUrl,
        filePath: path,
        name: 'photoType',
        header: {
          Authorization: this.token,
          tokenType: 'APP'
        },
        success: res => {
          console.log('🚀 ~ token--1:', this.token)
          console.log('🚀 ~ token--2:', uni.getStorageSync('App-Token'))
          console.log('🚀 ~ selectImg ~ res:', res)
          this.formData.photoType.push(JSON.parse(res.data).data[0])
          console.log('🚀 ~ upload ~ this.photoType:', this.formData.photoType)
        },
        fail: err => {
          console.log('🚀 ~ selectImg ~ err:', err)
        }
      })
    },
    deleteImg(e) {
      console.log('🚀 ~ deleteImg ~ e:', e)
      this.formData.photoList.forEach((item, index) => {
        if (index == e.index) {
          if (item.fileId) {
            this.formData.fileId.push(item.fileId)
          }
          this.formData.photoList.splice(index, 1)
        }
      })
      console.log('🚀 ~ deleteImg ~ this.formData:', this.formData)
    },
    async submitForm() {
      console.log('🚀 ~ submitForm ~ 点击:')
      console.log('🚀 ~ submitForm ~ this.formData:', this.formData)
      this.isLoading = true
      this.$refs.uForm
        .validate()
        .then(async valid => {
          console.log('🚀 ~ submitForm ~ this.formData:', this.formData)
          console.log('🚀 ~ submitForm ~ valid:', valid)
          // 调用上传
          const uploadPromises = this.formData.photoList.map(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
            })
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    // 提交
    async submit() {
      try {
        this.formData.photoList = this.formData.photoType
        this.formData.attachmentList = []
        console.log('🚀 ~ submit ~ this.formData:', this.formData)
        const res = await addSecurityCheckRecord(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
      }
    }
  }
}
</script>

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