<template>
  <view>
    <Navbar :title="title" />
    <div class="content">
      <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="auto">
        <Title title="违章信息" />
        <u-form-item label="违章工程" prop="proName" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.proName"
              isLink
              :label="formData.proName ? '' : '请选择违章工程'"
              @click="handlePicker(1)"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="违章类型" prop="violationTypeName" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.violationTypeName"
              isLink
              :label="formData.violationTypeName ? '' : '请选择违章类型'"
              @click="handlePicker(2)"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="违章编号" prop="violationCode" v-if="opt.isDetail">
          <u-input v-model="formData.violationCode" placeholder="请输入违章编号" border="bottom" disabled></u-input>
        </u-form-item>
        <u-form-item label="责任承包商" prop="consName" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.consName"
              isLink
              :label="formData.consName ? '' : '请选择责任承包商'"
              @click="handlePicker(3)"
              :disabled="opt.isDetail ? true : formData.proName ? false : true"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="承包商负责人" prop="personName" required>
          <u-input v-model="formData.personName" placeholder="承包商负责人" border="bottom" disabled></u-input>
        </u-form-item>
        <u-form-item label="责任人" prop="directorName" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.directorName"
              isLink
              :label="formData.directorName ? '' : '请选择责任人'"
              @click="handlePicker(4)"
              :disabled="opt.isDetail ? true : formData.proName ? false : true"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="违章时间" prop="violationTime" required>
          <u-cell-group :border="false">
            <u-cell
              :title="formData.violationTime"
              isLink
              :label="formData.violationTime ? '' : '请选择违章时间'"
              @click="showPicker2 = true"
              :disabled="opt.isDetail"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="违章依据" prop="violationContent" required>
          <u-textarea
            v-model="formData.violationContent"
            placeholder="请输入违章依据"
            :rows="5"
            :disabled="opt.isDetail"
            @blur="filter"
            maxlength="1000"
            count
          ></u-textarea>
        </u-form-item>
        <u-form-item label="违章照片" prop="violationPhotoList" required>
          <uni-file-picker
            v-model="formData.violationPhotoList"
            :auto-upload="false"
            ref="files"
            limit="9"
            @select="selectImg"
            @delete="deleteImg"
            :disabled="opt.isDetail"
            :readonly="opt.isDetail ? true : false"
          />
        </u-form-item>
        <Title title="违章采集信息" v-if="opt.isDetail" />
        <u-form-item label="违章来源" prop="violationSource" v-if="opt.isDetail">
          <u-input v-model="formData.violationSource" placeholder="违章来源" border="bottom" disabled></u-input>
        </u-form-item>
        <u-form-item label="新增人员" prop="createUserName" v-if="opt.isDetail">
          <u-input v-model="formData.createUserName" placeholder="新增人员" border="bottom" disabled></u-input>
        </u-form-item>
        <u-form-item label="新增时间" prop="createTime" v-if="opt.isDetail">
          <u-input v-model="formData.createTime" placeholder="新增时间" border="bottom" disabled></u-input>
        </u-form-item>
      </u-form>

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

    <!-- 下拉 -->
    <div v-if="showPicker"></div>
    <u-picker
      v-if="showPicker"
      :show="showPicker"
      :columns="columns"
      keyName="label"
      @cancel="showPicker = false"
      @confirm="confirm1"
    ></u-picker>

    <!-- 时间日期 -->
    <u-datetime-picker
      :show="showPicker2"
      v-model="dataTime"
      mode="date"
      :min-date="minDate"
      :max-date="maxDate"
      @cancel="showPicker2 = false"
      @confirm="confirm2"
    ></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 { filterInput } from '@/utils/regular'
import config from '@/config'
import { encryptCBC, decryptCBC } from '@/utils/aescbc'
import {
  getProSelect,
  getTypeOfViolationSelect,
  getConsByProIdSelect,
  addViolation,
  uploadFileUrl,
  getPersonByConsIdSelect,
  getViolationDetail
} from '@/api/hiddenDangerViolation'

