<template>
  <super-dialog
    v-model="isShowDialog"
    :modal="false"
    :title="'添加处置环节'"
    top="6vh"
    v-bind="$attrs"
    width="60%"
    @closed="closed"
    @open="open"
  >
    <div class="process-dialog">
      <el-form
        ref="processInfo"
        :model="processInfo"
        :rules="processInfoRules"
        label-position="top"
        label-suffix="："
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="事件处置环节" prop="eventNode">
              <el-select
                v-model="processInfo.eventNode"
                placeholder="请选择处置环节"
                @change="handleNodeChange"
              >
                <el-option
                  v-for="item in getDictionaryByCode('sj_czlc')"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!--非完结处置环节-->
        <template v-if="processInfo.eventNode !== '9'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="事件处置时间" prop="handleTime">
                <el-date-picker
                  v-model="processInfo.handleTime"
                  default-time="12:00:00"
                  placeholder="选择处置时间"
                  style="width: 100%"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="事件处置情况" prop="handleInfo">
                <el-input
                  v-model="processInfo.handleInfo"
                  placeholder="请输入事件处置情况"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="事件位置" prop="handleLngLat">
                <el-input
                  ref="placeInput"
                  v-model="processInfo.handleLngLat"
                  placeholder="请输入事件处置情况"
                  @focus="handlePlaceSearch"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="handlePlaceSearch"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="事件处置图片" prop="files">
                <el-upload
                  ref="upload"
                  :accept="acceptTypes"
                  :action="actionUrl + '/file/v1/fileUpload'"
                  :before-remove="beforeRemove"
                  :before-upload="beforeUpload"
                  :data="{
                    file: JSON.stringify({storeType: 'minio'})
                  }"
                  :file-list="processInfo.files"
                  :headers="headers"
                  :multiple="false"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  list-type="picture-card"
                  name="files"
                >
                  <span style="font-size: 22px; color: #205e94"> + </span>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!--完结处置环节-->
        <template v-else>
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="事件完成时间" prop="recoverTime">
                <el-date-picker
                  v-model="processInfo.recoverTime"
                  default-time="12:00:00"
                  placeholder="选择事件完成时间"
                  style="width: 100%"
                  type="datetime"
                  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="12">
              <el-form-item label="执法人员" prop="enforcementUser">
                <el-input
                  v-model="processInfo.enforcementUser"
                  clearable
                  placeholder="请输入执法人员"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="执法时间" prop="enforcementTime">
                <el-date-picker
                  v-model="processInfo.enforcementTime"
                  default-time="12:00:00"
                  placeholder="选择执法时间"
                  style="width: 100%"
                  type="datetime"
                  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="12">
              <el-form-item label="发布内容" prop="submitContent">
                <el-input
                  v-model="processInfo.submitContent"
                  clearable
                  placeholder="请输入发布内容"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="发布区域" prop="submitArea">
                <el-input
                  v-model="processInfo.submitArea"
                  clearable
                  placeholder="请输入发布区域"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="汇报时间" prop="reportTime">
                <el-date-picker
                  v-model="processInfo.reportTime"
                  default-time="12:00:00"
                  placeholder="选择汇报时间"
                  style="width: 100%"
                  type="datetime"
                  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="12">
              <el-form-item label="汇报人" prop="reportUser">
                <el-input
                  v-model="processInfo.reportUser"
                  clearable
                  placeholder="请输入汇报人"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="接受人" prop="receiveUser">
                <el-input
                  v-model="processInfo.receiveUser"
                  clearable
                  placeholder="请输入接受人"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="简要经过" prop="elapse">
                <el-input
                  v-model="processInfo.elapse"
                  clearable
                  placeholder="请输入简要经过"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="管制措施" prop="controlMeasures">
                <el-input
                  v-model="processInfo.controlMeasures"
                  clearable
                  placeholder="请输入管制措施"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShowDialog = false">取 消</el-button>
      <el-button :loading="processLoading" type="primary" @click="handleSave"
      >确 定</el-button
      >
    </span>
    <MapLocationPickup
      :is-show.sync="mapDialogVisible"
      :locationList="locationList"
      title="事件处置环节位置拾取"
      @location="handleLocation"
    ></MapLocationPickup>
  </super-dialog>
</template>

<script>
import moment from 'moment'
import SuperDialog from '@/components/SuperDialog/index.vue'
import MapLocationPickup from '@/components/MapLocationPickup/index.vue'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {addEventStep} from '@/api/patrolAndRescue/commandDispatch/eventManagement'
import {mapState} from 'vuex'
import {saveList, tableDetail} from '@/api/patrolAndRescue/commandDispatch/eventManagement/eventEdit'

