<template>
  <el-card class="hl-card">
    <template #header>
      <span><span v-html="dialogTitle"></span>页</span>
    </template>
    <el-form ref="formRef" label-width="120px" :model="formData" v-loading="formLoading">
      <!-- 基础信息  横向布局 -->
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
        </template>
        <el-row>
          <el-col :span="6">
            <el-form-item label="计划单号" prop="planCode">
              <el-input class="!w-260px" v-model="formData.planCode" :disabled="true" />
              <!-- {{ formData.planCode }} -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目编号" prop="projectCode">
              <!-- {{ formData.projectCode }} -->
              <el-input class="!w-260px" v-model="formData.projectCode" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <!-- {{ formData.customerName }} -->
              <el-input class="!w-260px" v-model="formData.customerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称" prop="projectName">
              <!-- {{ formData.projectName }} -->
              <el-input class="!w-260px" v-model="formData.projectName" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="项目负责人" prop="projectOwnerName">
              <!-- {{ formData.projectOwnerName }} -->
              <el-input class="!w-260px" v-model="formData.projectOwnerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属业务线" prop="businessLine">
              <!-- {{getDictLabel(DICT_TYPE.HELI_BUSINESS_LINE, formData.businessLine)}} -->
              <el-select class="!w-260px" v-model="formData.businessLine" placeholder="请选择所属业务线" :disabled="true">
                        <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HELI_BUSINESS_LINE)" :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性质" prop="property">
              <!-- {{getDictLabel(DICT_TYPE.HELI_PROJECT_PROPERTY, formData.property)}} -->
               <el-select class="!w-250px"  disabled v-model="formData.property" placeholder="请选择性质">
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PROPERTY)" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否紧急" prop="isUrgency">
              <!-- {{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, formData.isUrgency) }} -->
              <el-select class="!w-260px" :disabled="true" v-model="formData.isUrgency" placeholder="请选择是否紧急">
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processDesignType == 'BLUEPRINT_FOUNDRY_TECHNOLOGY'">

          <el-col :span="6">
            <el-form-item label="是否要工艺" prop="hasCraft">
              <!-- {{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, formData.hasCraft) }} -->
               <el-select class="!w-260px" :disabled="true" v-model="formData.hasCraft" placeholder="请选择是否要工艺">
                    <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺负责人" prop="craftOwnerName">
              <!-- {{formData.craftOwnerName}} -->
              <el-input class="!w-260px" v-model="formData.craftOwnerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺开始日期" prop="craftStartDate">
              <!-- {{formatDate(formData.craftStartDate, 'YYYY-MM-DD')}} -->
              <el-date-picker class="!w-260px" v-model="formData.craftStartDate" type="date" placeholder="请选择工艺开始日期" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工艺结束日期" prop="craftStartDate">
              <!-- {{formatDate(formData.craftEndDate, 'YYYY-MM-DD')}} -->
              <el-date-picker class="!w-260px" v-model="formData.craftEndDate" type="date" placeholder="请选择工艺结束日期" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processDesignType == 'BLUEPRINT_3D'">
          <el-col :span="6">
            <el-form-item label="3D负责人" prop="threeDimOwnerName">
              <!-- {{ formData.threeDimOwnerName }} -->
              <el-input class="!w-260px" v-model="formData.threeDimOwnerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="3D结束日期" prop="threeDimDate">
              <!-- {{formatDate(formData.threeDimDate, 'YYYY-MM-DD')}} -->
              <el-date-picker class="!w-260px" v-model="formData.threeDimDate" type="date" placeholder="请选择3D结束日期" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目名称" prop="projectSubName">
              <!-- {{formData.projectSubName}} -->
              <el-input class="!w-260px" v-model="formData.projectSubName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目编号" prop="projectSubCode">
              <!-- {{formData.projectSubCode}} -->
              <el-input class="!w-260px" v-model="formData.projectSubCode" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processDesignType == 'BLUEPRINT_2D'">
          <el-col :span="6">
            <el-form-item label="2D负责人" prop="twoDimOwnerName">
              <!-- {{ formData.twoDimOwnerName }} -->
              <el-input class="!w-260px" v-model="formData.twoDimOwnerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="2D结束日期" prop="twoDimDate">
              <!-- {{formatDate(formData.twoDimDate, 'YYYY-MM-DD')}} -->
              <el-date-picker class="!w-260px" v-model="formData.twoDimDate" type="date" placeholder="请选择2D结束日期" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目名称" prop="projectSubName">
              <!-- {{formData.projectSubName}} -->
              <el-input class="!w-260px" v-model="formData.projectSubName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目编号" prop="projectSubCode">
              <!-- {{formData.projectSubCode}} -->
              <el-input class="!w-260px" v-model="formData.projectSubCode" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="processDesignType == 'BLUEPRINT_WORKBLANK'">
          <el-col :span="6">
            <el-form-item label="毛坯负责人" prop="blankOwnerName">
              <!-- {{ formData.blankOwnerName }} -->
              <el-input class="!w-260px" v-model="formData.blankOwnerName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="毛坯结束日期" prop="blankDate">
              <!-- {{formatDate(formData.blankDate, 'YYYY-MM-DD')}} -->
              <el-date-picker class="!w-260px" v-model="formData.blankDate" type="date" placeholder="请选择毛坯结束日期" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目名称" prop="projectSubName">
              <!-- {{formData.projectSubName}} -->
              <el-input class="!w-260px" v-model="formData.projectSubName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="子项目编号" prop="projectSubCode">
              <!-- {{formData.projectSubCode}} -->
              <el-input class="!w-260px" v-model="formData.projectSubCode" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="生产状态" prop="planCode">
              <el-select v-model="formData.planStatus" placeholder="生产状态" clearable class="!w-260px" disabled>
                <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PLAN_STATUS)" :key="dict.value"
                           :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
         <!-- <el-col :span="6"  v-if="(formData.isDelay == null || formData.isDelay == 0) ">
             <el-button style="margin-left: 10%;" type="danger"  @click="openDelay">延期</el-button>

          </el-col> -->
           <el-col :span="6" >
             <el-form-item label="设计工时" prop="delayReason">
                <el-input class="!w-260px" :placeholder="getWorkTime(1)" :disabled="true"/>
              </el-form-item>
             </el-col>
           <el-col :span="6">
             <el-form-item label="设计工期" prop="delayReason">
                  <el-input class="!w-260px" :placeholder="getWorkTime(2)" :disabled="true"/>
              </el-form-item>
             </el-col>
               <el-col :span="6" >
             <el-button v-if="formData.isOverProcess == null || formData.isOverProcess == 0" style="margin-left: 10%;" type="warning"  @click="openDelay">延期</el-button>
                </el-col>
          <el-col :span="12" v-if="delayDialog || formData.isDelay">
             <el-form-item label="延期原因" prop="delayReason">
              <el-input
                v-model="formData.delayReason"
                :rows="2"
                :disabled="!delayDialog"
                @blur="(e) => delaySubmit(e)"
                type="textarea"
                placeholder="延期原因"
              />
              </el-form-item>
             </el-col>
        </el-row>
      </el-card>
      <!--延期弹框-->
      <!-- <el-dialog
          v-model="delayDialog"
          title="延期信息填写"
          :before-close="handleClose"
        >
          <span>
             <el-input
                v-model="formData.delayReason"
                :rows="2"
                type="textarea"
                placeholder="延期原因"
              />
          </span>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="delayDialog = false">取消</el-button>
              <el-button type="primary" @click="delaySubmit">
                确认
              </el-button>
            </span>
          </template>
        </el-dialog> -->
      <!-- 表格类信息 -->
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">进度汇报</span>
        </template>
        <el-row>
          <el-col v-if="active != 'detail'">
             <el-button  v-if="formData.isOverProcess == null || formData.isOverProcess == 0" class="hl-addbutton" type="primary" size="large" @click="onAddItem">开始</el-button>
            <el-button  v-if="formData.isOverProcess == null || formData.isOverProcess == 0" style="margin-left: 30px;" type="warning" size="large" @click="sendItem()">推送</el-button>
   <el-button v-if="formData.isOverProcess == null || formData.isOverProcess == 0" style="margin-left: 30px;" type="danger"  size="large"   @click="overProcess">{{ overbuttonName }}</el-button>

            <!-- <el-button class="hl-addbutton" type="primary" size="large" @click="onAddItem">新增</el-button> -->
          </el-col>
          <el-col>
            <el-card class="hl-incard">
              <el-form ref="processDesignProgressFormRef" :model="formData.processDesignProgressList" :rules="subFormRules" v-loading="subFormLoading" label-width="0">
                <el-table :data="formData.processDesignProgressList" class="hl-table">
                  <el-table-column label="序号" align="center" type="index" width="80" fixed />
                  <el-table-column label="开始时间" align="center" prop="beginTime" :formatter="dateFormatter" min-width="200">
                                        <template #header>开始时间</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.beginTime`"  class="mb-0px!">
                  <!-- <el-input-number min="0" max="100" class="!w-240px" :disabled="detailDisabled || row.id" v-model="row.progress" placeholder="请输入进度百分比" @change="verify1($index)"/>-->                    
                            <el-date-picker  :disabled-date="(date) => disabledDate1(date, row)" @change="(e) => beginTimeChange(e,row)" :disabled=" row.isOver == 1  || formData.isOverProcess == 1" :formatter="dateFormatter" v-model="row.beginTime" type="datetime" placeholder="选择开始日期"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="结束时间" align="center" prop="endTime" :formatter="dateFormatter" min-width="200">
                    <template #header>结束时间</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.endTime`"  class="mb-0px!">
                  <!-- <el-input-number min="0" max="100" class="!w-240px" :disabled="detailDisabled || row.id" v-model="row.progress" placeholder="请输入进度百分比" @change="verify1($index)"/>-->                    
                            <el-date-picker  :disabled-date="(date) => disabledDate(date, row)" @change="(e) => endTimeChange(e,row)" :disabled=" row.isOver == 1  || formData.isOverProcess == 1" :formatter="dateFormatter" v-model="row.endTime" type="datetime" placeholder="选择结束日期"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="已做时间(小时)" align="center" prop="workTime" width="280">
                    <template #header>已做时间(小时)</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.workTime`"  class="mb-0px!">
                        <el-input-number  :max="row.maxTime" :precision="2" class="!w-240px" :disabled=" row.isOver == 1 || formData.isOverProcess == 1" v-model="row.workTime" placeholder="请输入已做时间"/>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <!--2025.06.01改-->
                  <!-- <el-table-column label="上报时间" align="center" prop="createTime" :formatter="dateFormatter" min-width="200"/>
                  <el-table-column label="上报人" prop="creatorName" min-width="100"/>
                  <el-table-column label="进度百分比（%）" align="center" prop="progress" width="280">
                    <template #header> <span class="hl-table_header">*</span>进度百分比（%） </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.progress`" :rules="subFormRules.progress" class="mb-0px!">
                        <el-input-number min="0" max="100" class="!w-240px" :disabled="detailDisabled || row.id" v-model="row.progress" placeholder="请输入进度百分比" @change="verify1($index)"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="图纸链接"  prop="progress" min-width="280">
                    <template #header> <span class="hl-table_header">*</span>图纸链接 </template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.blueprintLink`" :rules="subFormRules.blueprintLink" class="mb-0px!">
                        <el-input :disabled="detailDisabled || row.id" v-model="row.blueprintLink" placeholder="请输入图纸链接" />
                      </el-form-item>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="备注" prop="remark" min-width="280">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
                        <el-input :disabled="row.hasNext || row.isOver == 1 || formData.isOverProcess == 1" v-model="row.remark" placeholder="请输入备注" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                   <el-table-column fixed="right" label="操作" align="center" min-width="160">
                    <template #default="scope">
                      <el-button