export default {
  data() {
    return {
      isLoading: false,
      title: '新增违章',
      actionUrl: uploadFileUrl,
      token: '',
      opt: {},
      currentPicker: 1,
      showPicker: false,
      columns: [],
      showPicker2: false,
      dataTime: Number(new Date()),
      photoList: [],
      handlePhotoList: [],
      formData: {
        id: '', // 违章id
        proId: '', // 违章工程id
        proName: '', // 违章工程
        violationType: '', // 违章类型id
        violationTypeName: '', // 违章类型
        violationCode: '', // 违章编号
        consId: '', // 责任承包商id
        consName: '', // 责任承包商
        personId: '', // 承包商负责人id
        personName: '', // 承包商负责人
        directorId: '', // 责任人id
        directorName: '', // 责任人
        violationTime: '', // 违章时间
        violationContent: '', // 违章依据
        violationSource: '', // 违章来源
        createUserId: uni.getStorageSync('userInfo').userId, // 新增人员id
        createUserName: uni.getStorageSync('userInfo').nickName, // 新增人员
        createTime: '', // 新增时间
        supUuid: '', // 监理id
        violationPhotoList: [], // 违章照片
        fileId: [], // 删除的图片/附件id
        delIds: '' // 删除的图片/附件id 字符串
      },
      // 违章工程-下拉
      violationProOpts: [],
      // 违章类型-下拉
      violationTypeOpts: [],
      // 责任承包商-下拉
      subProOpts: [],
      // 责任人-下拉
      subUserOpts: [],
      rules: {
        proName: [{ required: true, message: '请选择违章工程', trigger: 'blur' }],
        violationTypeName: [{ required: true, message: '请选择违章类型', trigger: 'blur' }],
        consName: [{ required: true, message: '请选择责任承包商', trigger: 'blur' }],
        directorName: [{ required: true, message: '请选择责任人', trigger: 'blur' }],
        violationTime: [{ required: true, message: '请选择违章时间', trigger: 'blur' }],
        violationContent: [{ 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.title = this.opt.title
    this.token = uni.getStorageSync('App-Token')
    this.handleDataTime()
    this.getProSelect()
    this.getTroubleType()
    if (!this.opt.isAdd) {
      this.getConsByProIdSelect(this.opt.proId)
      this.getPersonByConsIdSelect({ consUuid: this.opt.consId, proId: this.opt.proId })
      this.getDetail()
    }
  },
  methods: {
    // 编辑/详情
    async getDetail() {
      try {
        this.formData.violationPhotoList = []
        const params = { violationId: this.opt.violationId }
        console.log('🚀 ~ getDetail ~ params:', params)
        const res = await getViolationDetail(params)
        console.log('🚀 ~ getDetail ~ res:', res)
        this.formData = { ...this.formData, ...res.data }
        this.formData.id = res.data.violationId
        this.formData.violationPhotoList = res.data.photoList
        this.formData.violationPhotoList.forEach(item => {
          item.url = item.filePath = config.fileUrl + item.filePath
          item.path = config.fileUrl + item.path
        })
      } catch (error) {
        console.log('🚀 ~ getDetail ~ error:', error)
      }
    },
    // 违章工程-下拉
    async getProSelect() {
      try {
        const res = await getProSelect()
        console.log('🚀 ~ 工程下拉 ~ res:', res)
        this.violationProOpts = res.data
      } catch (error) {
        console.log('获取工程-下拉失败', error)
      }
    },
    // 违章类别-下拉
    async getTroubleType() {
      try {
        const res = await getTypeOfViolationSelect({ type: '2' })
        this.violationTypeOpts = res.data
      } catch (error) {
        console.log('获取类别-下拉失败', error)
      }
    },
    // 获取整改责任承包商-下拉
    async getConsByProIdSelect(val) {
      try {
        // 清除 承包商责任人
        this.formData.subPersonName = ''
        const params = {
          proId: val
        }
        const res = await getConsByProIdSelect(params)
        console.log('🚀 ~ getConsByProIdSelect ~ res:', res)
        this.subProOpts = res.data
      } catch (error) {
        console.log('获取整改责任承包商-下拉失败', error)
      }
    },
    // 负责人-下拉
    async getPersonByConsIdSelect(params) {
      try {
        const res = await getPersonByConsIdSelect(params)
        console.log('🚀 ~ getPersonByConsIdSelect ~ res:', res)
        this.subUserOpts = res.data
      } catch (error) {
        console.log('获取负责人-下拉失败', error)
      }
    },
    // 过滤输入特殊字符
    filter() {
      this.violationContent = filterInput(this.violationContent)
    },
    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年前的时间戳
    },

    handlePicker(type) {
      this.columns = []
      this.currentPicker = type
      if (type === 1) {
        this.columns.push(this.violationProOpts)
      } else if (type === 2) {
        this.columns.push(this.violationTypeOpts)
      } else if (type === 3) {
        this.columns.push(this.subProOpts)
      } else if (type === 4) {
        this.columns.push(this.subUserOpts)
      }
      console.log('🚀 ~ handlePicker ~ this.columns:', this.columns)
      this.showPicker = true
    },
    confirm1(e) {
      console.log('🚀 ~ confirm1 ~ e:', e)
      if (this.currentPicker === 1) {
        this.formData.proName = e.value[0].label
        this.formData.proId = e.value[0].value
        this.formData.consId = ''
        this.formData.consName = ''
        this.formData.personId = ''
        this.formData.personName = ''
        this.formData.directorId = ''
        this.formData.directorName = ''
        this.getConsByProIdSelect(this.formData.proId)
      } else if (this.currentPicker === 2) {
        this.formData.violationTypeName = e.value[0].label
        this.formData.violationType = e.value[0].value
      } else if (this.currentPicker === 3) {
        this.formData.consName = e.value[0].label
        this.formData.consId = e.value[0].valueUuid
        this.formData.personId = e.value[0].userId
        this.formData.personName = e.value[0].name
        this.formData.supUuid = e.value[0].supUuid
        this.formData.directorId = ''
        this.formData.directorName = ''
        this.getPersonByConsIdSelect({ consUuid: this.formData.consId, proId: this.formData.proId })
      } else if (this.currentPicker === 4) {
        this.formData.directorId = e.value[0].value
        this.formData.directorName = e.value[0].label
      }
      this.showPicker = false
    },
    confirm2(e) {
      console.log('🚀 ~ confirm2 ~ e:', e)
      this.formData.violationTime = this.formatTimestamp(e.value)
      this.showPicker2 = 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')
      return `${year}-${month}-${day}`
    },
    selectImg(e) {
      console.log('🚀 ~ selectImg ~ e:', e)
      e.tempFiles.forEach(item => {
        this.formData.violationPhotoList.push(item)
      })
      console.log('🚀 ~ selectImg ~ this.formData.violationPhotoList:', this.formData.violationPhotoList)
    },
    upload(path) {
      uni.uploadFile({
        url: this.actionUrl,
        filePath: path,
        name: 'photoType',
        header: {
          Authorization: this.token,
          tokenType: 'APP'
        },
        success: res => {
          console.log('🚀 ~ res:', res)
          this.handlePhotoList.push(JSON.parse(res.data).data[0])
          console.log('🚀 ~ upload ~ this.photoType:', this.handlePhotoList)
        },
        fail: err => {
          console.log('🚀 ~ err:', err)
        }
      })
    },
    deleteImg(e) {
      console.log('🚀 ~ deleteImg ~ e:', e)
      // this.formData.violationPhotoList.splice(e.index, 1)
      this.formData.violationPhotoList.forEach((item, index) => {
        if (index == e.index) {
          if (item.fileId) {
            console.log('🚀 ~ deleteImg ~ item.fileId:', this.formData)
            this.formData.fileId.push(item.fileId)
          }
          this.formData.violationPhotoList.splice(index, 1)
        }
      })
      console.log('🚀 ~ deleteImg ~ this.formData.violationPhotoList:', this.formData.violationPhotoList)
    },
    async submitForm() {
      console.log('🚀 ~ submitForm ~ 点击:', this.formData)
      // 单独校验violationPhoto
      if (this.formData.violationPhotoList.length === 0) {
        uni.showToast({
          title: '请上传违章照片',
          icon: 'none',
          duration: 1500
        })
        return
      }
      this.$refs.uForm.validate().then(async valid => {
        this.isLoading = true
        this.handlePhotoList = []
        // 调用上传
        const uploadPromises = this.formData.violationPhotoList.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
          })
      })
    },
    // 提交
    async submit() {
      try {
        console.log('🚀 ~ submit ~ this.处理图片:', this.handlePhotoList)
        if (this.handlePhotoList.length > 0) {
          this.formData.violationPhotoList = this.handlePhotoList
        } else {
          this.formData.violationPhotoList = []
        }
        if (this.formData.fileId.length > 0) {
          this.formData.delIds = this.formData.fileId.join(',')
        }
        console.log('🚀 ~ 提交 ~ params.formData:', this.formData)
        const res = await addViolation(this.formData)
        console.log('🚀 ~ submit ~ res:', res)
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
          this.isLoading = false
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.log('🚀 ~ submit ~ error:', error)
        this.isLoading = false
      }
    }
  }
}
</script>

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