<template>
  <super-dialog
    v-bind="$attrs"
    v-model="isShowDialog"
    width="60%"
    :modal="false"
    top="6vh"
    @open="open"
    @closed="closed"
    :title="'添加处置环节'"
  >
    <div class="process-dialog">
      <el-form
        ref="processInfo"
        :model="processInfo"
        :rules="processInfoRules"
        label-width="100px"
        label-position="right"
        label-suffix="："
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="事件环节" prop="rescueNode">
              <el-select
                v-model="processInfo.rescueNode"
                placeholder="请选择处置环节"
                @change="handleNodeChange"
              >
                <el-option
                  v-for="item in getDictionaryByCode('jy_czlc')"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="处置时间" prop="handleTime">
              <el-date-picker
                style="width: 100%"
                v-model="processInfo.handleTime"
                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>
          <el-col :span="24">
            <el-form-item label="处置情况" prop="handleInfo">
              <el-input
                type="textarea"
                v-model="processInfo.handleInfo"
                placeholder="请输入事件处置情况"
              ></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"
                @focus="handlePlaceSearch"
                v-model="processInfo.handleLngLat"
                placeholder="请输入事件处置情况"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="handlePlaceSearch"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div
          class="rows"
          v-if="
            processInfo.rescueNode === '10' || processInfo.rescueNode === '100'
          "
        >
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">费用明细</div>
          </div>
        </div>
        <el-row
          :gutter="20"
          v-if="
            processInfo.rescueNode === '10' || processInfo.rescueNode === '100'
          "
        >
          <el-col :span="8">
            <el-form-item
              label="拖移里程"
              :prop="
                processInfo.rescueNode === '10' ? 'cost.trailingMileage' : ''
              "
            >
              <el-input
                type="number"
                v-model.number="processInfo.cost.trailingMileage"
                placeholder="请输入拖移里程"
              >
                <i slot="suffix" class="input-unit">KM</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="故障车型"
              :prop="processInfo.rescueNode === '10' ? 'cost.carType' : ''"
            >
              <el-select
                v-model="processInfo.cost.carType"
                placeholder="请选择派遣车型"
              >
                <el-option
                  v-for="item in getDictionaryByCode('gzcx')"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="支付方式"
              :prop="processInfo.rescueNode === '10' ? 'cost.payType' : ''"
            >
              <el-select
                v-model="processInfo.cost.payType"
                placeholder="请选择支付方式"
              >
                <el-option label="线下支付" value="1"></el-option>
                <el-option label="线上支付" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          :gutter="20"
          v-if="
            processInfo.rescueNode === '10' || processInfo.rescueNode === '100'
          "
        >
          <el-col :span="6">
            <el-form-item
              label="夜间作业"
              :prop="
                processInfo.rescueNode === '10' ? 'cost.nightHomeWork' : ''
              "
            >
              <el-switch
                v-model="processInfo.cost.nightHomeWork"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="危险货物"
              :prop="
                processInfo.rescueNode === '10' ? 'cost.dangerousGoods' : ''
              "
            >
              <el-switch
                v-model="processInfo.cost.dangerousGoods"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="隧道作业"
              :prop="processInfo.rescueNode === '10' ? 'cost.tunnelWork' : ''"
            >
              <el-switch
                v-model="processInfo.cost.tunnelWork"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="交通事故"
              :prop="
                processInfo.rescueNode === '10' ? 'cost.trafficAccident' : ''
              "
            >
              <el-switch
                v-model="processInfo.cost.trafficAccident"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item
              label="救援费用"
              :prop="processInfo.rescueNode === '10' ? 'cost.shouldMoney' : ''"
            >
              <el-input
                type="number"
                v-model.number="processInfo.cost.shouldMoney"
                placeholder="请输入救援费用"
              >
                <i slot="suffix" class="input-unit">元</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
              label="实收金额"
              :prop="processInfo.rescueNode === '10' ? 'cost.actualMoney' : ''"
            >
              <el-input
                type="number"
                v-model.number="processInfo.cost.actualMoney"
                placeholder="请输入实收金额"
              >
                <i slot="suffix" class="input-unit">元</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item
              label="票据号码"
              :prop="processInfo.rescueNode === '10' ? 'cost.invoiceNo' : ''"
            >
              <el-input
                v-model="processInfo.cost.invoiceNo"
                placeholder="请输入票据号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="费用备注" prop="remark">
              <el-input
                type="textarea"
                v-model="processInfo.cost.remark"
                placeholder="请输入费用备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="files">
              <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="processInfo.files"
                ref="upload"
              >
                <span style="font-size: 22px; color: #205e94"> + </span>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="isShowDialog = false">取 消</el-button>
      <el-button type="primary" :loading="processLoading" @click="handleSave"
        >确 定</el-button
      >
    </span>
    <MapLocationPickup
      title="事件处置环节位置拾取"
      :is-show.sync="mapDialogVisible"
      :locationList="locationList"
      @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/obstacleClearingRescue/rescueRegistration'
