<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="left"
        label-suffix="："
        label-width="140px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">处置信息</div>
          </div>
        </div>
        <el-row :gutter="24">
          <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 linkList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '3'" :gutter="24">
          <el-col :span="12">
            <el-form-item label="派遣人员" prop="person">
              <el-input
                v-model="processInfo.person"
                class="el-click-input"
                clearable
                placeholder="点击选择派遣人员"
                readonly
                suffix-icon="el-icon-search"
                @click.native="showDialog('userChoice')"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="派遣车辆" prop="dispatchCarCode">
              <el-input
                v-model="processInfo.dispatchCarCode"
                class="el-click-input"
                clearable
                placeholder="点击选择派遣车辆"
                readonly
                suffix-icon="el-icon-search"
                @click.native="showDialog('carChoice')"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item class="stake-mark" label="救援开始桩号" prop="startPeg">
              <div class="pegVal-text1">K</div>
              <el-input
                v-model="processInfo.startPeg"
                clearable
                oninput="value=value.replace(/[^0-9]/g,'')"
                type="text"
              ></el-input>
              <div class="pegVal-text2">+</div>
              <el-input
                v-model="processInfo.startPegAdd"
                clearable
                oninput="value=value.replace(/[^0-9]/g,'')"
                type="text"
              ></el-input>
            </el-form-item>
          </el-col>
          <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 v-if="processInfo.rescueNode !== '3' && processInfo.rescueNode !== '4'" :gutter="24">
          <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 v-if="processInfo.rescueNode !== '3' && processInfo.rescueNode !== '4'" :gutter="24">
          <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>
        <div v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">收费信息</div>
          </div>
        </div>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="12">
            <el-form-item label="协议单号" prop="agreementNo">
              <el-input
                v-model="processInfo.agreementNo"
                placeholder="请输入协议单号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拖移里程" prop="trailingMileage">
              <el-input
                v-model="processInfo.trailingMileage"
                placeholder="请输入拖移里程"
                type="number"
              ><i slot="suffix" class="input-unit">KM</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="12">
            <el-form-item label="应收金额" prop="shouldMoney">
              <el-input
                v-model.number="processInfo.shouldMoney"
                placeholder="请输入应收金额"
                type="number"
              >
                <i slot="suffix" class="input-unit">元</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实收金额" prop="actualMoney">
              <el-input
                v-model.number="processInfo.actualMoney"
                placeholder="请输入实收金额"
                type="number"
              >
                <i slot="suffix" class="input-unit">元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="6">
            <el-form-item label="夜间作业" prop="nightHomeWork">
              <el-switch
                v-model="processInfo.nightHomeWork"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="危险货物" prop="dangerousGoods">
              <el-switch
                v-model="processInfo.dangerousGoods"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="隧道作业" prop="tunnelWork">
              <el-switch
                v-model="processInfo.tunnelWork"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="交通事故" prop="trafficAccident">
              <el-switch
                v-model="processInfo.trafficAccident"
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="24">
            <el-form-item label="故障车型" prop="carType">
              <el-radio-group v-model="processInfo.carType" size="medium">
                <el-radio
                  v-for="(item, index) in getDictionaryByCode('gzcx')"
                  :key="index"
                  :label="Number(item.value)"
                  :value="Number(item.value)"
                >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="24">
            <el-form-item label="支付方式" prop="payType">
              <el-radio-group v-model="processInfo.payType" size="medium">
                <el-radio
                  v-for="(item, index) in payTypeList"
                  :key="index"
                  :label="item.value"
                  :value="item.value"
                  border
                >{{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processInfo.rescueNode === '10' || processInfo.rescueNode === '100'" :gutter="24">
          <el-col :span="24">
            <el-form-item label="票据号码" prop="invoiceNo">
              <el-input
                v-model="processInfo.invoiceNo"
                placeholder="请输入票据号码"
              />
            </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 :loading="processLoading" type="primary" @click="handleSave"
      >确 定</el-button
      >
    </span>
    <!-- 车辆选择 -->
    <CarChoiceDialog
      :carData="carData"
      :is-show.sync="carChoiceDialog"
      :selected-content.sync="processInfo.car"
      @confirm="handleCarSelect"
    />
    <!-- 人员选择 -->
    <UserChoiceDialog
      :is-show.sync="userChoiceDialog"
      :personOptions="personOptions"
      :selected-content.sync="processInfo.dispatches"
      @confirm="handleUserSelect"
    />
  </super-dialog>
</template>

<script>
import SuperDialog from '@/components/SuperDialog/index.vue'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {mapState} from 'vuex'
import {
  addEventStep,
  getDictionaryDetail,
  incidentHandling
} from '@/api/patrolAndRescue/obstacleClearingRescue/rescueRegistration'
import {personAndCarInfo} from '@/api/patrolAndRescue/commandDispatch/eventRegistration'
import CarChoiceDialog
  from '@/views/patrolAndRescue/obstacleClearingRescue/RescueRegistration/components/EditAddPage/components/AppointDialog/components/CarChoiceDialog/index.vue'
import UserChoiceDialog
  from '@/views/patrolAndRescue/obstacleClearingRescue/RescueRegistration/components/EditAddPage/components/AppointDialog/components/UserChoiceDialog/index.vue'

export default {
  name: 'DisposalProcess',
  inheritAttrs: false,
  props: {
    isShow: {
      default: false,
      type: Boolean
    },
    eventInfo: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    UserChoiceDialog, CarChoiceDialog,
    SuperDialog
  },
  data() {
    const validateRange1 = () => {
      return (rule, value, callback) => {
        if (this.processInfo.startPeg === undefined || this.processInfo.startPegAdd === undefined) {
          callback(new Error('请输入救援点位桩号全值'))
        } else {
          callback()
        }
      }
    }
    return {
      processLoading: false,
      processInfo: {
        rescueNode: '',
        person: '',
        dispatchCarCode: '',
        startPeg: undefined,
        startPegAdd: undefined,
        handleInfo: '',
        handleTime: '',
        files: [],
        car: {},
        dispatches: []
      },
      processInfoRules: {
        rescueNode: [
          {
            required: true,
            message: '事件处置环节不能为空',
            trigger: ['change', 'blur']
          }
        ],
        person: [
          {
            required: true,
            message: '派遣人员不能为空',
            trigger: ['change', 'blur']
          }
        ],
        dispatchCarCode: [
          {
            required: true,
            message: '派遣车辆不能为空',
            trigger: ['change', 'blur']
          }
        ],
        handleTime: [
          {
            required: true,
            message: '事件处置时间不能为空',
            trigger: ['change', 'blur']
          }
        ],
        startPeg: [
          {required: true, validator: validateRange1(), trigger: 'blur'}
        ],
        // handleInfo: [
        //   {
        //     required: true,
        //     message: '事件处置情况不能为空',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        payType: [
          {
            required: true,
            message: '支付方式不能为空',
            trigger: ['change', 'blur']
          }
        ],
        shouldMoney: [
          {
            required: true,
            message: '应收金额不能为空',
            trigger: ['change', 'blur']
          }
        ],
        actualMoney: [
          {
            required: true,
            message: '实收金额不能为空',
            trigger: ['change', 'blur']
          }
        ],
        trailingMileage: [
          {
            required: true,
            message: '拖移里程不能为空',
            trigger: ['change', 'blur']
          }
        ],
        carType: [
          {
            required: true,
            message: '故障车型不能为空',
            trigger: ['change', 'blur']
          }
        ],
        nightHomeWork: [
          {
            required: true,
            message: '夜间作业不能为空',
            trigger: ['change', 'blur']
          }
        ],
        dangerousGoods: [
          {
            required: true,
            message: '危险货物不能为空',
            trigger: ['change', 'blur']
          }
        ],
        tunnelWork: [
          {
            required: true,
            message: '隧道作业不能为空',
            trigger: ['change', 'blur']
          }
        ],
        trafficAccident: [
          {
            required: true,
            message: '交通事故不能为空',
            trigger: ['change', 'blur']
          }
        ]
      },
      acceptTypes: 'image/jpeg, image/png, image/gif', // 允许上传的文件类型
      mapDialogVisible: false,
      carChoiceDialog: false,
      userChoiceDialog: false,
      carData: [], // 车辆数据
      personOptions: [], // 人员数据
      payTypeList: [
        {
          name: '线下支付',
          value: 1
        },
        {
          name: '线上支付',
          value: 2
        }
      ],
      linkList: []
    }
  },
  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,
    dictionaryEscape,
    // 打开弹层时触发
    open() {
      console.log(this.eventInfo, '000')
      this.processLoading = true
      this.getLinkList()
      this.getDefaultValue()
      this.getPersonAndCarInfo(this.eventInfo.teamId)
      this.$nextTick(() => {
        this.$refs.processInfo.clearValidate()
      })
    },

    //默认回显数据
    getDefaultValue() {
      //桩号
      if (this.eventInfo.pegVal) {
        let startPegArr = this.eventInfo.pegVal.split('+')
        this.$set(this.processInfo, 'startPeg', startPegArr[0].slice(1))
        this.$set(this.processInfo, 'startPegAdd', startPegArr[1])
      } else {
        this.$set(this.processInfo, 'startPeg', undefined)
        this.$set(this.processInfo, 'startPegAdd', undefined)
      }
      //人员
      if (this.eventInfo.dispatches) {
        let dispatchArr = this.eventInfo.dispatches.map(item => {
          return {
            ...item,
            id: item.dispatchUserId,
            name: item.dispatchUserName
          }
        })
        this.$set(this.processInfo, 'dispatches', dispatchArr)
        this.$set(
          this.processInfo,
          'person',
          this.eventInfo.dispatches.map((item) => item.dispatchUserName).join(',')
        )
      } else {
        this.$set(this.processInfo, 'dispatches', [])
        this.$set(this.processInfo, 'person', '')
      }
      //车辆
      if (this.eventInfo.car) {
        this.$set(this.processInfo, 'car', this.eventInfo.car)
        this.$set(
          this.processInfo,
          'dispatchCarCode',
          this.eventInfo.car.dispatchCarCode
        )
      } else {
        this.$set(this.processInfo, 'car', {})
        this.$set(this.processInfo, 'dispatchCarCode', '')
      }
    },

    // 根据队伍id查询人员信息及车辆信息
    getPersonAndCarInfo(id) {
      personAndCarInfo(id).then((res) => {
        const {members = [], cars = []} = res.value
        this.personOptions = members.map((person) => {
          person.label = person.tel + ' ' + person.name
          return person
        })
        this.carData = cars
      })
    },

    //根据状态查询环节列表
    async getLinkList() {
      let query = {
        code: 'jy_splc',
        value: this.eventInfo.handles?.[0]?.rescueNode
      }
      const res = await getDictionaryDetail(query)
      this.linkList = res?.lowerDic?.jy_czlc || []
      this.linkList.length > 0 && (this.processInfo.rescueNode = this.linkList[0].value)
      this.processLoading = false
      this.$forceUpdate()
      console.log(this.processInfo.rescueNode, 'this.processInfo.rescueNode')
    },

    handleSave() {
      this.$refs.processInfo.validate(async valid => {
        if (valid) {
          this.processLoading = true
          let query = {
            id: this.eventInfo.id,
            car: this.processInfo.car,
            dispatches: this.processInfo.dispatches.map(item => {
              delete item.id
              delete item.name
              return item
            }),
            handle: {
              ...this.processInfo,
              cost: {
                agreementNo: this.processInfo.agreementNo,
                trailingMileage: this.processInfo.trailingMileage,
                shouldMoney: this.processInfo.shouldMoney,
                actualMoney: this.processInfo.actualMoney,
                nightHomeWork: this.processInfo.nightHomeWork,
                dangerousGoods: this.processInfo.dangerousGoods,
                tunnelWork: this.processInfo.tunnelWork,
                trafficAccident: this.processInfo.trafficAccident,
                carType: this.processInfo.carType,
                payType: this.processInfo.payType,
                invoiceNo: this.processInfo.invoiceNo
              }
            }
          }
          let queryDefault = {
            rescueId: this.eventInfo.id,
            cost: {
              agreementNo: this.processInfo.agreementNo,
              trailingMileage: this.processInfo.trailingMileage,
              shouldMoney: this.processInfo.shouldMoney,
              actualMoney: this.processInfo.actualMoney,
              nightHomeWork: this.processInfo.nightHomeWork,
              dangerousGoods: this.processInfo.dangerousGoods,
              tunnelWork: this.processInfo.tunnelWork,
              trafficAccident: this.processInfo.trafficAccident,
              carType: this.processInfo.carType,
              payType: this.processInfo.payType,
              invoiceNo: this.processInfo.invoiceNo
            },
            ...this.processInfo
          }
          console.log(query, 'query')
          const {state} = this.processInfo.rescueNode === '3' ? await incidentHandling(query) : await addEventStep(queryDefault)
          if (state) {
            this.processLoading = false
            this.isShowDialog = false
            this.$message.success('事件处置环节操作成功')
            this.$emit('update:isShow', false)
            this.$emit('updataHandles')
          } else {
            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(`确定移除吗？`, '提示', {
          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})
    },
    handleNodeChange() {
      this.$nextTick(() => {
        this.$refs.processInfo.clearValidate()
      })
    },
    // 展示弹层
    showDialog(dialogName) {
      if (!dialogName) return
      this[dialogName + 'Dialog'] = true
    },
    handleCarSelect(car) {
      console.log('handleCarSelect', car)
      this.processInfo.car = {
        dispatchCarCode: car.carNumber,
        dispatchCarType: car.carClass
      }
      this.processInfo.dispatchCarCode = car.carNumber
      this.processInfo.dispatchCarType = car.carClass
    },
    handleUserSelect(user) {
      if (user.length > 0) {
        this.processInfo.dispatches = user.map(item => {
          return {
            dispatchUserId: item.id,
            dispatchUserName: item.name,
            dispatchUserTel: item.tel,
            name: item.name,
            id: item.id
          }
        })
        this.processInfo.person = user.map(item => item.name).join(',')
      }
      console.log('handleUserSelect', user)
    }
  }
}
</script>

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

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

  .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;
    }
  }
}

::v-deep .el-switch__label {
  color: #FFFFFF;
}

::v-deep .el-switch__label.is-active {
  color: #43a1ff;
}

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

.process-dialog {
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 20px;
  box-sizing: border-box;
}

.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: #ffffff;
    }

    .pegVal-text2 {
      padding-left: 10px;
      font-size: 24px;
    }
  }
}
</style>
