<template>
  <ContentWrap>
    <!--    顶部标题-->
    <div class="topTitle">
      <span class="tab-title">执行计划：{{route.query.sopName}}</span>
      <div class="set-btn" @click="goBack">
        <img src="../../../assets/images/返回.png" alt="" />
        返回
      </div>
    </div>
    <!--    规则设置-->
    <div class="custom-tabs-container">
      <div class="tab-header">
        <span class="tab-title">规则设置</span>
      </div>
    </div>
    <div class="tab-content">
      <el-form
        ref="formRef"
        :model="sopExcuteData"
        :rules="formRules"
        label-width="120px"
      >
        <!-- 启用执行计划 -->
        <el-form-item label="启用执行计划" prop="enableExecutionPlan">
          <el-switch
            v-model="sopExcuteData.enableExecutionPlan"
            size="small"
            :active-value="1"
            :inactive-value="0"
            @change="handleExecutionPlanChange"
          />
        </el-form-item>

        <!-- 执行频率单位 -->
        <el-form-item label="执行频率单位" prop="frequencyUnit">
          <el-radio-group v-model="sopExcuteData.frequencyUnit" @change="handlefrequencyUnitChange">
            <el-radio :value="3">天</el-radio>
            <el-radio :value="2">周</el-radio>
            <el-radio :value="1">月</el-radio>
            <el-radio :value="0">年</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 天 -->
        <el-form-item v-if="sopExcuteData.frequencyUnit == 3" label="执行频率" prop="frequency">
          每
          <el-input-number
            v-model="sopExcuteData.frequency"
            :min="1"
            :max="3650"
            class="mx-4"
            controls-position="right"
          /> 天
        </el-form-item>

        <!-- 周 -->
        <div v-else-if="sopExcuteData.frequencyUnit == 2" style="display:flex">
          <el-form-item label="执行频率" prop="frequency">
            每
            <el-input-number
              v-model="sopExcuteData.frequency"
              :min="1"
              :max="520"
              class="mx-4"
              controls-position="right"
            /> 周
          </el-form-item>
          <el-form-item label="在" prop="timePoint">
            <el-select v-model="sopExcuteData.timePoint" placeholder="选择星期" style="width: 115px">
              <el-option label="星期一" value="星期一" />
              <el-option label="星期二" value="星期二" />
              <el-option label="星期三" value="星期三" />
              <el-option label="星期四" value="星期四" />
              <el-option label="星期五" value="星期五" />
              <el-option label="星期六" value="星期六" />
              <el-option label="星期日" value="星期日" />
            </el-select>
          </el-form-item>
        </div>

        <!-- 月 -->
        <div v-else-if="sopExcuteData.frequencyUnit == 1" style="display:flex">
          <el-form-item label="执行频率" prop="frequency">
            每
            <el-input-number
              v-model="sopExcuteData.frequency"
              :min="1"
              :max="120"
              class="mx-4"
              controls-position="right"
            /> 月
          </el-form-item>
          <el-form-item label="第" prop="timePoint">
            <el-input-number
              v-model="sopExcuteData.timePoint"
              :min="1"
              :max="31"
              class="mx-4"
              controls-position="right"
            /> 日
          </el-form-item>
        </div>

        <!-- 年 -->
        <div v-else-if="sopExcuteData.frequencyUnit == 0"  style="display:flex">
          <el-form-item label="执行频率" prop="frequency">
            每
            <el-input-number
              v-model="sopExcuteData.frequency"
              :min="1"
              :max="10"
              class="mx-4"
              controls-position="right"
            /> 年
          </el-form-item>
          <el-form-item label="第" prop="timePoint">
            <el-input-number
              v-model="sopExcuteData.timePoint"
              :min="1"
              :max="365"
              class="mx-4"
              controls-position="right"
            /> 天
          </el-form-item>
        </div>

        <!-- 作业开始时间 -->
        <el-form-item label="作业开始时间" prop="startTime">
          <el-time-picker
            v-model="sopExcuteData.startTime"
            placeholder="请选择"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          />
        </el-form-item>

        <!-- 作业预估时长 -->
        <el-form-item label="作业预估时长" prop="duration">
          <el-time-picker
            v-model="sopExcuteData.duration"
            placeholder="请选择"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          />
        </el-form-item>

        <!-- 计划终止 -->
        <div style="display:flex">
          <el-form-item label="计划终止" prop="endType">
            <el-select v-model="sopExcuteData.endType" style="width: 115px" @change="handleEndTypeChange">
              <el-option v-for="dict in getStrDictOptions(DICT_TYPE.SOP_PLAN_TERMINATE_TYPE)"
                         :key="dict.value"
                         :label="dict.label"
                         :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="sopExcuteData.endType == 0" label="终止日期" prop="endValue">
            <el-date-picker
              v-model="sopExcuteData.endValue"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择"
              :disabled-date="disabledBeforeToday"
            />
          </el-form-item>
          <el-form-item v-if="sopExcuteData.endType == 2" label="执行次数" prop="endValue">
            <el-input-number
              v-model="sopExcuteData.endValue"
              :min="1"
              :max="10"
              class="mx-4"
              controls-position="right"
            /> 次后
          </el-form-item>
        </div>


        <!-- 非工作日 -->
        <div style="display:flex">
        <el-form-item label="非工作日" prop="nonWorkDay">
          <el-select v-model="sopExcuteData.nonWorkDay" style="width: 115px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SOP_PLAN_NOWORKING)"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="sopExcuteData.nonWorkDay == 2 || sopExcuteData.nonWorkDay == 3" label="顺延天数" prop="nonWorkMoveDay">
          <el-input-number
            v-model="sopExcuteData.nonWorkMoveDay"
            :min="1"
            :max="10"
            class="mx-4"
            controls-position="right"
          /> 工作日
        </el-form-item>
        </div>

        <!-- 按钮 -->
        <div class="btnstyle">
          <el-button plain v-if="ExcuteplanVisible == false" @click="submit">修改</el-button>
          <el-button type="primary" plain v-if="ExcuteplanVisible == true" @click="submit">新建</el-button>
          <el-button plain @click="goBack">取消</el-button>
        </div>
      </el-form>
    </div>
  </ContentWrap>
  <!--  预览计划-->
  <ContentWrap  v-if="tableData.length > 0">
    <div class="tab-header">
      <span class="tab-title">执行计划预览</span>
    </div>
    <!--    表格数据-->
    <div class="tableCon">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="planDay" label="作业日期" width="180" />
        <el-table-column prop="startTime" label="作业开始时间" width="180" />
        <el-table-column prop="duration" label="作业预估时长" />
        <el-table-column prop="workstationName" label="所属区域" />
        <el-table-column prop="machineryName" label="设备/工艺" />
        <el-table-column prop="sopTypeName" label="作业类型" />
      </el-table>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as ExecutePlan from '@/api/sop/executePlan'