import {mapState} from 'vuex'
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,
      processInfo: {
        rescueNode: '1',
        handleTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        files: [],
        handleLngLat: '',
        cost: {}
      },
      processInfoRules: {
        rescueNode: [
          {
            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']
          }
        ],
        'cost.trailingMileage': [
          {
            required: true,
            message: '拖移里程不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.carType': [
          {
            required: true,
            message: '故障车型不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.nightHomeWork': [
          {
            required: true,
            message: '夜间作业不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.dangerousGoods': [
          {
            required: true,
            message: '危险货物不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.tunnelWork': [
          {
            required: true,
            message: '隧道作业不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.trafficAccident': [
          {
            required: true,
            message: '交通事故不能为空',
            trigger: ['change', 'blur']
          }
        ],
        'cost.payType': [
          {
            required: true,
            message: '支付方式不能为空',
            trigger: ['change', 'blur']
          }
        ]
      },
      acceptTypes: 'image/jpeg, image/png, image/gif', // 允许上传的文件类型
      mapDialogVisible: false, // 位置选择弹层
      carType: '' // 派遣车型
    }
  },
  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() {
      const carCode = this.eventInfo?.car?.dispatchCarType || ''
      this.carType = dictionaryEscape('jycl-cllx', carCode + '') || '-'
    },
    handleLocation(location) {
      this.processInfo.handleLngLat = `${location.lng},${location.lat}`
      this.processInfo.handleLng = location.lng || ''
      this.processInfo.handleLat = location.lat || ''
    },
    // handleNodeChange
    handleNodeChange(val) {
      this.$refs.processInfo.clearValidate()
      if (val === '10' || val === '100') {
        this.processInfo.cost = {
          trailingMileage: '',
          carType: '',
          nightHomeWork: 0,
          dangerousGoods: 0,
          tunnelWork: 0,
          trafficAccident: 0,
          shouldMoney: '',
          actualMoney: '',
          invoiceNo: '',
          remark: '',
          payType: '1',
          costTime: moment().format('YYYY-MM-DD HH:mm:ss'),
          costType: val === '10' ? '1' : '2'
        }
      } else {
        this.processInfo.cost = {}
      }
    },
    // 位置选择弹层
    handlePlaceSearch() {
      this.mapDialogVisible = true
    },
    handleSave() {
      this.$refs.processInfo.validate(valid => {
        if (valid) {
          this.processLoading = true
          const query = {...this.processInfo}
          query.rescueId = this.eventInfo.id
          delete query.handleLngLat
          addEventStep(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')
              }
            })
            .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})
    }
  }
}
</script>

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

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

.input-unit {
  font-size: 14px;
  color: #e4e4e4;
  margin: 0 5px;
  font-style: normal;
}

.rows {
  display: flex;
  align-items: center;
  border-bottom: 1px solid $--system-border-color2;
  margin-bottom: 16px;
  padding: 10px 0;

  .rows-left {
    margin-right: 10px;

    .rows-hr {
      width: 3px;
      height: 18px;
      background-color: $--system-border-color1;
      border-radius: 2px;
    }
  }

  .rows-title {
    .text-overflow {
      width: 100%;
      font-size: 16px;
      color: $--color-white;
    }
  }
}
</style>
