<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1400px;" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="计划编号" prop="planNo">
              <el-input v-model="formData.planNo" placeholder="系统自动生成计划编号" :disabled=true />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>




    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">

      <el-tab-pane label="保养范围" name="maintenancePlanScope">
        <MaintenancePlanScopeForm ref="maintenancePlanScopeFormRef" :plan-id="formData.id" />
      </el-tab-pane>

      <el-tab-pane label="保养内容" name="maintenancePlanConsumable">

        <el-form-item label="保养标准" prop="standardId" style="width: 400px; text-align: left; ">
          <el-select
v-model="formData.standardId" placeholder="请选择保养标准"
                     @change="handleStandardChange" :clearable="true" >
            <el-option
                v-for="standard in deviceStandardList"
                :key="standard.id"
                :label="standard.standName"
                :value="standard.id"
            />
          </el-select>
        </el-form-item>

        <MaintenancePlanItemForm ref="maintenancePlanItemFormRef" :plan-id="formData.id" />

        <hr style="margin: 5px 0;"/>

        <MaintenancePlanConsumableForm ref="maintenancePlanConsumableFormRef" :plan-id="formData.id" />
      </el-tab-pane>
      <el-tab-pane label="保养周期" name="maintenancePlanItem">

        <el-row :gutter="20">
          <el-col :sm="12" :md="8">
            <el-form-item label="保养班组" prop="teamId">
              <el-select
v-model="formData.teamId" placeholder="请选择保养班组"
                         @change="handleTeamChange" :clearable="true" >
                <el-option
                    v-for="team in deviceTeamList"
                    :key="team.id"
                    :label="team.teamName"
                    :value="team.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="保养成员" prop="teamStaffIds">
              <el-select
                  v-model="selectedStaff"
                  placeholder="请选择保养成员"
                  multiple
                  @change="handleStaffChange"
              >
                <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.nickname"
                    :value="staff.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="超时提醒人" prop="timeoutReminder">
              <el-select
                  v-model="formData.timeoutReminder"
                  placeholder="请选择超时提醒人"
              >
                <el-option
                    v-for="staff in staffList"
                    :key="staff.id"
                    :label="staff.nickname"
                    :value="staff.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="8">
            <el-form-item label="任务时限" prop="timeoutHour">
              <el-input-number :min="1" v-model="formData.timeoutHour" placeholder="请输入任务执行时间要求(时)" />
            </el-form-item>
          </el-col>
        </el-row>



          <div class="form-section">
          <div class="section-title">周期参数</div>
            <el-row :gutter="20">
            <el-col :sm="12" :md="12">
              <el-form-item label="周期方式" prop="periodType">

                <el-radio-group v-model="formData.periodType">
                  <el-radio
                      v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_MAINTENANCE_PERIOD_TYPE)"
                      :key="dict.value"
                      :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>

              </el-form-item>
            </el-col>
            </el-row>

            <el-row :gutter="20">
            <el-col :sm="12" :md="8">
              <el-form-item label="首次执行时间" prop="firstDate">
                <el-date-picker
                    v-model="formData.firstDate"
                    type="datetime"
                    value-format="x"
                    placeholder="选择首次执行时间"
                    style="width: 100%"
                    @change="handlePeriodChange"
                />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8">
              <el-form-item label="下次执行时间" prop="secondDate">
                <el-date-picker
                    v-model="formData.secondDate"
                    type="datetime"
                    value-format="x"
                    placeholder="选择执行时间"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            </el-row>

            <el-row :gutter="20">
            <el-col :sm="12" :md="8" v-if="formData.periodType==1">
              <el-form-item label="间隔类型" prop="periodOneType">
                <el-radio-group v-model="formData.periodOneType">
                  <el-radio
                      v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_MAINTENANCE_PERIOD_ONE_TYPE)"
                      :key="dict.value"
                      :label="dict.value"
                      @change="handlePeriodChange"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>

              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="8" v-if="formData.periodType==1">
              <el-form-item label="间隔周期" prop="periodOneNum">
                <el-input-number :min="1" v-model="formData.periodOneNum" placeholder="请输入间隔周期" @change="handlePeriodChange" />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="8" v-if="formData.periodType==2" >
              <el-form-item label="按月方式" prop="periodTowType">
                <el-radio-group v-model="formData.periodTowType">
                  <el-radio
                      v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_MAINTENANCE_PERIOD_TOW_TYPE)"
                      :key="dict.value"
                      :label="dict.value"
                      @change="handlePeriodChange"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :sm="12" :md="8" v-if="formData.periodType==2">
              <el-form-item label="月第几天" prop="periodTowTypeDay">
                <el-input-number  :disabled="formData.periodTowType==2" :min="1" :max="28" v-model="formData.periodTowTypeDay" placeholder="请输入月第几天" @change="handlePeriodChange" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :md="8" v-if="formData.periodType==2">
              <el-form-item label="具体时间" prop="periodTowTypeHour">
                <el-input-number :min="0" :max="23" v-model="formData.periodTowTypeHour" placeholder="请输入具体时间（24小时制）" @change="handlePeriodChange" />
              </el-form-item>
            </el-col>
            </el-row>
          </div>
      </el-tab-pane>
    </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>


  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { MaintenancePlanApi, MaintenancePlanVO } from '@/api/device/maintenanceplan'
