<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle"  :close-on-click-modal="false">
    <el-form ref="basicFormRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="转办类型" prop="transferType">
            <el-select v-model="formData.transferType" placeholder="请选择转办类型" style="width: 150px" @change="onChangeSec">
              <el-option label="人员转办" value="0"></el-option>
              <el-option label="类型转办" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障类型" prop="faultType">
            <el-input v-model="formData.faultType" style="width: 150px" disabled></el-input>
            <el-button :icon="Search" @click="chooseFaultType" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备类别" prop="type" >
            <el-select v-model="formData.type" placeholder="请选择设备类别" style="width: 150px" :disabled = "isDisabled1" @change="onChangeType">
              <el-option label="设备" value="DEVICE"></el-option>
              <el-option label="工装" value="EQUIPMENT"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="equipmentCode" >
            <el-input v-model="formData.equipmentCode" style="width: 150px" disabled></el-input>
            <el-button :icon="Search" @click="chooseEquipmentCode" :disabled = "isDisabled1"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="车间" prop="workshopCode">
            <el-input v-model="formData.workshopCode" style="width: 150px" disabled></el-input>
            <el-button :icon="Search" @click="chooseWorkshopCode" :disabled = "isDisabled2"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维修人" prop="maintenancer">
            <el-input v-model="formData.maintenancer" style="width: 150px" :disabled = "isDisabled2"></el-input>
            <!-- <el-button :icon="Search" @click="chooseWorkshopCode" />-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="班组" prop="classType">
            <el-select v-model="formData.classType" placeholder="请选择班组类别" style="width: 150px">
              <el-option label="白班" value="0"></el-option>
              <el-option label="夜班" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm('success')">确 定</el-button>
      <el-button @click="handleClose('close')">取 消</el-button>
    </template>
  </Dialog>

<!--添加巡检项弹窗-->
  <SearchTable ref="searchTableRef" @searchTableSuccess="searchTableSuccess" />

</template>
<script lang="ts" setup>
import { SearchTable } from '@/components/SearchTable'
import {ElInput} from "element-plus";
import { Search } from '@element-plus/icons-vue'
import * as EquipmentRepairJobMainApi from "@/api/eam/equipmentRepairJobMain";
import * as WorkshopApi from "@/api/wms/workshop";
import {Workshop} from "@/views/wms/basicDataManage/factoryModeling/workshop/workshop.data";
import {EquipmentAccounts} from "@/views/eam/equipmentAccounts/equipmentAccounts.data";
import * as EquipmentItemApi from "@/api/eam/equipmentAccounts";
import {ToolAccounts} from "@/views/eam/toolAccounts/toolAccounts.data";
import * as ToolItemApi from "@/api/eam/toolAccounts";
import {BasicFaultType} from "@/views/eam/basicFaultType/basicFaultType.data";
import * as BasicFaultTypeApi from "@/api/eam/basicFaultType";

