""" @author: yy @desc：关联车辆 @date: 2025-07-25 01:17:31 """
<template>
  <MOSTY.Modal v-if="visible" v-model:visible="visible" v-model:loading="loading" :title="`${editId ? '编辑' : '新增'}关联车辆`" @ok="handleSave">
    <el-form :model="form" :rules="rules" label-width="auto" ref="formRef">
      <div class="wrapper">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="车牌号" prop="cph">
              <MOSTY.SelectSearch
                v-model:value="form.cph"
                remoteMethodType="post"
                remoteMethodApi="/mosty-api/mosty-jcgl/car/queryCarMsg"
                keyword="carnumber"
                :oth-params="{
                  pageCurrent: 1,
                  pageSize: 100,
                  orgid: id
                }"
                :fieldNames="{ label: 'carnumber', value: 'carnumber' }"
                placeholder="请选择"
                @change="handleCphChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车辆类型">
              <MOSTY.DictTree :zdbh="'D_TB_CLLX'" placeholder="请选择车辆类型" disabled v-model="form.cllx" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物联终端名称" prop="wlsbmc">
              <el-input v-model="form.wlsbmc" placeholder="请输入" :maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="物联设备ID" prop="wlsjzdid">
              <el-input v-model="form.wlsjzdid" placeholder="请输入" :maxlength="50" @blur="handleWlsjzdidCheck" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="物联终端大类" prop="wlzddlList">
              <MOSTY.DictRidioAndSelectV2 v-model="form.wlzddlList" multiple selectType="select" :dictKey="DICT_TYPE.D_BZ_CLAQZNH" @getOptions="getOptions" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <div class="title">已安装设备</div>
        <el-row :gutter="24">
          <el-col :span="12">
            <div>摄像头</div>
            <el-form-item label="车前">
              <el-input v-model="form.yazsb['01'].cq" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车后">
              <el-input v-model="form.yazsb['01'].ch" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车左">
              <el-input v-model="form.yazsb['01'].cz" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车右">
              <el-input v-model="form.yazsb['01'].cy" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="驾驶室">
              <el-input v-model="form.yazsb['01'].jss" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="货箱">
              <el-input v-model="form.yazsb['01'].hx" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div>雷达</div>
            <el-form-item label="车前">
              <el-input v-model="form.yazsb['03'].cq" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车后">
              <el-input v-model="form.yazsb['03'].ch" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车左">
              <el-input v-model="form.yazsb['03'].cz" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="车右">
              <el-input v-model="form.yazsb['03'].cy" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="定位" label-position="left" label-width="40px">
              <el-input v-model="form.yazsb['02']" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="OBD" label-position="left" label-width="44px">
              <el-input v-model="form.yazsb['04']" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </MOSTY.Modal>
</template>
<script setup>
import { computed, ref, watch, nextTick } from "vue"
import { ElMessage } from "element-plus"
import * as MOSTY from "@/components/MyComponents/index"
import { DICT_TYPE } from "@/components/MyComponents/Dict/const/dict"
import { getApi2, postApi2 } from "@/api/tobAcco_api.js"

const emit = defineEmits(["update:visible", "success"])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 责任单位的ID
  id: {
    type: String,
    default: ""
  },
  // 编辑时，请求详情的ID
  editId: {
    type: String,
    default: ""
  },
  // 智慧交通主列表的ID
  zhjtId: {
    type: String,
    default: ""
  }
})

const visible = computed({
  get() {
    return props.visible
  },
  set(val) {
    emit("update:visible", val)
  }
})
const form = ref({
  id: "",
  cph: "", // 车牌号
  cllx: "", // 车牌类型
  wlsbmc: "", // 物联设备终端名称
  wlsjzdid: "", // 物联终端ID
  wlzddlList: [], // 物联终端大类 [{text,value}]
  yazsb: {
    // 01 摄像头 02 定位 03 雷达 04 OBD
    "01": {
      cq: "",
      ch: "",
      cz: "",
      cy: "",
      jss: "",
      hx: ""
    },
    "02": "",
    "03": {
      cq: "",
      ch: "",
      cz: "",
      cy: ""
    },
    "04": ""
  }
})
const loading = ref(false)
const formRef = ref(null)
// 物联终端大类下拉框的值，用于保存时匹配数据给后端
let wlzdOptions = []
// 物联终端ID是否存在
const isMark = ref(false)

// 使用自定义组合式函数

const rules = ref({
  cph: [{ required: true, message: "请输入车牌号", trigger: ["change"] }],
  cllx: [{ required: true, message: "请选择车牌类型", trigger: ["change"] }],
  wlsbmc: [{ required: true, message: "请输入物联设备终端名称", trigger: ["change"] }],
  wlsjzdid: [{ required: true, message: "请输入物联终端ID", trigger: ["change"] }],
  wlzddlList: [{ required: true, message: "请选择物联终端大类", trigger: ["change"] }]
})

// 车牌号改变时，获取车辆类型
const handleCphChange = item => {
  form.value.cllx = item.cartype
  form.value.clxxid = item.id
}

const handleWlsjzdidCheck = async () => {
  try {
    const res = await getApi2({ wlsjzdid: form.value.wlsjzdid }, "/mosty-wljc/zhjtxt/existByWlsjzdid")

    isMark.value = res
    if (res) {
      ElMessage.error("物联终端ID已存在")
    }
  } catch (e) {
    console.log(e)
  }
}

// 物联终端大类获取的下拉框的值
const getOptions = options => {
  wlzdOptions = options
}

const getParam = () => {
  const params = JSON.parse(JSON.stringify(form.value))
  // 智慧交通系统id
  params.zhjtxtid = props.zhjtId
  params.id = props.editId
  params.wlzddlList = wlzdOptions.filter(t => form.value.wlzddlList.includes(t.dm)).map(t => ({ text: t.zdmc, value: t.dm }))
  return params
}

const handleSave = async () => {
  try {
    console.log("form.value", form.value)
    console.log("wlzdOptions", wlzdOptions)

    loading.value = true
    await formRef.value.validate()
    if (isMark.value) {
      ElMessage.error("物联终端ID已存在")
      return
    }
    await postApi2({ ...getParam() }, "/mosty-wljc/zhjtxt/replaceAtta")
    ElMessage.success("保存成功")
    visible.value = false
    emit("success")
  } catch (error) {
    console.log("error", error)
  } finally {
    loading.value = false
  }
}

// 编辑时，获取详情
const getDetail = async () => {
  try {
    const res = await getApi2({ id: props.editId }, "/mosty-wljc/zhjtxt/detailAtta")
    console.log(res)
    form.value = {
      id: res?.id,
      cph: res?.cph,
      cllx: res?.cllx,
      clxxid: res?.clxxid,
      wlsbmc: res?.wlsbmc,
      wlsjzdid: res?.wlsjzdid,
      wlzddlList: res?.wlzddlList.map(t => t.value),
      yazsb: res?.yazsb
    }
  } catch (error) {
    console.log("error", error)
  }
}

watch(
  () => props.visible,
  val => {
    if (val && props.editId) {
      getDetail()
    }
  },
  { immediate: true }
)
</script>
<style lang="scss" scoped>
.wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  .title {
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    margin: 0px 0 20px;
  }
}
</style>