v-if="scope.row.isOver == 0 && active != 'detail'"
                        link
                        type="danger"
                        
                        @click="overRow(scope.row)"
                      >
                        结束
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <!-- <div class="hl-footer text-center">
      <el-button @click="goback" size="large">取 消</el-button>
      <el-button v-if="active != 'detail'" @click="submitForm('SAVE')" type="success" :disabled="formLoading" size="large">保 存</el-button>
    </div> -->
  </el-card>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import {dateFormatter, formatDate,dateFormatter1} from "@/utils/formatTime";
import {ref} from "vue";
import * as ProcessDesignApi from "@/api/heli/processdesign";
import { inject } from 'vue'
import {useUserStore} from "@/store/modules/user";
import {useCommonStore} from "@/store/modules/common";
import {verify} from "node:crypto";
import { delay, fromPairs, now } from 'lodash-es';
import { FolderOpened } from '@element-plus/icons-vue/dist/types';

defineOptions({ name: 'ProcessDesignDetail' })

const reload = inject('reload')
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()

const active = toRef(commonStore.getStore('active'))
const currentId = toRef(commonStore.getStore('id'))
const processDesignType = toRef(commonStore.getStore('processDesignType'))

const formLoading = ref(false)
const dialogTitle = ref('')
const detailDisabled = ref(false)
const flag = ref(false)
const delayDialog = ref(false)
const formData = ref({
  id: undefined,
  planId: undefined,
  processDesignType: undefined,
  remark: undefined,
  status: 1,
  projectId: undefined,
  projectSubId: undefined,
  processDesignProgressList: [],
})