export default {
  name: 'DisposalProcess',
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    locationList: {
      type: Array,
      default: () => []
    },
    eventInfo: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    SuperDialog,
    MapLocationPickup
  },
  data() {
    return {
      processLoading: false,
      detailData: {}, // 完结节点事件数据
      processInfo: {
        eventNode: '1',
        handleTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        files: [],
        handleLngLat: '',
        enforcementTime: '',
        reportTime: moment().format('YYYY-MM-DD HH:mm:ss'), // 汇报时间
        recoverTime: '' // 事件完成时间
      },
      processInfoRules: {
        recoverTime: [
          {
            required: true,
            message: '事件完成时间不能为空',
            trigger: ['change', 'blur']
          }
        ]
        // eventNode: [
        //   {
        //     required: true,
        //     message: '处置环节不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // handleTime: [
        //   {
        //     required: true,
        //     message: '处置时间不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // handleInfo: [
        //   {
        //     required: true,
        //     message: '处置情况不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // handleLngLat: [
        //   {
        //     required: true,
        //     message: '事件位置不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // enforcementUser: [
        //   {required: true, message: '请输入执法人员', trigger: 'blur'}
        // ],
        // enforcementTime: [
        //   {required: true, message: '请选择执法时间', trigger: 'change'}
        // ],
        // submitContent: [
        //   {required: true, message: '请输入发布内容', trigger: 'blur'}
        // ],
        // submitArea: [
        //   {required: true, message: '请输入发布区域', trigger: 'blur'}
        // ],
        // reportTime: [
        //   {required: true, message: '请选择汇报时间', trigger: 'change'}
        // ],
        // reportUser: [
        //   {required: true, message: '请输入汇报人', trigger: 'blur'}
        // ],
        // receiveUser: [
        //   {required: true, message: '请输入接受人', trigger: 'blur'}
        // ],
        // elapse: [{required: true, message: '请输入简要经过', trigger: 'blur'}],
        // controlMeasures: [
        //   {required: true, message: '请输入管制措施', trigger: 'blur'}
        // ]
      },
      acceptTypes: 'image/jpeg, image/png, image/gif', // 允许上传的文件类型
      mapDialogVisible: 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}`
      })
    })
  },
  watch: {},
  monted() {
  },
  methods: {
    getDictionaryByCode,
    dictionaryEscape,
    // 打开弹层时触发
    open() {
      this.$nextTick(() => {
        this.$refs.processInfo.clearValidate()
      })
      if (this.eventInfo) {
        this.getDetail(this.eventInfo.id) // 调用接口获取详情数据
      }
    },
    // 获取详情数据
    async getDetail(id) {
      this.processLoading = true
      try {
        this.detailData = await tableDetail(id)
        this.processLoading = false
        console.log(this.detailData)
      } catch (error) {
        this.processLoading = false
        console.error('获取事件详情失败：', error)
      }
    },
    handleLocation(location) {
      this.processInfo.handleLngLat = `${location.lng},${location.lat}`
      this.processInfo.handleLng = location.lng || ''
      this.processInfo.handleLat = location.lat || ''
    },

    // 位置选择弹层
    handlePlaceSearch() {
      this.mapDialogVisible = true
    },
    handleSave() {
      this.$refs.processInfo.validate(async valid => {
        if (valid) {
          this.processLoading = true
          let query, API
          if (this.processInfo.eventNode !== '9') {
            let {
              handleLngLat,
              enforcementTime,
              ...rest
            } = this.processInfo
            query = {
              eventId: this.eventInfo.id,
              ...rest
            }
            API = addEventStep
          } else {
            const {
              recoverTime,
              enforcementUser,
              enforcementTime,
              submitContent,
              submitArea,
              elapse,
              controlMeasures,
              reportTime,
              reportUser,
              receiveUser
            } = this.processInfo
            API = saveList
            query = {
              recoverTime,
              enforcementUser,
              enforcementTime,
              submitContent,
              submitArea,
              elapse,
              controlMeasures,
              reportTime,
              reportUser,
              receiveUser,
              ...this.detailData
            }
          }
          API(query)
            .then(res => {
              console.log(res)
              if (res.state) {
                this.processLoading = false
                this.isShowDialog = false
                this.$message.success('事件处置环节操作成功')
                this.$emit('update:isShow', false)
                this.$emit('updataHandles')
                // this.$refs.processInfo.clearValidate()
              }
            })
            .catch(err => {
              this.processLoading = false
              this.$message.error('事件处置环节操作失败')
            })
        }
      })
    },
    // 文件上传前
    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.processInfo.files.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.processInfo.files.findIndex(i => i.fileId === fileId)
      if (index !== -1) this.processInfo.files.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')
      }
    },
    // 关闭弹层触发
    closed() {
      const {orgData} = this
      // 重置data中的数据
      Object.assign(this.$data, this.$options.data.call(this), {orgData})
      // this.$refs.processInfo.clearValidate()
    },
    handleNodeChange() {
      this.$nextTick(() => {
        this.processInfo.recoverTime = ''
        this.$refs.processInfo.clearValidate()
      })
    }
  }
}
</script>

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

.process-dialog {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