import * as SopApi from '@/api/sop'
import { updateSopExecutionPlan } from '@/api/sop/executePlan'
const { t } = useI18n() // 国际化

const router = useRouter()
const route = useRoute()
const message = useMessage() // 消息弹窗
const tableData = ref([])
const formRef = ref(null)
const sopExcuteData = reactive({
  sopId: route.query.id,
  frequencyUnit: 3,
  frequency: '',
  timePoint: null,
  startTime: '',
  duration: '',
  endType: '',
  endValue: '',
  nonWorkDay: '',
  nonWorkMoveDay: '',
  enableExecutionPlan:0,
})
// 校验规则
const formRules = {
  // enableExecutionPlan: [{ required: true, message: '请选择是否启用执行计划', trigger: 'change' }],
  frequencyUnit: [{ required: true, message: '请选择执行频率单位', trigger: 'change' }],
  frequency: [{ required: true, message: '请输入执行频率', trigger: 'blur' }],
  timePoint: [
    {
      required: true,
      message: '请输入时间点',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if ((sopExcuteData.frequencyUnit == 2 || sopExcuteData.frequencyUnit == 1 || sopExcuteData.frequencyUnit == 0) && !value) {
          callback(new Error('请输入时间点'))
        } else {
          callback()
        }
      }
    }
  ],
  startTime: [{ required: true, message: '请选择作业开始时间', trigger: 'change' }],
  duration: [{ required: true, message: '请选择作业预估时长', trigger: 'change' }],
  endType: [{ required: true, message: '请选择计划终止方式', trigger: 'change' }],
  endValue: [
    {
      required: true,
      message: '请输入终止值',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (sopExcuteData.endType == 0 && !value) {
          callback(new Error('请选择终止日期'))
        } else if (sopExcuteData.endType == 2 && !value) {
          callback(new Error('请输入执行次数'))
        } else {
          callback()
        }
      }
    }
  ],
  nonWorkDay: [{ required: true, message: '请选择非工作日处理方式', trigger: 'change' }],
  nonWorkMoveDay: [
    {
      required: true,
      message: '请输入顺延天数',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if ((sopExcuteData.nonWorkDay == 2 || sopExcuteData.nonWorkDay == 3) && !value) {
          callback(new Error('请输入顺延天数'))
        } else {
          callback()
        }
      }
    }
  ]
}


const ExcuteplanVisible = ref(false) // 判断sop执行计划是新增还是修改
// 添加初始化标志位
const isInitialized = ref(false)
// const isPrompt=ref(true)

onMounted(async() => {
  // 数据加载完成后
  isInitialized.value = true
  await getSopExcuteData()
  const data=await SopApi.selectSopById(route.query.id)
  sopExcuteData.enableExecutionPlan= data.enableExecutionPlan
  console.log(route.query.sopName,'sop名称')
})

// 返回
const goBack = () => {
  router.push('/sopm/sop')
}

// 校验是否为闰年
const isLeapYear = (year) => {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}

// 获取某年有效的最大天数
const getValidDayOfYear = (year, dayOfYear) => {
  const maxDay = isLeapYear(year) ? 366 : 365
  return Math.min(dayOfYear, maxDay)
}