const formRef = ref() // 表单 Ref
const processDesignProgressFormRef = ref()
const overbuttonName = ref('')
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    processDesignType: undefined,
    remark: undefined,
    status: 1,
    projectId: undefined,
    projectSubId: undefined,
    processDesignProgressList: [],
  }
  formRef.value?.resetFields()
}



const disabledDate = (time: Date,row : any) => {
 const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1); // 设置为明天
  tomorrow.setHours(23, 59, 59, 999); 
  if(row.beginTime != null){
      const beginDate = new Date(row.beginTime);

  return time.getTime() < beginDate.getTime() || time.getTime() > tomorrow.getTime();
  }else{
    return  time.getTime() > tomorrow.getTime();
  }
}
const disabledDate1 = (time: Date,row : any) => {
 const today = new Date();
 today.setHours(23, 59, 59, 999); 
  return  time.getTime() > today.getTime();

}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('是否退出?')
    .then(() => {
			delayDialog.value=false;
    })
    .catch(() => {
    })
}
const getWorkTime = (type) =>{
  var beginTime = null ;
  var endTime = null
  if(processDesignType.value == 'BLUEPRINT_WORKBLANK'){
    if(formData.value.blankDate != null && formData.value.startBlankDate ){
        beginTime = formData.value.startBlankDate;
        endTime  = formData.value.blankDate 
    }

  }
  if(processDesignType.value == 'BLUEPRINT_2D'){
    if(formData.value.twoDimDate != null && formData.value.startTwoDimDate ){
              beginTime = formData.value.startTwoDimDate;
        endTime  = formData.value.twoDimDate 
    }
  }
    if(processDesignType.value == 'BLUEPRINT_3D'){
    if(formData.value.threeDimDate != null && formData.value.startThreeDimDate != null){
              beginTime = formData.value.startThreeDimDate;
        endTime  = formData.value.threeDimDate; 

    }
  }
  if(processDesignType.value == 'BLUEPRINT_FOUNDRY_TECHNOLOGY'){
    if(formData.value.craftStartDate != null && formData.value.craftEndDate != null ){
              beginTime = formData.value.craftStartDate;
        endTime  = formData.value.craftEndDate 
    
    }
  }


  if(beginTime != null &&  endTime != null){
            const start = new Date(beginTime ).getTime();
        const end = new Date(endTime).getTime();
        const diffTime = Math.abs(end - start);
        var day =  Math.floor(diffTime / (1000 * 60 * 60 * 24));
    if(type == 1){
        return day * 8 + '小时';

    }else{
        return day +'天'
    }
  }else{return ''
  }
}
const endTimeChange = (e , row) =>{
  if(e == null ){
    row.workTime = null
    row.maxTime = row.workTime;
  }else{
      var endTime =  new Date(e);
      if(row.beginTime != null){
        if(new Date(row.beginTime).getTime() > endTime.getTime()){
          row.workTime  = null
          message.error("开始时间不能大于结束时间,请确认!")
        }else{
          var timeDiff = endTime.getTime() -row.beginTime;
          row.workTime = timeDiff / (1000 * 60 * 60);
          row.maxTime = row.workTime;
        }

      }else{
        row.workTime  = null
            row.maxTime = row.workTime;
      }
  }
}
const beginTimeChange = (e , row) =>{
  if(e == null ){
    row.workTime = null
    row.maxTime = row.workTime;
  }else{
      var beginTime =  new Date(e);
      if(row.endTime != null){
        if(new Date(row.endTime).getTime() < beginTime.getTime()){
          row.workTime  = null
          message.error("开始时间不能大于结束时间,请确认!")
        }else{
          var timeDiff = new Date(row.endTime).getTime() -beginTime.getTime();
          row.workTime = timeDiff / (1000 * 60 * 60);
          row.maxTime = row.workTime;
        }
      }else{
        row.workTime  = null
            row.maxTime = row.workTime;
      }
  }
}
const delaySubmit = async(event) =>{
  if(formData.value.delayReason == null || formData.value.delayReason.replaceAll(' ','') == ''){
       message.error("延期原因不得为空,请确认!")
      return;
  }
  formData.value.isDelay = 1;
  formData.value.delayTime = (new Date()).getTime()
  await submitForm('SAVE');
}
const openDelay = () =>{
  var date =  new Date();
  if(processDesignType.value == 'BLUEPRINT_WORKBLANK'){
    if(formData.value.blankDate != null ){
      if(formData.value.blankDate > date.getTime()){
         message.error("当前日期为正常生产周期,未达到延期条件,请确认!")
         return
      }
    }else{
       message.error("毛坯结束时间为空!请确认!")
         return
    }
  }
  if(processDesignType.value == 'BLUEPRINT_2D'){
    if(formData.value.twoDimDate != null ){
      if(formData.value.twoDimDate > date.getTime()){
         message.error("当前日期为正常生产周期,未达到延期条件,请确认!")
         return
      }
    }else{
       message.error("2D结束时间为空!请确认!")
         return
    }
  }
    if(processDesignType.value == 'BLUEPRINT_3D'){
    if(formData.value.threeDimDate != null ){
      if(formData.value.threeDimDate > date.getTime()){
         message.error("当前日期为正常生产周期,未达到延期条件,请确认!")
         return
      }
    }else{
       message.error("3D结束时间为空!请确认!")
         return
    }
  }
  if(processDesignType.value == 'BLUEPRINT_FOUNDRY_TECHNOLOGY'){

    if(formData.value.craftEndDate != null ){
      if(formData.value.craftEndDate > date.getTime()){
         message.error("当前日期为正常生产周期,未达到延期条件,请确认!")
         return
      }
    }else{
       message.error("工艺结束时间为空!请确认!")
         return
    }
  }
  delayDialog.value = true;

}
const overRow = async( row :any) =>{
    if(row.beginTime == null ){
     message.error("开始时间不能为空!请确认!")
     return
  }
  if(row.endTime == null ){
     row.endTime =   new Date().getTime()
    var timeDiff = row.endTime -row.beginTime;

    // 将毫秒转换为小时
    row.workTime = timeDiff / (1000 * 60 * 60);
    row.maxTime = row.workTime;
    // row.workTime = row.endTime - row.
  }
  if(new Date(row.beginTime) > new Date(row.endTime)){
     message.error("开始时间不能大于结束时间!请确认!")
     return
  }
   if(row.workTime == null 
  ){
     message.error("已做时间不能为空!请确认")
     return
  }
  row.isOver = 1;
 await submitForm('SAVE');
  //更新一下这条数据的状态
}
const overProcess = () =>{
  if(formData.value.processDesignProgressList != null && formData.value.processDesignProgressList.length > 0){
    for (let index = 0; index <  formData.value.processDesignProgressList.length; index++) {
      var item = formData.value.processDesignProgressList[index];
      if(!item.hasNext){
        if(item.endTime == null ){
              message.error("结束时间不能为空!请确认!")
          return
        }
        if(item.workTime == null){
              message.error("已做时间不能为空!请确认")
              return
        }
      }
      item.isOver = 1;   
   }
  }else{
    message.error("至少进行一次进度汇报！")
    return
  }
    ElMessageBox.confirm('是否结束该项目?')
    .then( async () => {
      await submitForm('SAVE');
			 await ProcessDesignApi.over(formData.value.id)
       await queryData(formData.value.id)
      message.success("修改成功！")

    })
    .catch(() => {
    })
}
const sendItem = async() =>{
  //推送最新的一条,如果备注为空提示备注为空不能推送
  if(formData.value.processDesignProgressList != null && formData.value.processDesignProgressList.length > 0){
    var senIndex = 0;//推送的消息第几天,规则:
    /**
     * 推送最新一条数据，内容为：客户简称+项目名称+子项目名+备注内容。
推送条件：
报工后，点击保存，然后推送菜单有效，
1，要求先保证，推送需要判断备注不能为空。报警提示

     */
    for (let index = 0; index <  formData.value.processDesignProgressList.length; index++) {
      var item = formData.value.processDesignProgressList[index];
      if(!item.hasNext){
        senIndex = index;
          if(item.beginTime == null){
              message.error("开始时间不能为空!请确认!")
          return
        }
        if(item.endTime == null){
              message.error("结束时间不能为空!请确认!")
          return
        }
        if(item.workTime == null){
              message.error("已做时间不能为空!请确认")
              return
        }
        if(item.remark == null || item.remark == ''){
              message.error("推送备注不能为空!请确认")
              return
        }
      }
      item.isOver = 1   
   }
   //先保存
   await submitForm('SAVE');
   //调用推送方法
  }else{
       message.error("至少添加一条数据后才能推送!请确认!")
  }
}
const subFormLoading = ref(false) // 子表单的加载中
const subFormRules = reactive({
  // progress: [{ required: true, message: '进度百分比(%)不能为空', trigger: 'blur' }],
  // blueprintLink: [{ required: true, message: '图纸链接不能为空', trigger: 'blur' }],
})

