<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formData.type === 'in' ? formRules : outFormRules"
      v-loading="formLoading"
      style="margin-right: 4em; margin-left: 0.5em; margin-top: 1em"
      label-width="130px"
    >
      <div class="base-expandable-content">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="t('maintain.deviceName')" prop="deviceName">
              <el-select disabled v-model="formData.deviceName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('maintain.status')" prop="status">
              <el-select v-model="formData.status" clearable disabled>
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_MAIN_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.repairType')" prop="type">
              <el-select disabled v-model="formData.type" clearable>
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_MAIN_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.shutDown')" prop="ifStop">
              <el-select v-model="formData.ifStop" clearable disabled>
                <el-option
                  v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="t('iotMaintain.startTime')"
              prop="maintainStartTime"
              :rules="formData.type === 'in' ? startRule : []"
            >
              <el-date-picker
                disabled
                style="width: 150%"
                v-model="formData.maintainStartTime"
                type="datetime"
                value-format="x"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="t('iotMaintain.endTime')"
              prop="maintainEndTime"
              :rules="formData.type === 'in' ? endRule : []"
            >
              <el-date-picker
                disabled
                style="width: 150%"
                v-model="formData.maintainEndTime"
                type="datetime"
                value-format="x"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.PersonInCharge')" prop="maintainPerson">
              <el-select
                v-model="formData.maintainPerson"
                filterable
                clearable
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="item in deptUsers"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.failureTime')" prop="failureTime">
              <el-date-picker
                disabled
                style="width: 150%"
                v-model="formData.failureTime"
                type="datetime"
                value-format="x"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.failureImpact')" prop="failureInfluence">
              <el-input v-model="formData.failureInfluence" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.faultySystem')" prop="failureSystem">
              <el-input v-model="formData.failureSystem" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.picture')" prop="pics">
              <UploadImgs v-model="formData.pics" :disabled="true" height="55px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.applyPerson')" prop="applyPersonId" :rules="formData.type==='out'?classifyRules:[]">
              <el-select v-model="formData.applyPersonId" :placeholder="t('iotMaintain.applyPersonHolder')" disabled clearable>
                <el-option
                  v-for="person in applyPeoPle"
                  :key="person.oaId"
                  :label="person.lastname"
                  :value="person.oaId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.maintainClassify')" prop="maintainClassify" :rules="formData.type==='out'?classifyRules:[]">
              <el-select v-model="formData.maintainClassify" :placeholder="t('iotMaintain.maintainClassifyHolder')" disabled clearable>
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_MAIN_CLASSIFY)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.kmHour')" prop="kmHour">
              <el-input v-model="formData.kmHour" :placeholder="t('iotMaintain.kmHourHolder')" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('deviceForm.model')" prop="model" :rules="formData.type==='out'?modelRules:[]">
              <el-input v-model="formData.model" :placeholder="t('deviceForm.modelHolder')" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('deviceForm.enable')" prop="enableDate" :rules="formData.type==='out'?modelRules:[]">
              <el-date-picker
                disabled
                style="width: 150%"
                v-model="formData.enableDate"
                type="date"
                value-format="YYYY-MM-DD"
                :placeholder="t('deviceForm.enableHolder')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <div style="display: flex;flex-direction: row">
              <el-form-item :label="t('iotMaintain.supplier')" prop="supplier" style="width: 86%" :rules="formData.type==='out'?supplierRules:[]">
                <el-input
                  disabled
                  clearable
                  v-model="formData.supplier"
                  :placeholder="t('iotMaintain.suppHolder')"
                />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="8" >
            <el-form-item :label="t('iotMaintain.repairCosts')" prop="maintainFee" :rules="formData.type==='out'?feeRules:[]">
              <el-input-number
                disabled
                v-model="formData.maintainFee"
                :min="0"
                :precision="2"
                :step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.projectManager')" prop="projectManager" :rules="formData.type==='out'?projectRules:[]">
              <el-select v-model="formData.projectManager" :placeholder="t('iotMaintain.projectManagerHolder')" disabled clearable filterable>
                <el-option
                  v-for="person in projectManager"
                  :key="person.oaId"
                  :label="person.lastname"
                  :value="person.oaId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8"  v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.address')" prop="address">
              <el-input  v-model="formData.address" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formData.type === 'out'">
            <el-form-item :label="t('iotMaintain.attachment')" prop="outFiles">
              <UploadFile v-model="formData.outFiles" :is-show-tip="false" class="min-w-80px" multiple :limit="2" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="16"  v-if="formData.type === 'out'" >
            <el-form-item :label="t('iotMaintain.maintainItem')" prop="maintainItem" :rules="formData.type==='out'?itemRules:[]">
              <el-input type="textarea" v-model="formData.maintainItem" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.faultDescription')" prop="description">
              <el-input type="textarea" v-model="formData.description" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.repairDescription')" prop="maintainDescription">
              <el-input type="textarea" v-model="formData.maintainDescription" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="t('iotMaintain.solution')" prop="solution">
              <el-input type="textarea" v-model="formData.solution" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('iotMaintain.remark')" prop="remark">
              <el-input v-model="formData.remark" type="textarea" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column :label="t('iotMaintain.deviceCode')" align="center" prop="deviceCode" />
        <el-table-column :label="t('iotMaintain.deviceName')" align="center" prop="deviceName" />
        <el-table-column :label="t('iotMaintain.repairItems')" align="center" prop="name" />

        <el-table-column :label="t('iotMaintain.operation')" align="center" min-width="120px">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center; width: 100%">
              <div style="margin-left: 12px">
                <el-button
                  link
                  type="primary"
                  @click="handleViewNew(scope.row.id, scope.row.bomNodeId)"
                >
                  物料详情
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>
  </ContentWrap>
  <ContentWrap>
    <el-form>
      <el-form-item style="float: right">
        <el-button type="info" @click="close">取 消</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <MaterialListDrawer
    :model-value="drawerVisible"
    @update:model-value="(val) => (drawerVisible = val)"
    :node-id="currentBomNodeId"
    :materials="materialList"
    :detail="true"
  />