import { MaintenanceStandardApi, MaintenanceStandardVO} from "@/api/device/maintenancestandard";
import { MaintenanceTeamApi } from '@/api/device/maintenanceteam'
import { getSimpleUserList } from '@/api/system/user'

import MaintenancePlanConsumableForm from './components/MaintenancePlanConsumableForm.vue'
import MaintenancePlanItemForm from './components/MaintenancePlanItemForm.vue'
import MaintenancePlanScopeForm from './components/MaintenancePlanScopeForm.vue'
import {ref} from "vue";
import {InspectionTeamApi} from "@/api/device/inspectionteam";

/** 设备保养计划 表单 */
defineOptions({ name: 'MaintenancePlanForm' })

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 formData = ref({
  id: undefined,
  planNo: undefined,
  planName: undefined,
  standardId: undefined,
  teamId: undefined,
  teamStaffIds: '',
  teamStaffNames: '',
  selectedStaff: [], // 选择的保养班组成员
  timeoutHour: undefined,
  timeoutReminder: undefined,
  firstDate: undefined,
  secondDate: undefined,
  periodType: undefined,
  periodOneType: undefined,
  periodOneNum: undefined,
  periodTowType: undefined,
  periodTowTypeDay: undefined,
  periodTowTypeHour: undefined,
  processInstanceId: undefined,
})
const formRules = reactive({
  planName: [{ required: true, message: '计划名称不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref


/** 子表的表单 */
const subTabsName = ref('maintenancePlanScope')
const maintenancePlanConsumableFormRef = ref()
const maintenancePlanItemFormRef = ref()
const maintenancePlanScopeFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MaintenancePlanApi.getMaintenancePlan(id)

      if (formData.value.teamStaffIds) {
        selectedStaff.value = formData.value.teamStaffIds.split(',').map(id => parseInt(id))
      }
    } finally {
      formLoading.value = false
    }
  }

  await getStandardList();
  await getTeamList();
  await getStaffList();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await maintenancePlanConsumableFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'maintenancePlanConsumable'
    return
  }
  try {
    await maintenancePlanItemFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'maintenancePlanItem'
    return
  }
  try {
    await maintenancePlanScopeFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'maintenancePlanScope'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MaintenancePlanVO
    // 拼接子表的数据
    data.maintenancePlanConsumables = maintenancePlanConsumableFormRef.value.getData()
    data.maintenancePlanItems = maintenancePlanItemFormRef.value.getData()
    data.maintenancePlanScopes = maintenancePlanScopeFormRef.value.getData()
    if (formType.value === 'create') {
      await MaintenancePlanApi.createMaintenancePlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await MaintenancePlanApi.updateMaintenancePlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planNo: undefined,
    planName: undefined,
    standardId: undefined,
    teamId: undefined,
    teamStaffIds: undefined,
    timeoutHour: undefined,
    timeoutReminder: undefined,
    firstDate: undefined,
    secondDate: undefined,
    periodType: undefined,
    periodOneType: undefined,
    periodOneNum: undefined,
    periodTowType: undefined,
    periodTowTypeDay: undefined,
    periodTowTypeHour: undefined,
    processInstanceId: undefined,
  }
  formRef.value?.resetFields()
}

// 查询标准列表
const deviceStandardList = ref([]) // 标准列表
const getStandardList = async () => {
  let result = await MaintenanceStandardApi.getMaintenanceStandardPage({
    pageNo: 1,
    pageSize: 100,
  });
  deviceStandardList.value = result.list || [];
  // console.log(JSON.stringify(deviceStandardList.value));
}
// 选择标准事件，查询标准详情
const handleStandardChange = async (standardId) => {
  if (!standardId){
    return
  }
  formData.value.standardId = standardId;
  // formData.value.standard = await MaintenanceStandardApi.getMaintenanceStandard(standardId);
  let maintenancePlanItems = await MaintenanceStandardApi.getMaintenanceStandardItemListByStandId(standardId);
  let maintenancePlanConsumables = await MaintenanceStandardApi.getMaintenanceStandardConsumableListByStandId(standardId);

  console.log(JSON.stringify(maintenancePlanItems));
  maintenancePlanItemFormRef.value.setData(maintenancePlanItems);
  maintenancePlanConsumableFormRef.value.setData(maintenancePlanConsumables);
}

// 查询班组列表
const deviceTeamList = ref([]) // 标准列表
const getTeamList = async () => {
  let result = await MaintenanceTeamApi.getMaintenanceTeamPage({
    pageNo: 1,
    pageSize: 100,
  });
  deviceTeamList.value = result.list || [];
}
// 选择班组事件，查询班组详情 赋值给保养成员
const handleTeamChange = async (val) => {
  if (!val) {
    // 如果清空了班组选择，则清空班组成员选择
    selectedStaff.value = []
    formData.value.teamStaffIds = undefined
    formData.value.teamStaffNames = undefined
    return
  }

  try {
    // 获取班组详情
    const teamDetail = await MaintenanceTeamApi.getMaintenanceTeam(val)
    // 从班组详情中提取成员信息
    if (teamDetail && teamDetail.teamStaffIds) {
      // 设置选中的成员ID列表（需要将字符串转换为数组）
      selectedStaff.value = teamDetail.teamStaffIds.split(',').map(id => parseInt(id, 10))

      // 设置班组成员ID和名称（直接使用返回的值）
      formData.value.teamStaffIds = teamDetail.teamStaffIds
      formData.value.teamStaffNames = teamDetail.teamStaffNames
    } else {
      // 如果没有成员信息，则清空选择
      selectedStaff.value = []
      formData.value.teamStaffIds = undefined
      formData.value.teamStaffNames = undefined
    }
  } catch (error) {
    message.error('获取班组详情失败')
    // 出错时清空班组成员选择
    selectedStaff.value = []
    formData.value.teamStaffIds = undefined
    formData.value.teamStaffNames = undefined
  }
}

const selectedStaff = ref([]) // 选中的用户
const staffList = ref([])
const getStaffList = async () => {
  try {
    staffList.value = await getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
  }
}
const handleStaffChange = (val) => {
  // 根据选中的用户ID获取对应的用户信息
  const selectedUsers = staffList.value.filter(user => val.includes(user.id))

  // 设置ID字符串（逗号拼接）
  formData.value.teamStaffIds = selectedUsers.map(user => user.id).join(',')

  // 设置名称字符串（逗号拼接）
  formData.value.teamStaffNames = selectedUsers.map(user => user.nickname).join(',')
}

// 选择周期事件，自动计算下次执行时间
const handlePeriodChange = async () => {
  // 获取首次执行时间
  const firstDate = formData.value.firstDate;
  const periodType = formData.value.periodType; // 周期方式 1-年月日间隔 2-按月
  const periodOneType = formData.value.periodOneType; // 年月日间隔周期类型 1-年 2-月 3-日
  const periodOneNum = formData.value.periodOneNum; // 年月日间隔周期
  const periodTowType = formData.value.periodTowType; // 按月方式 1-具体日期 2-月末最后一天
  const periodTowTypeDay = formData.value.periodTowTypeDay; // 按月具体日期 第几天
  const periodTowTypeHour = formData.value.periodTowTypeHour; // 按月具体日期 几时

  // 如果没有首次执行时间，则无法计算下次执行时间
  if (!firstDate) {
    formData.value.secondDate = undefined;
    return;
  }

  const firstDateTime = new Date(firstDate);

  if (periodType === 1) {
    // 年月日间隔方式
    if (periodOneType && periodOneNum) {
      const nextDate = new Date(firstDateTime);
      switch (periodOneType) {
        case 1: // 年
          nextDate.setFullYear(firstDateTime.getFullYear() + periodOneNum);
          break;
        case 2: // 月
          nextDate.setMonth(firstDateTime.getMonth() + periodOneNum);
          break;
        case 3: // 日
          nextDate.setDate(firstDateTime.getDate() + periodOneNum);
          break;
        default:
          break;
      }
      formData.value.secondDate = nextDate.getTime();
    } else {
      formData.value.secondDate = firstDate;
    }
  } else if (periodType === 2) {
    // 按月方式
    if (periodTowType === 1 && periodTowTypeDay && periodTowTypeHour !== undefined) {
      // 按月具体日期
      const nextDate = new Date(firstDateTime);
      nextDate.setMonth(firstDateTime.getMonth() + 1);
      nextDate.setDate(periodTowTypeDay);
      nextDate.setHours(periodTowTypeHour, 0, 0, 0);
      formData.value.secondDate = nextDate.getTime();
    } else if (periodTowType === 2) {
      // 月末最后一天
      const nextDate = new Date(firstDateTime);
      // 下个月的第一天
      nextDate.setMonth(firstDateTime.getMonth() + 1, 1);
      // 前一天即为本月最后一天
      nextDate.setDate(nextDate.getDate() - 1);
      nextDate.setHours(periodTowTypeHour, 0, 0, 0);
      formData.value.secondDate = nextDate.getTime();
    } else {
      formData.value.secondDate = firstDate;
    }
  } else {
    formData.value.secondDate = firstDate;
  }
}

</script>

<style scoped>
.form-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
  margin-bottom: 15px;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}

.el-divider {
  margin: 10px 0;
}

.el-form-item {
  margin-bottom: 15px;
}

.qrcode-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 5px;
}

.qrcode-placeholder {
  color: #909399;
  font-size: 12px;
  text-align: center;
}

:deep(.max-dialog .el-dialog) {
  max-width: 100%;
  height: 100vh;
  margin: 0 !important;
  display: flex;
  flex-direction: column;
}

:deep(.max-dialog .el-dialog__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
}
</style>
