<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"
          :rules="rules"
          label-width="100px"
          label-position="top"
          label-suffix="："
        >
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="视频点位" prop="id">
                <el-select
                  v-model="addEditForm.id"
                  style="width: 100%"
                  placeholder="视频点位"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in videoList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="异常发生时间" prop="abnormalTime">
                <el-date-picker
                  style="width: 100%"
                  v-model="addEditForm.abnormalTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  default-time="12:00:00"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="异常描述" prop="inspectInfo">
                <el-input
                  type="textarea"
                  v-model="addEditForm.inspectInfo"
                  :autosize="{minRows: 4, maxRows: 10}"
                  placeholder="请输入内容"
                >
                </el-input>
              </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'}),
                  }"
                  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>
          <el-button
            :loading="saveLoading"
            size="small"
            type="primary"
            @click="handleReport"
          >
            事件上报
          </el-button>
        </div>
      </div>
    </div>

    <!--  所在路段选择弹层  -->
    <RoadChoiceDialog
      :is-show.sync="roadChoiceDialog"
      :selected-content.sync="addEditForm.road"
      @confirm="handleRoadSelect"
    />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import RoadChoiceDialog from '../RoadChoiceDialog/index'
import {getDictionaryByCode} from '@/utils/dictionary'
import {uploadErrVideo} 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,
    },
    videoList: {
      default: () => [],
      type: Array,
    },
  },
  components: {
    SuperDialog,
    RoadChoiceDialog,
  },
  data() {
    return {
      addEditForm: {
        id: '',
        inspectInfo: '',
        fileList: [],
        abnormalTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      },
      acceptTypes: 'image/jpeg, image/png, image/gif', // 允许上传的文件类型
      rules: {
        id: [
          {
            required: true,
            message: '视频点位不能为空',
            trigger: ['change', 'blur'],
          },
        ],
        fileList: [
          {
            required: true,
            message: '请上传异常图片',
            trigger: [, 'blur', 'change'],
          },
        ],
        inspectInfo: [
          {
            required: true,
            message: '异常描述不能为空',
            trigger: ['change'],
          },
        ],
        abnormalTime: [
          {
            required: true,
            message: '异常发生时间不能为空',
            trigger: ['change'],
          },
        ],
      },
      roadChoiceDialog: false,
      saveLoading: false,
    }
  },
  computed: {
    isShowDialog: {
      get() {
        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
    },

    handleRoadSelect(road) {
      this.$set(this.addEditForm, 'roadId', road.roadId)
    },

    // 文件上传前
    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::-webkit-scrollbar-thumb,
::v-deep::-webkit-scrollbar {
    display: none;
}
</style>
