<template>
  <div v-loading="formLoading" class="maintain-detail-page">
    <div class="detail-header">
      <div class="detail-header__main">
        <div class="detail-header__icon">
          <Icon icon="ep:tools" />
        </div>
        <div>
          <h2 class="detail-title">维修工单详情</h2>
          <p class="detail-subtitle">查看设备故障、维修处理与关联物料信息</p>
        </div>
      </div>
      <el-button size="default" @click="close">
        <Icon icon="ep:arrow-left" class="mr-5px" />返回
      </el-button>
    </div>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formData.type === 'in' ? formRules : outFormRules"
      size="default"
      label-width="112px"
      class="detail-form">
      <section class="detail-section">
        <div class="section-heading"><span></span>基础信息</div>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('maintain.deviceName')" prop="deviceName">
              <el-input v-model="formData.deviceName" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('maintain.status')" prop="status">
              <el-select v-model="formData.status" 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 :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.repairType')" prop="type">
              <el-select v-model="formData.type" disabled>
                <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 :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.shutDown')" prop="ifStop">
              <el-select v-model="formData.ifStop" 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 :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.failureTime')" prop="failureTime">
              <el-date-picker
                v-model="formData.failureTime"
                type="datetime"
                value-format="x"
                disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.faultySystem')" prop="failureSystem">
              <el-input v-model="formData.failureSystem" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.failureImpact')" prop="failureInfluence">
              <el-input v-model="formData.failureInfluence" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </section>

      <section class="detail-section">
        <div class="section-heading"><span></span>维修处理</div>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.startTime')"
              prop="maintainStartTime"
              :rules="formData.type === 'in' ? startRule : []">
              <el-date-picker
                v-model="formData.maintainStartTime"
                type="datetime"
                value-format="x"
                disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.endTime')"
              prop="maintainEndTime"
              :rules="formData.type === 'in' ? endRule : []">
              <el-date-picker
                v-model="formData.maintainEndTime"
                type="datetime"
                value-format="x"
                disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.PersonInCharge')" prop="maintainPerson">
              <el-input v-model="formData.maintainPerson" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('maintain.maintainWay')" prop="maintainMethod">
              <el-select v-model="formData.maintainMethod" disabled>
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PMS_MAINTAIN_METHOD)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.repairCosts')"
              prop="maintainFee"
              :rules="formData.type === 'out' ? feeRules : []">
              <el-input-number
                v-model="formData.maintainFee"
                :min="0"
                :precision="2"
                :step="0.1"
                controls-position="right"
                disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="t('maintain.methodDescription')" prop="methodDescription">
              <el-input
                v-model="formData.methodDescription"
                type="textarea"
                :rows="2"
                resize="none"
                disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </section>

      <section v-if="formData.type === 'out'" class="detail-section">
        <div class="section-heading"><span></span>外委信息</div>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.applyPerson')"
              prop="applyPersonId"
              :rules="classifyRules">
              <el-select v-model="formData.applyPersonId" disabled>
                <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 :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.maintainClassify')"
              prop="maintainClassify"
              :rules="classifyRules">
              <el-select v-model="formData.maintainClassify" disabled>
                <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 :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.kmHour')" prop="kmHour"
              ><el-input v-model="formData.kmHour" disabled
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('deviceForm.model')" prop="model" :rules="modelRules"
              ><el-input v-model="formData.model" disabled
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('deviceForm.enable')" prop="enableDate" :rules="modelRules"
              ><el-date-picker
                v-model="formData.enableDate"
                type="date"
                value-format="YYYY-MM-DD"
                disabled
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.supplier')" prop="supplier" :rules="supplierRules"
              ><el-input v-model="formData.supplier" disabled
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item
              :label="t('iotMaintain.projectManager')"
              prop="projectManager"
              :rules="projectRules">
              <el-select v-model="formData.projectManager" disabled
                ><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 :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.address')" prop="address"
              ><el-input v-model="formData.address" disabled
            /></el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :xl="8">
            <el-form-item :label="t('iotMaintain.attachment')" prop="outFiles"
              ><UploadFile
                v-model="formData.outFiles"
                :is-show-tip="false"
                multiple
                :limit="2"
                disabled
            /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="t('iotMaintain.maintainItem')"
              prop="maintainItem"
              :rules="itemRules"
              ><el-input
                v-model="formData.maintainItem"
                type="textarea"
                :rows="2"
                resize="none"
                disabled
            /></el-form-item>
          </el-col>
        </el-row>
      </section>

      <section class="detail-section">
        <div class="section-heading"><span></span>故障描述</div>
        <el-row :gutter="24">
          <el-col :xs="24" :xl="8">
            <el-form-item :label="t('iotMaintain.picture')" prop="pics">
              <UploadImgs v-model="formData.pics" :disabled="true" height="72px" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :xl="16"
            ><el-form-item :label="t('iotMaintain.faultDescription')" prop="description"
              ><el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                resize="none"
                disabled /></el-form-item
          ></el-col>
          <el-col :xs="24" :xl="12"
            ><el-form-item :label="t('iotMaintain.repairDescription')" prop="maintainDescription"
              ><el-input
                v-model="formData.maintainDescription"
                type="textarea"
                :rows="3"
                resize="none"
                disabled /></el-form-item
          ></el-col>
          <el-col :xs="24" :xl="12"
            ><el-form-item :label="t('iotMaintain.solution')" prop="solution"
              ><el-input
                v-model="formData.solution"
                type="textarea"
                :rows="3"
                resize="none"
                disabled /></el-form-item
          ></el-col>
          <el-col :span="24"
            ><el-form-item :label="t('iotMaintain.remark')" prop="remark"
              ><el-input
                v-model="formData.remark"
                type="textarea"
                :rows="2"
                resize="none"
                disabled /></el-form-item
          ></el-col>
        </el-row>
      </section>
    </el-form>

    <section class="detail-section material-section">
      <div class="section-heading"><span></span>关联物料</div>
      <ZmTable
        :loading="formLoading"
        :data="list"
        :show-border="true"
        settings-cache-key="pms-maintain-detail-material">
        <ZmTableColumn
          :label="t('iotMaintain.deviceCode')"
          align="center"
          prop="deviceCode"
          fixed="left" />
        <ZmTableColumn :label="t('iotMaintain.deviceName')" align="center" prop="deviceName" />
        <ZmTableColumn :label="t('iotMaintain.repairItems')" align="center" prop="name" />
        <ZmTableColumn :label="t('iotMaintain.operation')" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button
              size="default"
              link
              type="primary"
              @click="handleViewNew(scope.row.id, scope.row.bomNodeId)"
              >物料详情</el-button
            >
          </template>
        </ZmTableColumn>
      </ZmTable>
    </section>

    <div class="sticky-action-bar">
      <el-button size="default" @click="close">返回</el-button>
    </div>
  </div>

  <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 { useTableComponents } from '@/components/ZmTable/useTableComponents'

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