// 获取某年某月的最大天数
const getValidDayOfMonth = (year, month, day) => {
  const maxDate = new Date(year, month, 0).getDate()
  return Math.min(day, maxDate)
}

// 自动修正时间点
const handleTimePointChange = () => {
  const { frequencyUnit, frequency, timePoint } = sopExcuteData
  const now = new Date()

  if (frequencyUnit === '0') {
    // 年：从当前年开始 + frequency
    const targetYear = now.getFullYear() + frequency
    const validDay = getValidDayOfYear(targetYear, timePoint)
    sopExcuteData.timePoint = validDay
  }

  if (frequencyUnit === '1') {
    // 月：从当前月开始 + frequency
    const baseMonth = now.getMonth() + 1
    const targetMonth = ((baseMonth - 1 + frequency) % 12) + 1
    const targetYear = now.getFullYear() + Math.floor((baseMonth - 1 + frequency) / 12)
    const validDay = getValidDayOfMonth(targetYear, targetMonth, timePoint)
    sopExcuteData.timePoint = validDay
  }
}

// 是否打开执行计划
const handleExecutionPlanChange = async (val) => {
  console.log(val,'val',val)
  sopExcuteData.enableExecutionPlan = val
}

// 频率单位为周时频率后面选框默认渲染的值
const handlefrequencyUnitChange=()=>{
  if(sopExcuteData.frequencyUnit == 2){
    sopExcuteData.timePoint='星期一'
  }else if(sopExcuteData.frequencyUnit == 1 || sopExcuteData.frequencyUnit == 0){
    sopExcuteData.timePoint=1
  }else{

    sopExcuteData.timePoint=null
  }
}


// 非工作日下拉框值改变
const handlenonWorkMoveDayChange=()=>{
  if(sopExcuteData.nonWorkDay == 2 || sopExcuteData.nonWorkDay == 3){
    sopExcuteData.nonWorkMoveDay=1
    console.log(sopExcuteData.nonWorkMoveDay,'skjwsiojddo')
  }else{
    sopExcuteData.nonWorkMoveDay=''
  }
}

// 计划终止切换时清空后面日期数据
const handleEndTypeChange = (val) => {
  // 切换到 0（终止日期）或 2（执行次数）时，清空 endValue
  if (val == 0 || val == 2) {
    sopExcuteData.endValue = ''
  }
}

// 计划执行日期当前日期之前时间不可选条件判断
const disabledBeforeToday = (time) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 清零时分秒
  return time.getTime() < today.getTime() // 小于今天的禁用
}


// 创建按钮事件
const submit = async () => {
  try {
    // 先做表单校验
    await formRef.value.validate()

    // 新增执行计划
    let data
    let successMessage
    if (sopExcuteData.frequencyUnit == '3') {
      sopExcuteData.timePoint = 0
    }
    if (ExcuteplanVisible.value == true) {
      data = await ExecutePlan.insertSopExecutionPlan(sopExcuteData)
      if(data){
        await getSopExcuteData()
        ExcuteplanVisible.value = false
      }
      successMessage = t('common.createSuccess')
    } else {
      data = await ExecutePlan.updateSopExecutionPlan(sopExcuteData)
      if(data){
        await getSopExcuteData()
      }
      successMessage = t('common.updateSuccess')
      console.log(data, '修改是否成功')
    }
    if (data) {
      message.success(successMessage)
    }
  } catch (error) {
    // console.error('保存失败:', error)
    message.error('保存失败')
  }
}

// 获取sop执行计划数据
const getSopExcuteData = async () => {
  try {
    const excuteList = await ExecutePlan.selectSopExecutionPlanBySopId(route.query.id)
    console.log(excuteList, '有社么数据')
    if (excuteList) {
      Object.assign(sopExcuteData, excuteList)
      tableData.value = excuteList.previewDataList
    }else{
      // 新增
      ExcuteplanVisible.value = true
    }
  } catch (error) {
    console.error('获取失败:', error)
    // if(error.code==902){
    //   // 新增
    //   ExcuteplanVisible.value = true
    //   // isPrompt.value = false //执行计划没有时不提示后端接口消息
    // }
  }
}
console.log(route.query.id, '是否拿到了id')
</script>

<style scoped lang="scss">
.topTitle {
  width: 100%;
  line-height: 40px;
}

.set-btn {
  width: 60px;
  height: 30px;
  border: 1px solid black;
  border-radius: 6px;
  text-align: center;
  line-height: 30px;
  float: right;
  cursor: pointer;
  margin: 10px 0;

  img {
    width: 14px;
    height: 14px;
  }
}

.custom-tabs-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 20px;
}

.tab-header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  padding: 12px 20px;
  border-radius: 4px 4px 0 0;
}

.tab-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

//设置规则
.tab-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  //background-color: #c81818;
  border-radius: 0 0 4px 4px;

  section {
    width: 100%;
    height: 100%;
    margin: 15px 0;
    display: flex;

    span {
      display: inline-block;
      width: 130px;
      //background: #000;
    }
  }

  .btnstyle {
    text-align: right;
  }
}
</style>
