<script setup lang="ts">
import XDatePicker from '@af-mobile-client-vue3/components/core/XDatePicker/index.vue'
import XSelect from '@af-mobile-client-vue3/components/core/XSelect/index.vue'
import { getConfigByName } from '@af-mobile-client-vue3/services/api/common'
import CameraView from '@af-mobile-client-vue3/views/SafeInspection/SecurityFormItem/CameraView/index.vue'
import SecurityFormItem from '@af-mobile-client-vue3/views/SafeInspection/SecurityFormItem/FormItem.vue'
import moment from 'moment'
import { Field as VanField } from 'vant'
import { inject, onBeforeMount, ref } from 'vue'

const props = defineProps({
  // 配置项数据
  row: {
    type: Object,
    required: true,
  },
  userDetail: {
    type: Object,
    required: false,
  },
  showTitle: {
    type: Boolean,
    default: true,
  },
  safeConfig: {
    type: Object,
    required: false,
  },
  // 全局只读：为 true 时，该组件内所有表单项均只读
  isReadOnly: {
    type: Boolean,
    default: false,
  },
  // 检查人信息
  checkerInfo: {
    type: Object,
    required: false,
    default: () => ({}),
  },
})

const emit = defineEmits(['valueChange', 'processModeChange', 'cameraViewChange', 'updateFileList', 'photoQualityChange'])
// 数据结构的映射配置
const dataStructure = {
  fieldType: 'type', // 表单项类型
  fieldLabel: 'itemname',
  fieldValue: 'value',
  placeholder: 'itemname',
  fieldOptions: 'options',
  optionsLabel: 'data',
  optionsValue: 'data',
  redundantData: 'f_data',
}

// 从父组件获取 dispatchDeptList 和 repairmanList，仅读取一次而非持有引用
const { dispatchDeptList: parentDispatchDeptList, repairmanList: parentRepairmanList } = (() => {
  try {
    const parent = inject<any>('provideParent', undefined)
    return {
      dispatchDeptList: parent?.dispatchDeptList?.value ?? [],
      repairmanList: parent?.repairmanList?.value ?? [],
    }
  }
  catch {
    return { dispatchDeptList: [], repairmanList: [] }
  }
})()

// 添加处理方式选项常量
const processModeList = ref([])
// 水印配置
const watermarkConfig = ref({})
// 获取派单类型列表
const handlingTypeList = ref([])
// 获取派单部门列表
const dispatchDeptList = ref([])
// 获取维修员列表
const repairmanList = ref([])
// 处理方式变更
function processModeChange(item: any, selVal: any, selObj: any) {
  if (props.isReadOnly)
    return
  item.f_process_mode = selVal
  item.f_handling_type = null
  item.f_dispatch_dept = null
  item.f_dispatch_dept_name = null
  item.f_repairman = null
  item.f_repairman_name = null
  emit('valueChange', selVal, selObj, item)
}
// 派单类型变更
function handlingTypeChange(item: any, selVal: any, selObj: any) {
  if (props.isReadOnly)
    return
  item.f_handling_type = selVal
  item.f_dispatch_dept = null
  item.f_dispatch_dept_name = null
  item.f_repairman = null
  item.f_repairman_name = null
  emit('valueChange', selVal, selObj, item)
}
// 派单部门变更
function dispatchDeptChange(item: any, selVal: any, selObj: any) {
  if (props.isReadOnly)
    return
  item.f_dispatch_dept = selVal
  item.f_dispatch_dept_name = selObj[0].label
  emit('valueChange', selVal, selObj, item)
}
// 维修员变更
function repairmanChange(item: any, selVal: any, selObj: any) {
  if (props.isReadOnly)
    return
  item.f_repairman = selVal
  item.f_repairman_name = selObj[0].label
  emit('valueChange', selVal, selObj, item)
}

// 相机视图变更
function cameraViewChange(item: any, list: any, type: string) {
  if (props.isReadOnly)
    return
  if (type === '隐患') {
    item.f_defect_paths = list
  }
  if (type === '隐患消除') {
    item.f_process_paths = list
  }
  emit('valueChange', null, null, item)
}