const { t } = useI18n() // 国际化
const { ZmTable, ZmTableColumn } = useTableComponents<IotMaintainMaterialVO>()

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 { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const drawerVisible = ref<boolean>(false)
const list = ref<IotMaintainMaterialVO[]>([]) // 列表的数据
const { params } = useRoute() // 查询参数
const id = params.id || props.id
const materialList = ref<any[]>([]) // 保养工单bom关联物料列表
const currentBomNodeId = ref<string>()
const formData = ref({
  methodDescription: undefined,
  maintainMethod: undefined,
  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
  })
}
/** 提交表单 */
onMounted(async () => {
  formLoading.value = true
  await IotMaintainApi.getIotMaintain(id).then((res) => {
    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) => {
        projectManager.value = ressss
      })
    }
  })
  formLoading.value = false
})
</script>

<style scoped>
.maintain-detail-page {
  display: flex;
  flex-direction: column;
  min-height: calc(
    100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  );
  padding: 16px;
  background: #f5f7fa;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  margin-bottom: 16px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 8%);
}

.detail-header__main {
  display: flex;
  align-items: center;
  min-width: 0;
}

.detail-header__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  margin-right: 12px;
  font-size: 20px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.detail-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  line-height: 26px;
  color: var(--el-text-color-primary);
}

.detail-subtitle {
  margin: 2px 0 0;
  font-size: 13px;
  line-height: 20px;
  color: var(--el-text-color-secondary);
}

.detail-form,
.detail-section {
  min-width: 0;
}

.detail-section {
  padding: 0 20px 4px;
  margin-bottom: 16px;
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 5%);
}

.section-heading {
  display: flex;
  height: 46px;
  padding: 0 20px;
  margin: 0 -20px 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
  align-items: center;
}

.section-heading span {
  width: 4px;
  height: 18px;
  margin-right: 10px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.detail-form :deep(.el-select),
.detail-form :deep(.el-date-editor),
.detail-form :deep(.el-input-number) {
  width: 100%;
}

.detail-form :deep(.el-form-item) {
  margin-bottom: 16px;
}

.material-section {
  padding-bottom: 20px;
}

.sticky-action-bar {
  position: sticky;
  bottom: 0;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  min-height: 58px;
  padding: 10px 20px;
  margin-top: auto;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 -4px 12px rgb(0 0 0 / 8%);
}

.sticky-action-bar :deep(.el-button) {
  margin-left: 0;
}

@media (width <= 768px) {
  .maintain-detail-page {
    padding: 12px;
  }

  .sticky-action-bar {
    padding-right: 12px;
    padding-left: 12px;
    margin-right: -12px;
    margin-bottom: -12px;
    margin-left: -12px;
  }

  .detail-header,
  .detail-section {
    padding-right: 12px;
    padding-left: 12px;
  }

  .detail-subtitle {
    display: none;
  }

  .section-heading {
    padding-right: 12px;
    padding-left: 12px;
    margin-right: -12px;
    margin-left: -12px;
  }

  .detail-form {
    --el-form-label-width: 96px;
  }
}
</style>
