<script setup lang="ts">
import {ref, computed, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import {DynamicTbApi} from '@/api/pressure2/dynamictb'
import {useDictStore} from '@/store/modules/dict'
import dayjs from 'dayjs'
import {
  createPressureInspectionNature,
  updatePressureInspectionNature
} from "@/api/pressure/inspectionNature";
import {updatePressure2InspectionNature} from "@/api/pressure2/inspectionNature";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  editType: {
    type: String,
    default: 'create'
  },
  editId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dictStore = useDictStore()

// 锅炉检验部件类型字典
const getPressureBoilerPartType = computed(() => dictStore.getDictMap['pressure2_boiler_part_type'])

const getPressureEquipmentCategory = computed(() => [{
  value: '-1',
  label: '全部设备',
  children: dictStore.getDictMap['pressure_equipment_category']
}])

// 字典数据
const getPressureInspectionNatureType = ref({
  '200': computed(() => dictStore.getDictMap['pressure_inspection_nature']),
  '300': computed(() => dictStore.getDictMap['pressure_inspection_nature_boiler'])
})

const getPressureEquipType = ref({
  '200': computed(() => dictStore.getDictMap['system_equip_pipe_type']),
  '300': computed(() => dictStore.getDictMap['system_equip_boiler_type'])
})

// 表单相关
const inspectionNatureFormRef = ref()
const inspectionNatureForm = ref({
  inspectionNature: '',
  equipmentCategory: '',
  equipmentType: '',
  templateSaveReqVOList: [] as any[]
})

// 判断是否为电站锅炉内检
const isPowerStationBoiler = computed(() => {
  return inspectionNatureForm.value.equipmentType == '1' && inspectionNatureForm.value.equipmentCategory == '300' && inspectionNatureForm.value.inspectionNature == '100'
})

const inspectionNatureFormRules = ref({
  inspectionNature: [
    {required: true, message: '请选择检验性质', trigger: 'blur'}
  ],
  equipmentCategory: [
    {required: true, message: '请选择设备类别', trigger: 'blur'}
  ],
  equipmentType: [
    {required: true, message: '请选择设备类型', trigger: 'blur'}
  ],
  templateSaveReqVOList: [
    {required: true, message: '请选择关联报告模板', trigger: 'blur'}
  ]
})

const getTemplateNames = computed(() => inspectionNatureForm.value.templateSaveReqVOList.map(x => x.name))

// 报告模板弹窗
const reportTemplateDialog_Boiler = ref(false)
const reportTemplateTableRef = ref()
const reportPageNo = ref(1)
const reportPageSize = ref(10)
const reportTotal = ref(0)
const reportTemplateListSearchForm = ref({})
const reportTemplateList = ref([])

const getPressureReportTemplateType = computed(() => dictStore.getDictMap['pressure_report_template_type'])

const reportColumns = computed(() => ([
  {
    type: 'selection',
    width: 55,
    fieldProps: {
      reserveSelection: true,
      selectable: (row) => {
        return inspectionNatureForm.value.templateSaveReqVOList.findIndex(item => item.templateId === row.id) < 0
      }
    }
  },
  {
    label: '报告编号',
    prop: 'id',
  },
  {
    label: '报告名称',
    prop: 'name',
    search: {
      type: 'input',
      placeholder: '请输入报告名称'
    }
  },
  {
    label: '报告分类',
    prop: 'className',
    search: {
      type: 'select',
      options: [],
      prop: 'classId'
    },
  },
  {
    label: '报告类型',
    prop: 'type',
    render: (row) => {
      return getPressureReportTemplateType.value[row.type]?.label || '未知'
    }
  },
  {
    label: '生效日期',
    prop: 'effectiveDate',
  },
  {
    label: '失效日期',
    prop: 'expiryDate',
  }
]))

// 监听弹窗打开
const handleDialogOpen = async () => {
  if (props.editType === 'edit' && props.editId) {
    await loadDetailInfo()
  } else {
    resetForm()
  }
}

// 加载详情信息
const loadDetailInfo = async () => {
  try {
    const detailInfo = await DynamicTbApi.getPressureInspectionNatureInfoBoiler({id: props.editId})

    inspectionNatureForm.value = {
      ...detailInfo,
      templateSaveReqVOList: detailInfo.templateDetailRespVOList.map(item => ({
        ...item,
        name: item.templateName,
        // 将后端返回的 part 字符串转换为数组
        part: item.part ? (typeof item.part === 'string' ? item.part.split('/').filter(p => p) : (item.part || [])) : []
      }))
    }
  } catch (error) {
    console.error('加载详情失败:', error)
    ElMessage.error('加载详情失败')
  }
}

// 重置表单
const resetForm = () => {
  inspectionNatureForm.value = {
    inspectionNature: '',
    equipmentCategory: '',
    equipmentType: '',
    templateSaveReqVOList: []
  }
  inspectionNatureFormRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  emit('update:modelValue', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await inspectionNatureFormRef.value.validate()

    const params = {
      ...inspectionNatureForm.value,
      templateSaveReqVOList: inspectionNatureForm.value.templateSaveReqVOList.map((item: any) => ({
        id: item.id,
        templateId: item.templateId,
        isDefault: item.isDefault,
        inspectionNatureId: item.inspectionNatureId || (props.editType === 'edit' ? props.editId : undefined),
        part: isPowerStationBoiler.value ? (item.part || []).join('/') : ""
      })),
      id: props.editType === 'edit' ? props.editId : undefined
    }

    const result = props.editType === 'edit' ? await updatePressure2InspectionNature(params) : await createPressureInspectionNature(params)

    if (result) {
      ElMessage.success((props.editType === 'edit' ? '编辑' : '新增') + '成功')
      emit('success')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 显示报告模板列表
const handleShowReportList = () => {
  reportTemplateDialog_Boiler.value = true
  fetchReportTemplateList_Boiler()
}

// 获取报告模板列表
const fetchReportTemplateList_Boiler = async () => {
  const params = {
    pageNo: reportPageNo.value,
    pageSize: reportPageSize.value,
    reportType: 100,
    ...reportTemplateListSearchForm.value
  }
  const result = await DynamicTbApi.getDynamicTbPageInspection(params)
  if (result) {
    reportTemplateList.value = result.list
    reportTotal.value = result.total

    const selectedIds = inspectionNatureForm.value.templateSaveReqVOList.map(item => item.templateId)
    nextTick(() => {
      const tableRef = reportTemplateTableRef.value?.getTableRef()
      if (tableRef) {
        reportTemplateList.value.forEach(row => {
          if (selectedIds.includes(row.id)) {
            tableRef.toggleRowSelection(row, true)
          }
        })
      }
    })
  }
}

// 确认选择报告模板
const handleReportTemplateConfirm = () => {
  const selectedRows = reportTemplateTableRef.value?.getTableRef().getSelectionRows() || []

  selectedRows.forEach(item => {
    const templateIds = inspectionNatureForm.value.templateSaveReqVOList.map(x => x.templateId)
    if (!templateIds.includes(item.id)) {
      inspectionNatureForm.value.templateSaveReqVOList.push({
        templateId: item.id,
        name: item.name,
        effectiveDate: item.effectiveDate,
        expiryDate: item.expiryDate,
        isDefault: '0',
        part: [] // 初始化部件类型数组
      })
    }
  })
}

// 删除报告模板
const handleDeleteReport = (row, index) => {
  inspectionNatureForm.value.templateSaveReqVOList.splice(index, 1)
}

// 清除选中项
const handleClearSelectedItem = () => {
  inspectionNatureForm.value.templateSaveReqVOList = []
}

// 移除标签
const handleRemoveTag = (name) => {
  inspectionNatureForm.value.templateSaveReqVOList = inspectionNatureForm.value.templateSaveReqVOList.filter(item => item.name !== name)
}

</script>

<template>
  <CustomDialog
    :model-value="modelValue"
    :title="(editType === 'edit' ? '编辑' : '添加') + '检验性质'"
    width="1200px"
    :showFooter="false"
    @open="handleDialogOpen"
    @close="handleClose"
  >
    <el-form
      ref="inspectionNatureFormRef"
      :model="inspectionNatureForm"
      :rules="inspectionNatureFormRules"
      style="width: 400px;"
      label-width="110px"
    >
      <el-form-item label="检验性质" prop="inspectionNature">
        <el-select v-model="inspectionNatureForm.inspectionNature" placeholder="请选择检验性质">
          <el-option
            v-for="item in getPressureInspectionNatureType[inspectionNatureForm.equipmentCategory]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属设备" prop="equipmentCategory">
        <el-select
          v-model="inspectionNatureForm.equipmentCategory"
          placeholder="请选择所属设备"
          @change="inspectionNatureForm.equipmentType = ''"
        >
          <el-option
            v-for="item in getPressureEquipmentCategory[0].children"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select v-model="inspectionNatureForm.equipmentType" placeholder="请选择设备类型">
          <el-option
            v-for="item in getPressureEquipType[inspectionNatureForm.equipmentCategory]"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联报告模板" prop="templateSaveReqVOList">
        <el-select
          :model-value="getTemplateNames"
          clearable
          multiple
          @remove-tag="handleRemoveTag"
          @click.stop.prevent="handleShowReportList"
          @clear="handleClearSelectedItem"
          placeholder="请选择关联报告模板"
        />
      </el-form-item>
    </el-form>

    <el-table :data="inspectionNatureForm.templateSaveReqVOList">
      <el-table-column label="检验项目名称" prop="name"/>
      <el-table-column label="是否默认" prop="isDefault">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isDefault"
            active-value="1"
            inactive-value="0"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </template>
      </el-table-column>
      <el-table-column label="部件" prop="part" v-if="isPowerStationBoiler">
        <template #default="scope">
          <el-select
            v-model="scope.row.part"
            multiple
            placeholder="请选择部件"
            style="width: 100%"
          >
            <el-option
              v-for="item in getPressureBoilerPartType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="handleDeleteReport(scope.row, scope.$index)">
            解除关联
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: center; padding-top: 24px;">
      <el-button type="default" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </CustomDialog>

  <!-- 报告模板选择弹窗 -->
  <CustomDialog
    v-model="reportTemplateDialog_Boiler"
    title="报告模板列表"
    width="1200px"
    @confirm="handleReportTemplateConfirm"
  >
    <SmartTable
      ref="reportTemplateTableRef"
      v-model:columns="reportColumns"
      v-model:pageNo="reportPageNo"
      v-model:pageSize="reportPageSize"
      v-model:formData="reportTemplateListSearchForm"
      :data="reportTemplateList"
      :total="reportTotal"
      :refresh="false"
      @on-page-no-change="fetchReportTemplateList_Boiler"
      @on-page-size-change="fetchReportTemplateList_Boiler"
      @on-reset="fetchReportTemplateList_Boiler"
      @on-search="fetchReportTemplateList_Boiler"
      @refresh="fetchReportTemplateList_Boiler"
      :tableProps="{
        height: 500
      }"
    />
  </CustomDialog>
</template>

<style scoped lang="scss">
</style>
