<template>
  <super-dialog
    v-bind="$attrs"
    v-model="isShowDialog"
    :width="width"
    :modal="false"
    :top="top"
    @closed="closed"
    :title="'视频巡检异常详情'"
  >
    <div class="eventInfo-dialog" :style="{height}">
      <div class="form-module">
        <el-form
          ref="eventInfo"
          :model="addEditForm"
          label-width="120px"
          label-position="right"
          label-suffix="："
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="视频名称">
                <span :title="addEditForm.videoName" class="text">
                  {{ addEditForm.videoName || '-' }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="异常发生时间" prop="abnormalTime">
                <span :title="addEditForm.abnormalTime" class="text">
                  {{ addEditForm.abnormalTime || '-' }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="异常描述" prop="inspectInfo">
                <span :title="addEditForm.inspectInfo" class="text">
                  {{ addEditForm.inspectInfo || '-' }}
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="异常图片" prop="fileList">
                <el-upload
                  :data="{
                    file: JSON.stringify({storeType: 'minio'}),
                  }"
                  disabled
                  name="files"
                  list-type="picture-card"
                  :action="actionUrl + '/file/v1/fileUpload'"
                  :accept="acceptTypes"
                  :before-upload="beforeUpload"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemove"
                  :multiple="false"
                  :headers="headers"
                  :file-list="addEditForm.fileList"
                  ref="upload"
                >
                  <span style="font-size: 22px; color: #205e94"> + </span>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="content-bottom">
          <el-button size="small" @click="closed"> 取 消 </el-button>
        </div>
      </div>
    </div>
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {getDictionaryByCode} from '@/utils/dictionary'
import {getVideoErrData} from '@/api/patrolAndRescue/videoPatrol/videoInspection'
import moment from 'moment'
import {mapState} from 'vuex'
export default {
  name: 'ReportDialog',
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean,
    },
    top: {
      default: '14vh',
      type: String,
    },
    width: {
      default: '60%',
      type: String,
    },
    height: {
      default: '65vh',
      type: String,
    },
    confirmCloseDialog: {
      default: true,
      type: Boolean,
    },
    videoData: {
      default: () => {},
      type: Object,
    },
  },
  components: {
    SuperDialog,
  },
  data() {
    return {
      addEditForm: {
        id: '',
        inspectInfo: '',
        fileList: [],
        abnormalTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      },
      acceptTypes: 'image/jpeg, image/png, image/gif', // 允许上传的文件类型
      roadChoiceDialog: false,
      saveLoading: false,
    }
  },
  computed: {
    isShowDialog: {
      get() {
        this.getData(this.isShow)
        return this.isShow
      },
      set(val) {
        this.$emit('update:isShow', val)
      },
    },
    actionUrl: (_) => window.context.portal,
    previewUrl: (_) =>
      window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
    downloadUrl: (_) => window.context.portal + '/file/v1/downloadFile?fileId=',
    ...mapState({
      headers: (state) => ({
        Authorization: `Bearer ${state.login.currentUser.token}`,
      }),
    }),
  },
  methods: {
    getDictionaryByCode,

    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },
    async getData(val) {
      if (val) {
        const {...item} = await getVideoErrData(this.videoData.id)
        this.addEditForm = {
          ...item,
        }
      }
    },

    // 文件上传前
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.warning('只能上传图片文件!')
        return false
      }
    },

    // 文化上传成功
    handleSuccess(response) {
      const {
        fileId = '',
        fileName = '',
        size: fileSizes = 0,
        success,
      } = response
      if (success) {
        this.addEditForm.fileList.push({fileId, fileSizes, fileName})
      } else {
        this.$message.error('文件上传失败')
      }
      this.saveLoading = false
    },

    // 文件上传失败
    handleError() {
      this.$message.warning('文件上传失败')
    },

    // 文件删除前
    beforeRemove(file) {
      return new Promise((resolve, reject) => {
        this.$confirm(`确定移除${file.name}吗？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then((_) => {
            resolve()
          })
          .catch((_) => reject())
      })
    },

    // 文件删除后
    handleRemove(file) {
      const fileId = file.fileId || file.response.fileId || ''
      const index = this.addEditForm.fileList.findIndex(
        (i) => i.fileId === fileId
      )
      if (index !== -1) this.addEditForm.fileList.splice(index, 1)
    },

    // 已上传文件点击
    async handlePreview(file) {
      const fileId = file.fileId || file.response.fileId || '' // 文件ID
      const fileName = file.name || file.fileName || '' // 文件名
      if (!(fileId && fileName))
        return this.$message.warning('文件错误，请删除后重新上传')
      const browserOperablePattern = /\.(jpg|jpeg|png|gif|bmp|webp|pdf)$/i
      if (browserOperablePattern.test(fileName)) {
        window.open(this.previewUrl + fileId, '_blank')
      } else {
        window.open(this.downloadUrl + fileId, '_blank')
      }
    },

    handleReport() {
      this.$refs.eventInfo.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true

          try {
            let {state, message, value} = await uploadErrVideo({
              ...this.addEditForm,
            })
            if (state) {
              this.$message.success(`上报成功`)
              this.saveLoading = false
              this.closed()
            } else {
              this.$message.success(message || '上报失败')
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },

    // 关闭弹层触发
    closed() {
      const {addEditForm} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {
        addEditForm,
      })
      this.$nextTick(() => {
        this.$refs.eventInfo?.clearValidate()
      })
      this.isShowDialog = false
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables';

.el-icon-plus {
    cursor: pointer;
    display: block;
    height: 100%;
    font-size: 16px !important;
    font-weight: 900;
    color: #43a1ff;
}

.eventInfo-dialog {
    width: 100%;
    display: flex;
    flex-direction: column;
    column-gap: 16px;
    min-height: 50vh;

    .form-module {
        width: 100%;
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        row-gap: 16px;
        background-color: $--system-module-color1;
        padding: 16px;
        box-sizing: border-box;
        border-radius: 8px;

        .el-form {
            height: calc(100% - 40px);
            overflow-y: scroll;
        }

        .content-bottom {
            display: flex;
            justify-content: flex-end;
            height: 40px;
        }
    }

    .stake-mark {
        ::v-deep .el-form-item__content {
            display: flex;
            justify-content: space-between;

            .pegVal-text2,
            .pegVal-text1 {
                padding-right: 10px;
                font-size: 16px;
                width: fit-content;
                color: #fff;
            }

            .pegVal-text2 {
                padding-left: 10px;
                font-size: 24px;
            }
        }
    }
    ::v-deep .el-form-item__content .text {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        -o-text-overflow: ellipsis;
        font-size: 0.72917vw;
        line-height: 1.25vw;
        color: #c3cad0;
        font-weight: 500;
    }
}

::v-deep::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
    display: none;
}
</style>