const queryData = async (id?: number) => {
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProcessDesignApi.getProcessDesign(id)
      formData.value.processDesignProgressList = await ProcessDesignApi.getProcessDesignProgressListByProcessDesignId(id)
      if( formData.value.processDesignProgressList != null &&  formData.value.processDesignProgressList.length > 0){
        var maxTime = null;
        if(formData.value.processDesignProgressList.length == 1){
            formData.value.processDesignProgressList[0].hasNext = false;
            if(formData.value.processDesignProgressList[0].endTime != null && formData.value.processDesignProgressList[0].endTime != ''){
              formData.value.processDesignProgressList[0].maxTime = (formData.value.processDesignProgressList[0].endTime - formData.value.processDesignProgressList[0].beginTime)/ (1000 * 60 * 60);
            }
        } else{
          var maxIndex = 0;
          for (let index = 0; index <  formData.value.processDesignProgressList.length; index++) {
            var item = formData.value.processDesignProgressList[index];
            if(item.endTime != null && item.endTime != ''){
              item.maxTime = (item.endTime - item.beginTime)/ (1000 * 60 * 60);
            }
            if(maxTime == null){
              maxIndex = index;
              maxTime = item.createTime;
              item.hasNext = false;
            }else{
              if(item.createTime > maxTime){
                formData.value.processDesignProgressList[maxIndex].hasNext = true;
                maxIndex  = index;
                item.hasNext = false;
              }else{
                item.hasNext = true;
              }
            }   
            
         }
        }    
      } 
    } finally {
      formLoading.value = false
    }
  }
}