// 值变更处理
function valueChange(selVal: any, selObj: any, currentVal: any) {
  if (props.isReadOnly)
    return
  /*
  * {
    "isdefect": true,
    "defectdes": "超期",
    "data": "是",
    "level": "重大隐患",
    "isdefault": false,
    "aging": "5",
    "processMode": "自行处理"
    }
  * */
  switch (currentVal.type) {
    case 'radio':
    case 'selector':
    case 'checkbox':
    case 'multipleSelect':
      currentVal.f_is_defect = selObj[0].isdefect
      currentVal.aging = selObj[0].aging
      currentVal.level = selObj[0].level
      currentVal.defectdes = selObj[0].defectdes
      currentVal.f_process_mode = selObj[0].processMode
      currentVal.f_handle_date = selObj[0].aging ? moment().add(Number(selObj[0].aging), 'd').format('YYYY-MM-DD HH:mm:ss') : ''
      break
  }
  emit('valueChange', selVal, selObj, currentVal)
}

onBeforeMount(() => {
  getConfigByName('dict_safe_process_mode', (result) => {
    processModeList.value = [
      ...result.value,
    ]
  }, 'af-safecheck')
  // 获取水印配置
  getConfigByName('PhotoWatermarkConfig', (result) => {
    if (result) {
      watermarkConfig.value = result
    }
  }, 'af-safecheck')
  // 获取派单类型列表
  getConfigByName('dict_safe_handling_type', (result) => {
    if (result && result.value) {
      handlingTypeList.value = result.value
    }
  }, 'af-safecheck')
  dispatchDeptList.value = parentDispatchDeptList
  repairmanList.value = parentRepairmanList
})
</script>

