<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-row>
      </el-card>
      <!-- 表格类信息 -->
      <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 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="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="detailDisabled || row.id" v-model="row.remark" placeholder="请输入备注" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="text-center hl-footer">
      <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} 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";

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 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 resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    processDesignType: undefined,
    remark: undefined,
    status: 1,
    projectId: undefined,
    projectSubId: undefined,
    processDesignProgressList: [],
  }
  formRef.value?.resetFields()
}
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)
    } 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 = () => {
  if (formData.value.processDesignProgressList.length>0){
    var element = formData.value.processDesignProgressList[0].progress;
    if (element==100){
      message.error("上报进度已100%,请确认")
      return
    }
  }
  const row = {
    id: undefined,
    processDesignId: undefined,
    progress: undefined,
    blueprintLink: undefined,
    remark: undefined,
    createTime: new Date().getTime(),
    creatorName: userStore.getUser.nickname,
    status: 1,
  }
  row.processDesignId = formData.value.id
  formData.value.processDesignProgressList.unshift(row)
}

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

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

  queryData(currentId.value)
})
</script>
<style scoped lang="less"></style>