const submitForm = async (operate) => {
  // if (formData.value.processDesignProgressList.length>1){
  //     var  Current = formData.value.processDesignProgressList[0].progress;
  //     var  previous = formData.value.processDesignProgressList[1].progress;
  //     if (Current<previous){
  //       message.error("本次上报进度"+Current+"%小于上次上报进度"+previous+"%,请确认")
  //       return
  //     }
  //   }


  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  await processDesignProgressFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProcessDesignApi.ProcessDesignVO
    let processDesignId;
    if (!formData.value.id) {
      processDesignId = await ProcessDesignApi.createProcessDesign(data)
    } else {
      processDesignId = await ProcessDesignApi.updateProcessDesign(data)
    }
    message.success(t('common.operationSuccess'))
    commonStore.setStore('active', 'update');
    commonStore.setStore('id', processDesignId);
    reload()
  } finally {
    formLoading.value = false
  }
}

/** 新增按钮操作 */
const onAddItem = async() => {
  //条件修改：没有时间就不填
    var date =  new Date();
  if(processDesignType.value == 'BLUEPRINT_WORKBLANK'){
    if(formData.value.blankDate != null ){
      if(formData.value.blankDate < date.getTime()){
         if(formData.value.isDelay == null || formData.value.isDelay == 0){
            message.error("当前任务已超期,请延期后重试!")
           return
         }
      }
    }else{
      //  message.error("毛坯结束时间为空!请确认!")
      //    return
    }
  }
  if(processDesignType.value == 'BLUEPRINT_2D'){
    if(formData.value.twoDimDate != null ){
      if(formData.value.twoDimDate < date.getTime()){
         if(formData.value.isDelay == null || formData.value.isDelay == 0){
            message.error("当前任务已超期,请延期后重试!")
           return
         }
        
      }
    }else{
      //  message.error("2D结束时间为空!请确认!")
      //    return
    }
  }
    if(processDesignType.value == 'BLUEPRINT_3D'){
    if(formData.value.threeDimDate != null ){
      if(formData.value.threeDimDate < date.getTime()){
          if(formData.value.isDelay == null || formData.value.isDelay == 0){
            message.error("当前任务已超期,请延期后重试!")
           return
         }
      }
    }else{
      //  message.error("3D结束时间为空!请确认!")
      //    return
    }
  }
  if(processDesignType.value == 'BLUEPRINT_FOUNDRY_TECHNOLOGY'){
    console.log(formData.value.craftEndDate)
    if(formData.value.craftEndDate != null ){
      console.log(date.getTime())
      console.log(formData.value.craftEndDate)
      if(formData.value.craftEndDate < date.getTime()){
          if(formData.value.isDelay == null || formData.value.isDelay == 0){
            message.error("当前任务已超期,请延期后重试!")
           return
         }
      }
    }else{
      //  message.error("工艺结束时间为空!请确认!")
      //    return
    }
  }


  if (formData.value.processDesignProgressList != null && formData.value.processDesignProgressList.length>0){
    for ( var i = 0 ; i < formData.value.processDesignProgressList.length ; i++){
      var item = formData.value.processDesignProgressList[i];
      if(item.isOver == 0){
        message.error("上一项进度未结束汇报!请确认!")
        return;
      }
        // if(item.endTime == null ){
        //     message.error("结束时间不能为空!请确认!")
        //     return
        //   }
        //   if(item.workTime == null 
        //   ){
        //     message.error("已做时间不能为空!请确认")
        //     return
        //   }
    }
  }



  const row = {
    id: undefined,
    processDesignId: undefined,
    progress: undefined,
    blueprintLink: undefined,
    remark: '',
    createTime: date.getTime(),
    beginTime:date.getTime(),
    endTime:undefined,
    isOver:0,
    workTime:undefined,
    creatorName: userStore.getUser.nickname,
    status: 1,
  }
  row.processDesignId = formData.value.id
  formData.value.processDesignProgressList.unshift(row)
  await submitForm('SAVE');
}

const goback = () => {
  router.back()
}

onMounted(() => {
  dialogTitle.value = t('action.' + active.value)
  if ('detail' == active.value) {
    detailDisabled.value = true
  }

  queryData(currentId.value)
   if(processDesignType.value == 'BLUEPRINT_WORKBLANK'){
     overbuttonName.value = '毛坯项目完结'
  }
  if(processDesignType.value == 'BLUEPRINT_2D'){
     overbuttonName.value = '2D项目完结'
  }
    if(processDesignType.value == 'BLUEPRINT_3D'){
    overbuttonName.value = '3D项目完结'
  }
  if(processDesignType.value == 'BLUEPRINT_FOUNDRY_TECHNOLOGY'){
    overbuttonName.value='铸造项目完结'
  }
})
</script>
<style scoped lang="less"></style>