<template>
  <div>
    <div v-if="props.showTitle" class="x-form-title">
      {{ row.itemname }}
    </div>
    <template v-for="(item, index) in row.items" :key="row.itemname + index">
      <SecurityFormItem
        v-if="item.show !== false"
        :item="item"
        :user-detail="userDetail"
        :safe-config="safeConfig"
        :data-structure="dataStructure"
        :config="row"
        :readonly="props.isReadOnly || item.readonly === true"
        :watermark-config="watermarkConfig"
        :checker-info="props.checkerInfo"
        @value-change="valueChange"
        @update-file-list="(list) => cameraViewChange(item, list, null)"
        @photo-quality-change="(type) => emit('photoQualityChange', type)"
      >
        <template v-if="(item as any).f_is_defect === true" #default="{ item: securityItem }">
          <div class="defect-section">
            <VanField
              v-if="!('defect_photo' in item) || item.defect_photo"
              name="picture"
              center
              label="隐患照片"
              :required="securityItem.checkmust === 'true'"
              :rules="[
                {
                  required: securityItem.checkmust === 'true',
                  validator: () => Array.isArray((securityItem as any).f_defect_paths) && (securityItem as any).f_defect_paths.length > 0,
                  message: '请上传隐患照片',
                },
              ]"
              class="defect-field"
            >
              <template #input>
                <CameraView
                  upload-mode="server"
                  :image-list="(securityItem.f_defect_paths as any[])"
                  authority="admin"
                  :disabled="props.isReadOnly"
                  :attr="{
                    addOrEdit: 'addOrEdit',
                    acceptCount: safeConfig?.defectPhotoNumber?.defectPhoto || 5,
                    uploadImage: safeConfig?.isUploadPhoto?.defect ?? false,
                    watermark: {
                      ...watermarkConfig,
                      userName: props.checkerInfo?.name || '',
                    },
                  }"
                  @update-file-list="(list) => cameraViewChange(item, list, '隐患')"
                  @photo-quality-change="(type) => emit('photoQualityChange', type)"
                />
              </template>
            </VanField>
            <VanField
              v-show="!(safeConfig?.showAndReadonly?.processMode?.hide)"
              v-model="securityItem.f_process_mode"
              name="handlingMethod"
              center
              label="处理方式"
              :required="securityItem.checkmust === 'true'"
              :rules="[{ required: securityItem.checkmust === 'true', message: '请选择处理方式' }]"
              :readonly="props.isReadOnly"
              class="defect-field"
            >
              <template #input>
                <XSelect
                  v-model="securityItem.f_process_mode"
                  placeholder="请选择处理方式"
                  :columns="processModeList"
                  :readonly="props.isReadOnly || safeConfig?.showAndReadonly?.processMode?.readonly"
                  @confirm="(selVal, selObj) => { processModeChange(securityItem, selVal, selObj) }"
                />
              </template>
            </VanField>
            <VanField
              v-if="securityItem.f_process_mode === '现场处理' && (!('process_photo' in item) || item.process_photo)"
              name="picture"
              center
              label="处理照片"
              :required="securityItem.checkmust === 'true'"
              :rules="[
                {
                  required: securityItem.checkmust === 'true',
                  validator: () => Array.isArray((securityItem as any).f_process_paths) && (securityItem as any).f_process_paths.length > 0,
                  message: '请上传处理照片',
                },
              ]"
              class="defect-field"
            >
              <template #input>
                <CameraView
                  upload-mode="server"
                  :image-list="(securityItem.f_process_paths as any[])"
                  authority="admin"
                  :disabled="props.isReadOnly"
                  :attr="{
                    addOrEdit: 'addOrEdit',
                    acceptCount: safeConfig?.defectPhotoNumber?.processphoto || 5,
                    uploadImage: safeConfig?.isUploadPhoto?.process ?? false,
                    watermark: {
                      ...watermarkConfig,
                      userName: props.checkerInfo?.name || '',
                    },
                  }"
                  @update-file-list="(list) => cameraViewChange(item, list, '隐患消除')"
                  @photo-quality-change="(type) => emit('photoQualityChange', type)"
                />
              </template>
            </VanField>
            <VanField
              v-if="securityItem.f_process_mode === '转维修' && !(safeConfig?.showAndReadonly?.handlingType?.hide)"
              name="handlingType"
              center
              label="派单类型"
              :readonly="props.isReadOnly"
              class="defect-field"
            >
              <template #input>
                <XSelect
                  v-model="securityItem.f_handling_type"
                  placeholder="请选择派单类型"
                  :columns="handlingTypeList"
                  :readonly="props.isReadOnly"
                  @confirm="(selVal, selObj) => { handlingTypeChange(securityItem, selVal, selObj) }"
                />
              </template>
            </VanField>
            <VanField
              v-if="securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转站点'"
              v-model="securityItem.f_dispatch_dept"
              name="dispatchDept"
              center
              label="选择站点"
              :readonly="props.isReadOnly"
              :required="securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转站点'"
              :rules="[
                {
                  required: securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转站点',
                  message: '请选择站点',
                },
              ]"
              class="defect-field"
            >
              <template #input>
                <XSelect
                  v-model="securityItem.f_dispatch_dept"
                  placeholder="请选择站点"
                  :columns="dispatchDeptList"
                  :readonly="props.isReadOnly"
                  @confirm="(selVal, selObj) => { dispatchDeptChange(securityItem, selVal, selObj) }"
                />
              </template>
            </VanField>
            <VanField
              v-if="securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转维修员'"
              v-model="securityItem.f_repairman"
              name="dispatchWorker"
              center
              label="选择维修员"
              :readonly="props.isReadOnly"
              :required="securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转维修员'"
              :rules="[
                {
                  required: securityItem.f_process_mode === '转维修' && securityItem.f_handling_type === '转维修员',
                  message: '请选择维修员',
                },
              ]"
              class="defect-field"
            >
              <template #input>
                <XSelect
                  v-model="securityItem.f_repairman"
                  placeholder="请选择维修员"
                  :columns="repairmanList"
                  :readonly="props.isReadOnly"
                  @confirm="(selVal, selObj) => { repairmanChange(securityItem, selVal, selObj) }"
                />
              </template>
            </VanField>
            <VanField
              v-show="!(safeConfig?.showAndReadonly?.processTime?.hide)"
              v-model="securityItem.f_handle_date"
              name="handlingPicker"
              center
              label="处理时效"
              :required="securityItem.checkmust === 'true'"
              :rules="[{ required: securityItem.checkmust === 'true', message: '请选择处理时效' }]"
              :readonly="props.isReadOnly"
              class="defect-field"
            >
              <template #input>
                <XDatePicker
                  v-model="securityItem.f_handle_date"
                  :attr="{ name: '处理时效', formValueFormat: 'YYYY-MM-DD' }"
                  mode="修改"
                  :readonly="props.isReadOnly || safeConfig?.showAndReadonly?.processTime?.readonly"
                  placeholder="请选择处理时效"
                />
              </template>
            </VanField>
          </div>
        </template>
      </SecurityFormItem>
    </template>
  </div>
</template>

<style scoped lang="less">
.x-form-title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  background-color: #fff;
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.defect-section {
  margin: 4px;
  padding: 6px;
  // background-color: #f1f5f9;
  background-color: #fafbfc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
}

.defect-field {
  // margin-bottom: 6px;

  &:last-child {
    margin-bottom: 0;
  }
}
</style>