</template>
<script setup lang="ts">
import { DICT_TYPE, getBoolDictOptions, getStrDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import { ref } from 'vue'
import { IotMaintainMaterialApi, IotMaintainMaterialVO } from '@/api/pms/maintain/material'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { IotMaintainApi } from '@/api/pms/maintain'
import MaterialListDrawer from '@/views/pms/iotmainworkorder/SelectedMaterialDrawer.vue'
import { IotMaintainMaterialsApi } from '@/api/pms/maintain/materials'
import {CACHE_KEY, useCache} from "@/hooks/web/useCache";

/** 维修工单 表单 */
defineOptions({ name: 'IotMaintainDetail' })

const { t } = useI18n() // 国际化

const projectRules = [{ required: true, message: '项目经理不能为空', trigger: 'blur' }]
const itemRules = [{ required: true, message: '维修项目不能为空', trigger: 'blur' }]
const classifyRules = [{ required: true, message: '维修类别不能为空', trigger: 'blur' }]
const feeRules = [{ required: true, message: '维修费用不能为空', trigger: 'blur' }]
const modelRules = [{ required: true, message: '规格型号不能为空', trigger: 'blur' }]
const supplierRules = [{ required: true, message: '供应商不能为空', trigger: 'blur' }]

const applyPeoPle = ref([])
const projectManager = ref([])

const props = defineProps<{ id?: number }>()
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const deptUsers = ref<UserApi.UserVO[]>([]) // 用户列表
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const deviceLabel = ref('') // 表单的类型：create - 新增；update - 修改
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const list = ref<IotMaintainMaterialVO[]>([]) // 列表的数据
const { params, name } = useRoute() // 查询参数
const id = params.id || props.id
const materialList = ref<any[]>([]) // 保养工单bom关联物料列表
const { wsCache } = useCache()
const currentBomNodeId = ref<string>()
const formData = ref({
  kmHour:undefined,
  maintainItem:undefined,
  enableDate: undefined,
  projectManager:undefined,
  applyPersonId:undefined,
  maintainClassify: undefined,
  address:undefined,
  model:undefined,
  id: undefined,
  failureCode: undefined,
  failureName: undefined,
  deviceId: undefined,
  status: undefined,
  type: undefined,
  ifStop: undefined,
  failureTime: undefined,
  failureInfluence: undefined,
  failureSystem: undefined,
  description: undefined,
  pic: undefined,
  pics:undefined,
  outFiles:undefined,
  solution: undefined,
  maintainStartTime: undefined,
  maintainEndTime: undefined,
  remark: undefined,
  deviceName: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  deptId: undefined,
  maintainPerson: undefined,
  maintainDescription: undefined,
  supplier: undefined,
  maintainFee: undefined,
  outFile: undefined,
  supplierName: undefined,
})
const formRules = reactive({
  // deviceName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  // failureCode: [{ required: true, message: '故障编码不能为空', trigger: 'blur' }],
  // type: [{ required: true, message: '维修类型不能为空', trigger: 'blur' }],
  // ifStop: [{ required: true, message: '是否停机不能为空', trigger: 'blur' }],
  // failureName: [{ required: true, message: '故障名称不能为空', trigger: 'blur' }],
  // // failureTime: [{ required: true, message: '故障时间不能为空', trigger: 'blur' }],
  // maintainStartTime: [{ required: true, message: '维修开始时间不能为空', trigger: 'blur' }],
  // maintainDescription: [{ required: true, message: '维修描述不能为空', trigger: 'blur' }],
  // maintainPerson: [{ required: true, message: '维修负责人不能为空', trigger: 'blur' }],
  // deviceId: [{ required: true, message: '设备id不能为空', trigger: 'blur' }],
  // status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const outFormRules = reactive({
  // deviceName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  // failureCode: [{ required: true, message: '故障编码不能为空', trigger: 'blur' }],
  // type: [{ required: true, message: '维修类型不能为空', trigger: 'blur' }],
  // ifStop: [{ required: true, message: '是否停机不能为空', trigger: 'blur' }],
  // failureName: [{ required: true, message: '故障名称不能为空', trigger: 'blur' }],
  // maintainStartTime: [{ required: true, message: '维修开始时间不能为空', trigger: 'blur' }],
  // maintainEndTime: [{ required: true, message: '维修结束时间不能为空', trigger: 'blur' }],
  // maintainDescription: [{ required: true, message: '维修描述不能为空', trigger: 'blur' }],
  // maintainPerson: [{ required: true, message: '维修负责人不能为空', trigger: 'blur' }],
  // deviceId: [{ required: true, message: '设备id不能为空', trigger: 'blur' }],
  // maintainFee: [{ required: true, message: '维修费用不能为空', trigger: 'blur' }],
  // supplier: [{ required: true, message: '供应商不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'IotMaintain', params: {} })
}
const startRule = [
  // { required: true, message: '维修开始时间不能为空', trigger: 'blur' }
]
const endRule = [
  // { required: true, message: '维修结束时间不能为空', trigger: 'blur' }
]
const handleViewNew = (nodeId, bomId) => {
  drawerVisible.value = true
  const queryParams = {
    pageNo: 1,
    pageSize: 100,
    bomId: nodeId
  }
  IotMaintainMaterialsApi.getIotMaintainMaterialsPage(queryParams).then((res) => {
    currentBomNodeId.value = bomId
    materialList.value = res.list
  })
}
const userId = ref('')
/** 提交表单 */
onMounted(async () => {
  const userInfo = wsCache.get(CACHE_KEY.USER)
  userId.value = userInfo.user.nickname;
  await IotMaintainApi.getIotMaintain(id).then((res) => {
    debugger
    formData.value = res
    if (res.outFile) {
      formData.value.outFile = res.outFile.split(',')
    }
    list.value = res.maintainBomDOS
    list.value.forEach((item) => {
      item.deviceName = res.deviceName
      item.deviceCode = res.deviceCode
    })
    UserApi.getUser(formData.value.maintainPerson).then((ress) => {
      formData.value.maintainPerson = ress.nickname
    })
    IotMaintainMaterialApi.getMaterialsByDeviceId()
    if (formData.value.type === 'out') {
      IotMaintainApi.getApplyUsers(res.creator).then((resss) => {
        applyPeoPle.value = resss
      })
      IotMaintainApi.getProjectUsers(res.creator).then((ressss) => {
        debugger
        projectManager.value = ressss
      })
    }
  })
})
</script>