defineOptions({ name: 'TeamForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('转办') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const tags=ref([])

const typeValue = ref('')
const inputVisible = ref(false)
const isDisabled1 = ref(false)
const isDisabled2 = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()


const formData = ref({
  id:'',
  number:'',
  transferType:'',
  faultType:'',
  type:'',
  equipmentCode:'',
  workshopCode:'',
  maintenancer: '',
  classType: '',
})
const formRules = reactive({
  transferType: [
    { required: true, message: '转办类型不能为空', trigger: 'change' },
    { max: 50, message: '不得超过50个字符', trigger: 'change' }
  ],
  faultType: [
    { required: true, message: '故障类型不能为空', trigger: 'change' },
  ],
  classType: [
    { required: true, message: '班次不能为空', trigger: 'change' },
  ],
  workshopCode: [
    { required: false, message: '车间不能为空', trigger: 'change' },
  ],
  maintenancer: [
    { required: false, message: '维修人不能为空', trigger: 'change' },
  ],
  type: [
    { required: false, message: '设备类别不能为空', trigger: 'change' },
  ],
  equipmentCode: [
    { required: false, message: '设备编号不能为空', trigger: 'change' },
  ],
})
const basicFormRef = ref() // 表单 Ref

// /** 弹窗相关参数 */
const searchTableRef = ref();
const _searchTableTitle = ref();
const _searchTableAllSchemas = ref();
const _searchTablePage = ref();
const _searchField = ref();
const _formField = ref();
const _multiple = ref();
const _searchCondition = ref({})


/** 选择故障类型弹窗 */
const chooseFaultType = (field) => {
    _searchCondition.value = {}
    const filters: any[] = []
    filters.push({
      key: 'available',
      value: 'TRUE',
      isMainValue: false
    })
    // 参数整理
    _searchCondition.value.isSearch = true
    _searchCondition.value.filters = filters
    _searchTableTitle.value = '选择故障类型'
    _searchField.value = "faultType"
    _formField.value = 'faultType'
    _searchTablePage.value = BasicFaultTypeApi.getBasicFaultTypePage,
    _searchTableAllSchemas.value = BasicFaultType.allSchemas,
    openCommon()
}


/** 选择设备编码弹窗 */
const chooseEquipmentCode = (field) => {
    _searchCondition.value = {}
    const filters: any[] = []
    filters.push({
      key: 'status',
      value: 'NORMAL',
      action: '==',
      isSearch: true,
      isMainValue: false
    })
    // 参数整理
    _searchCondition.value.isSearch = true
    _searchCondition.value.filters = filters
    _searchField.value = "equipmentCode"
    _formField.value = 'equipmentCode'
    if(typeValue.value == 'DEVICE'){
        _searchTableTitle.value = '选择设备编号'
        _searchTablePage.value = EquipmentItemApi.getEquipmentAccountsPage,
        _searchTableAllSchemas.value = EquipmentAccounts.allSchemas
    }else{
        _searchTableTitle.value = '选择工装编号'
        _searchTablePage.value = ToolItemApi.getToolAccountsPage,
        _searchTableAllSchemas.value = ToolAccounts.allSchemas
    }
    openCommon()
}


/** 选择车间弹窗 */
const chooseWorkshopCode = (field) => {
  _searchCondition.value = {}
  const filters: any[] = []
  filters.push({
    key: 'available',
    value: 'TRUE',
    isMainValue: false
  })
  // 参数整理
  _searchCondition.value.isSearch = true
  _searchCondition.value.filters = filters
  _searchTableTitle.value = '选择车间'
  _searchField.value = "workshopCode"
  _formField.value = 'workshopCode'
  _searchTablePage.value = WorkshopApi.getWorkshopPage,
  _searchTableAllSchemas.value = Workshop.allSchemas,
  openCommon()
}

/*打开弹窗*/
const openCommon = () => {
  searchTableRef.value.open(
    _searchTableTitle.value,
    _searchTableAllSchemas.value,
    _searchTablePage.value,
    _searchField.value,
    _searchCondition.value
  )
}

/** 弹窗选择之后  回调函数 */
const searchTableSuccess = (formField, searchField, val) => {
  nextTick?.(() => {
    console.log(formField)
    if (formField === 'workshopCode') {
      formData.value.workshopCode = val[0].code
    }
    if (formField === 'equipmentCode') {
      formData.value.equipmentCode = val[0].code
    }
    if (formField === 'faultType') {
      formData.value.faultType = val[0].code
    }
  })
}

/** 初始化弹窗 */
const open = async (type: string, row?: object) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  //初始化数据
  formData.value.id = row.id
  formData.value.number = row.number
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


const onChangeType = (field) => {
    typeValue.value = ''
    if(field == 'DEVICE'){
        typeValue.value = 'DEVICE'
        formData.value.equipmentCode = null
    }else if(field == 'EQUIPMENT'){
        typeValue.value = 'EQUIPMENT'
        formData.value.equipmentCode = null
    }
}

const onChangeSec = (field) => {
    //人员转办
    if(field == '0'){
        formData.value.equipmentCode = null
        formData.value.type = null
        isDisabled1.value = true
        isDisabled2.value = false
        formRules.workshopCode[0].required = true
        formRules.maintenancer[0].required = true
        formRules.type[0].required = false
        formRules.equipmentCode[0].required = false
    }else{
    //类型转办
        formData.value.workshopCode = null
        formData.value.maintenancer = null
        isDisabled1.value = false
        isDisabled2.value = true
        formRules.workshopCode[0].required = false
        formRules.maintenancer[0].required = false
        formRules.type[0].required = true
        formRules.equipmentCode[0].required = true
    }
}

/** 提交表单 */
const submitForm = async (val) => {

   // 校验表单
   if (!basicFormRef) return
   const valid = await basicFormRef.value.validate()
   if (!valid) return

   await message.delConfirm('是否提交数据？');

   //发送数据
   await EquipmentRepairJobMainApi.updateEquipmentRepairJobMain(formData.value)
   //把success函数传递到父页面
   emit('success',formData.value.id)
   dialogVisible.value = false
}

const handleClose=(val)=>{
  dialogVisible.value = false
  emit('close',val)
}

// 传递给父类
const emit = defineEmits(['close','success'])

</script>

<style scoped>
.tag-container {
  margin-top: 10px; /* 可根据需要调整标签容器与表单项之间的间距 */
  border: 1px solid #ccc; /* 添加边框样式 */
  padding: 10px; /* 可根据需要调整容器内边距 */
  width: 950px; /* 设置固定宽度为 950px */
  overflow-y: auto; /* 当内容溢出容器高度时显示滚动条 */
  word-wrap: break-word; /* 使用 word-wrap 属性实现超出范围换行 */
  overflow-wrap: break-word; /* 兼容性更好的写法 */
  flex-wrap: wrap;
}
.input-with-button {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-with-button > .el-input {
  flex: 1;
  /*margin-right: 10px;*/
}

</style>
