<template>
	<el-card class="hl-card" style="position: relative">
		<template #header>
			<span><span v-html="dialogTitle"></span>页</span>
		</template>
		<div class="abstatus">
			<img src="/src/assets/imgs/status/status16.png" v-if="formData.orderStatus == 16" alt="" />
			<img src="/src/assets/imgs/status/status3.png" v-else-if="formData.orderStatus == 3" alt="" />
			<img src="/src/assets/imgs/status/status8.png" v-else-if="formData.orderStatus == 8" alt="" />
			<div v-else-if="formData.orderStatus == 32">
				<div v-if="query.active != 'detailArchive'" class="shipments">
					<div v-if="formData.deliveryStatus == 3">
						<span class="shipmentsfont" style="margin-left:50px">已发货</span>
					</div>

					<div v-else class="shipments">
						<span
v-if="betweenDay(new Date(), new Date(formData.projectEndTime)) == -1"
							class="shipmentsfont">距交货还有{{ betweenDay(new Date(), new Date(formData.projectEndTime)) + 1 }}天
						</span>
						<span
v-else-if="betweenDay(new Date(), new Date(formData.projectEndTime)) < -1"
							class="shipmentsfont">距交货还有{{ betweenDay(new Date(), new Date(formData.projectEndTime)) + 1 }}天
						</span>
						<span
v-else
							class="shipmentsfont">距交货还有{{ betweenDay(new Date(), new Date(formData.projectEndTime)) + 1 }}天
						</span>

					</div>
					<img src="/src/assets/imgs/status/status32.png" alt="" />
				</div>
				<img v-else src="/src/assets/imgs/status/status32.png" alt="" />
			</div>
			<img src="/src/assets/imgs/status/status64.png" v-else-if="formData.orderStatus == 64" alt="" />
		</div>
		<el-form ref="formRef" :model="formData" :rules="formRules" label-width="160px" 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="12">
						<el-row>
							<el-col :span="12">
								<el-row>
									<el-col :span="24">
										<el-form-item label="项目编号" prop="code">
											<el-input
v-if="query.active != 'detailArchive'" disabled
												v-model="formData.code" class="!w-250px" placeholder="系统自动生成" />
											<el-input
v-else disabled v-model="formData.snapshotCode" class="!w-250px"
												placeholder="系统自动生成" />
										</el-form-item>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="提出部门" prop="businessDeptId">
											<el-tree-select
class="!w-250px" v-model="formData.businessDeptId"
												:data="deptList" :props="defaultProps" check-strictly node-key="id"
												clearable placeholder="请选择提出部门"
												:disabled="alterDisabled || detailDisabled || priceDisabled" />
										</el-form-item>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="项目名称" prop="projectName">
											<el-input
class="!w-250px" :disabled="alterDisabled || detailDisabled || priceDisabled"
												v-model="formData.projectName" placeholder="请输入项目名称" />
										</el-form-item>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="项目开始日期" prop="projectStartTime">
											<el-date-picker
class="!w-250px" v-model="formData.projectStartTime"
												type="date" value-format="x" placeholder="选择项目开始日期"
												:disabled="alterDisabled || detailDisabled || priceDisabled" />
										</el-form-item>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">

										<el-form-item label="首付款" prop="shouFuKuan">
											<div style="display: flex; align-items: center">
												<el-input-number
v-model="formData.shouFuKuan"
													:disabled="detailDisabled || formData.hasPrice == 0"
													placeholder="请输入首付款" @blur="handleBlur" :controls="false" :min="0"
													:precision="6" style="width: 150px"
													:class="{ 'alter-class': fieldHasAlter('price') }" />
												<el-input
													v-model="formData.shouFuKuanBiLi" @blur="handleBlurBL"
													placeholder="比例" style="width: 100px"
													:class="{ 'alter-class': fieldHasAlter('currency') }">%</el-input>
											</div>
										</el-form-item>

									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">

										<el-form-item label="第三笔款" prop="threeFuKuan">
											<div style="display: flex; align-items: center">
												<el-input-number
v-model="formData.threeFuKuan"
													:disabled="detailDisabled || formData.hasPrice == 0"
													placeholder="输入第三笔付款" @blur="threehandleBlur" :controls="false"
													:min="0" :precision="6" style="width: 150px"
													:class="{ 'alter-class': fieldHasAlter('price') }" />
												<el-input
													v-model="formData.threeFuKuanBiLi" @blur="threehandleBlurBL"
													placeholder="比例" style="width: 100px"
													:class="{ 'alter-class': fieldHasAlter('currency') }" />
											</div>
										</el-form-item>

									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">

										<el-form-item label="第五笔款" prop="fiveFuKuan">
											<div style="display: flex; align-items: center">
												<el-input-number
v-model="formData.fiveFuKuan"
													:disabled="detailDisabled || formData.hasPrice == 0"
													placeholder="输入第三笔付款" @blur="fivehandleBlur" :controls="false"
													:min="0" :precision="6" style="width: 150px"
													:class="{ 'alter-class': fieldHasAlter('price') }" />
												<el-input
													v-model="formData.fiveFuKuanBiLi" @blur="fivehandleBlurBL"
													placeholder="比例" style="width: 100px"
													:class="{ 'alter-class': fieldHasAlter('currency') }" />
											</div>
										</el-form-item>

									</el-col>
								</el-row>
							</el-col>
							<el-col :span="12">
								<el-row>
									<el-col :span="24">
										<el-form-item label="单据日期" prop="orderTime">
											{{
                        query.active != 'detailArchive'
                          ? formatDate(formData.orderTime, 'YYYY-MM-DD')
                          : formatDate(formData.snapshotOrderTime, 'YYYY-MM-DD')
                      }}
										</el-form-item>
									</el-col>
								</el-row>

								<el-row>
									<el-col :span="24">
										<el-form-item label="业务员" prop="businessMan">
                      <el-tree-select
class="!w-250px" v-model="formData.businessMan"
                                      :data="userList" :props="userProps" check-strictly node-key="id"
                                      clearable placeholder="请选择业务员" filterable
                                      :disabled="alterDisabled || detailDisabled || priceDisabled" />
<!--											<UserSelect :disabled="alterDisabled || detailDisabled || priceDisabled"-->
<!--												v-model="formData.businessMan" @update:newValue="handleSelectedUser" />-->

										</el-form-item>
									</el-col>
								</el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目简码" prop="projectNameSim">
                      <el-input
                        class="!w-250px" :disabled="alterDisabled || detailDisabled || priceDisabled"
                        v-model="formData.projectNameSim" placeholder="请输入项目简码" />
                    </el-form-item>
                  </el-col>
                </el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="项目结束日期" prop="projectEndTime">
											<el-date-picker
class="!w-250px"
												:class="{ 'alter-class': fieldHasAlter('projectEndTime') }"
												v-model="formData.projectEndTime" type="date" value-format="x"
												placeholder="选择项目结束日期" :disabled="detailDisabled || priceDisabled" />
											<span
style="position: absolute; left: 0; top: 30px"
												v-if="formData.projectStartTime && formData.projectEndTime">{{
                          ' 共计' +
                          betweenDay1(
                            new Date(formData.projectStartTime),
                            new Date(formData.projectEndTime)
                          ) +
                          '天'
                        }}</span>
										</el-form-item>
									</el-col>
								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="首付款预计时间" prop="shouFuKuanTime">
											<el-date-picker
class="!w-250px" v-model="formData.shouFuKuanTime"
												type="date" value-format="x" placeholder="选择日期"
												:disabled="detailDisabled || formData.hasPrice == 0" />
										</el-form-item>
									</el-col>

								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="第三笔款预计时间" prop="threeFuKuanTime">
											<el-date-picker
class="!w-250px" v-model="formData.threeFuKuanTime"
												type="date" value-format="x" placeholder="选择日期"
												:disabled="detailDisabled || formData.hasPrice == 0" />
										</el-form-item>
									</el-col>

								</el-row>
								<el-row>
									<el-col :span="24">
										<el-form-item label="第五笔款预计时间" prop="fiveFuKuanTime">
											<el-date-picker
class="!w-250px" v-model="formData.fiveFuKuanTime"
												type="date" value-format="x" placeholder="选择日期"
												:disabled="detailDisabled || formData.hasPrice == 0" />
										</el-form-item>
									</el-col>
								</el-row>
							</el-col>
						</el-row>


						<el-row>
							<el-col :span="24">
								<el-form-item label="可引用的原有技术" prop="referenceTechnology">
									<el-input
class="!w-703px" :disabled="detailDisabled || priceDisabled"
										v-model="formData.referenceTechnology" placeholder="请输入可引用的原有技术"
										:class="{ 'alter-class': fieldHasAlter('referenceTechnology') }" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-col>

					<el-col :span="6">
<!--						<el-row>-->
<!--							<el-col :span="24">-->
<!--								<el-form-item label="单据状态" prop="orderStatus">-->
<!--									{{ getDictLabel(DICT_TYPE.HELI_PROJECT_ORDER_STATUS, formData.orderStatus) }}-->
<!--								</el-form-item>-->
<!--							</el-col>-->
<!--						</el-row>-->
            <el-row>
              <el-col :span="24">
                <el-form-item label="性质" prop="property">
                  <el-select
                    class="!w-250px" :class="{ 'alter-class': fieldHasAlter('property') }"
                    :disabled="detailDisabled || priceDisabled" 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-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="客户名称" prop="customerId">

									<ClientSelect
:disabled="alterDisabled || detailDisabled || priceDisabled"
										v-model="formData.customerId" @update:new-value="handleSelectedClient" />
								</el-form-item>
							</el-col>
						</el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="所属业务线" prop="businessLine">
                  <el-select
                    class="!w-250px" v-model="formData.businessLine"
                    placeholder="请选择所属业务线" :disabled="alterDisabled || detailDisabled">
                    <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-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="是否有价格" prop="hasPrice">
									<el-radio-group
v-model="formData.hasPrice" :disabled="detailDisabled || priceDisabled"
										:class="{ 'alter-class': fieldHasAlter('hasPrice') }">
										<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)"
											:key="dict.value" :label="dict.value">
											{{ dict.label }}
										</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>


						<el-row>
							<el-col :span="24">

								<el-form-item label="第二笔款" prop="twoFuKuan">
									<div style="display: flex; align-items: center">
										<el-input-number
v-model="formData.twoFuKuan"
											:disabled="detailDisabled || formData.hasPrice == 0" placeholder="输入第二笔付款"
											@blur="twohandleBlur" :controls="false" :min="0" :precision="6"
											style="width: 150px" :class="{ 'alter-class': fieldHasAlter('price') }" />
										<el-input
											v-model="formData.twoFuKuanBiLi" @blur="twohandleBlurBL" placeholder="比例"
											style="width: 100px"
											:class="{ 'alter-class': fieldHasAlter('currency') }" />
									</div>
								</el-form-item>

							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">

								<el-form-item label="第四笔款" prop="fourFuKuan">
									<div style="display: flex; align-items: center">
										<el-input-number
v-model="formData.fourFuKuan"
											:disabled="detailDisabled || formData.hasPrice == 0" placeholder="输入第四笔付款"
											@blur="fourhandleBlur" :controls="false" :min="0" :precision="6"
											style="width: 150px" :class="{ 'alter-class': fieldHasAlter('price') }" />
										<el-input
											v-model="formData.fourFuKuanBiLi" @blur="fourhandleBlurBL" placeholder="比例"
											style="width: 100px"
											:class="{ 'alter-class': fieldHasAlter('currency') }" />
									</div>
								</el-form-item>

							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="第六笔款" prop="sixFuKuan">
									<div style="display: flex; align-items: center">
										<el-input-number
v-model="formData.sixFuKuan"
											:disabled="detailDisabled || formData.hasPrice == 0" placeholder="输入第六笔付款"
											@blur="sixhandleBlur" :controls="false" :min="0" :precision="6"
											style="width: 150px" :class="{ 'alter-class': fieldHasAlter('price') }" />
										<el-input
											v-model="formData.sixFuKuanBiLi" @blur="sixhandleBlurBL" placeholder="比例"
											style="width: 100px"
											:class="{ 'alter-class': fieldHasAlter('currency') }" />
									</div>
								</el-form-item>
							</el-col>
						</el-row>



						<el-row>
							<el-col :span="24">
								<el-form-item label="是否紧急" prop="isUrgency">
									<el-radio-group
v-model="formData.isUrgency" :disabled="detailDisabled || priceDisabled"
										:class="{ 'alter-class': fieldHasAlter('isUrgency') }">
										<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)"
											:key="dict.value" :label="dict.value">
											{{ dict.label }}
										</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
					</el-col>
					<el-col :span="6">
						<el-row>
							<el-col :span="24">
								<el-form-item label="发货状态" prop="deliveryStatus">
									{{ getDictLabel(DICT_TYPE.HELI_DELIVERY_STATUS, formData.deliveryStatus) }}
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="合同号" prop="contractNo">
									<el-input
class="!w-250px" :disabled="detailDisabled || priceDisabled"
										v-model="formData.contractNo" placeholder="请输入合同号" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="模具图号" prop="blueprintNo">
									<el-input
class="!w-250px" :disabled="alterDisabled || detailDisabled || priceDisabled"
										v-model="formData.blueprintNo" placeholder="请输入模具图号" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="含税价格（元）" prop="price">
									<div style="display: flex; align-items: center">
										<el-input-number
v-model="formData.price"
											:disabled="detailDisabled || formData.hasPrice == 0" placeholder="请输入价格"
											:controls="false" :min="0" :precision="6" style="width: 150px"
											:class="{ 'alter-class': fieldHasAlter('price') }" />
										<el-select
:disabled="detailDisabled" v-model="formData.currency"
											placeholder="请选择币种" style="width: 100px"
											:class="{ 'alter-class': fieldHasAlter('currency') }">
											<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.HELI_CURRENCY)"
												:key="dict.value" :label="dict.label" :value="dict.value" />
										</el-select>
									</div>
								</el-form-item>
							</el-col>
						</el-row>


						<el-row>
							<el-col :span="24">
								<el-form-item label="第二笔预计时间" prop="twoFuKuanTime">
									<el-date-picker
class="!w-250px" v-model="formData.twoFuKuanTime" type="date"
										value-format="x" placeholder="选择日期"
										:disabled="detailDisabled || formData.hasPrice == 0" />
								</el-form-item>
							</el-col>

						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="第四笔款预计时间" prop="fourFuKuanTime">
									<el-date-picker
class="!w-250px" v-model="formData.fourFuKuanTime" type="date"
										value-format="x" placeholder="选择日期"
										:disabled="detailDisabled || formData.hasPrice == 0" />
								</el-form-item>
							</el-col>

						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="第六笔款预计时间" prop="sixFuKuanTime">
									<el-date-picker
class="!w-250px" v-model="formData.sixFuKuanTime" type="date"
										value-format="x" placeholder="选择日期"
										:disabled="detailDisabled || formData.hasPrice == 0" />
								</el-form-item>
							</el-col>
						</el-row>

						<el-row>
							<el-col :span="24">
								<el-form-item label="是否已变更" prop="hasAlter">
									<el-select class="!w-250px" v-model="formData.hasAlter" placeholder="请选择" disabled>
										<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-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="检验要求" prop="qualityRequirement">
							<el-input
class="!w-703px" :disabled="detailDisabled || priceDisabled " type="textarea"
								v-model="formData.qualityRequirement" placeholder="请输入检验要求" show-word-limit
								maxlength="200" :class="{ 'alter-class': fieldHasAlter('qualityRequirement') }" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="备注" prop="remark" :disabled="detailDisabled">
							<el-input
class="!w-703px" :disabled="detailDisabled || priceDisabled" type="textarea"
								v-model="formData.remark" placeholder="请输入检验备注" show-word-limit maxlength="200"
								:class="{ 'alter-class': fieldHasAlter('remark') }" />
						</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 :span="6">
						<el-form-item label="有无合同" prop="hasContract">
							<el-radio-group
:disabled="detailDisabled || priceDisabled" v-model="formData.hasContract"
								:class="{ 'alter-class': fieldHasAlter('hasContract') }">
								<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)"
									:key="dict.value" :label="dict.value">
									{{ dict.label }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="有无技术协议" prop="hasTechnologyProtocol">
							<el-radio-group
:disabled="detailDisabled || priceDisabled" v-model="formData.hasTechnologyProtocol"
								:class="{ 'alter-class': fieldHasAlter('hasTechnologyProtocol') }">
								<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)"
									:key="dict.value" :label="dict.value">
									{{ dict.label }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="有无图纸/数模" prop="hasBlueprint">
							<el-radio-group
:disabled="detailDisabled || priceDisabled" v-model="formData.hasBlueprint"
								:class="{ 'alter-class': fieldHasAlter('hasBlueprint') }">
								<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)"
									:key="dict.value" :label="dict.value">
									{{ dict.label }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="" label-width="0" prop="blueprintRemark">
							<el-input
v-model="formData.blueprintRemark" placeholder="请输入图纸/数模说明" :disabled="
                  detailDisabled || (formData.hasBlueprint == 0 && (formData.blueprintRemark = '')) || priceDisabled
                " :class="{ 'alter-class': fieldHasAlter('blueprintRemark') }" />
						</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>
						<el-card class="hl-incard">
							<el-col v-if="'update,create,alter'.indexOf(query.active) > -1">
								<el-button class="hl-addbutton" type="primary" size="large" @click="onAddItem">新增
								</el-button>
							</el-col>
							<el-form
ref="projectOrderSubFormRef" :model="formData.projectOrderSubs"
								:rules="subFormRules" v-loading="subFormLoading" label-width="0">
								<el-table
:data="formData.projectOrderSubs" class="hl-table"
									:row-class-name="({row,rowIndex}) => { return fieldHasAlterInRow('NEW', row) ? 'alter-class1' : ''}">
									<el-table-column label="序号" type="index" width="80" />
									<el-table-column min-width="200" align="center">
										<template #header> <span class="hl-table_header">*</span>子项目名称 </template>
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.name`" :rules="subFormRules.name"
												class="mb-0px!">
												<el-input
:disabled="detailDisabled || row.id || priceDisabled" v-model="row.name"
													placeholder="请输入子项目名称" />
											</el-form-item>
										</template>
									</el-table-column>
                  <el-table-column min-width="200" align="center">
                    <template #header> <span class="hl-table_header">*</span>子项目简码 </template>
                    <template #default="{ row, $index }">
                      <el-form-item
                        :prop="`${$index}.nameSim`" :rules="subFormRules.nameSim"
                        class="mb-0px!">
                        <el-input
                          :disabled="detailDisabled || row.id || priceDisabled" v-model="row.nameSim"
                          placeholder="请输入子项目简码" />
                      </el-form-item>
                    </template>
                  </el-table-column>
									<el-table-column label="设备型号" min-width="150" align="center">
										<!-- <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.deviceModel`" :rules="subFormRules.deviceModel" class="mb-0px!">
                        <el-input :disabled="detailDisabled || (alterDisabled && row.id)" v-model="row.deviceModel" placeholder="请输入设备型号" />
                      </el-form-item>
                    </template> -->
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.deviceModel`"
												:rules="subFormRules.deviceModel" class="mb-0px!">
												<EquipSelect
v-model="row.deviceModel"
													@update:new-value="handleSelectedequip($index, $event)"
													:disabled="detailDisabled || (alterDisabled && row.id) || priceDisabled" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="125" align="center">
										<template #header> <span class="hl-table_header">*</span>数量 </template>
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.amount`" :rules="subFormRules.amount"
												class="mb-0px!">
												<el-input-number
style="width: 100%" :disabled="auditDisabled&&(detailDisabled || priceDisabled)"
													v-model="row.amount" placeholder="请输入数量" :min="0" :precision="0"
													:class="{ 'alter-class': fieldHasAlterInRow('amount', row) }" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="125" align="center">
										<template #header> <span class="hl-table_header">*</span>单位 </template>
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.unit`" :rules="subFormRules.unit"
												class="mb-0px!">
												<el-select
:disabled="detailDisabled || priceDisabled" v-model="row.unit"
													placeholder="请选择单位"
													:class="{ 'alter-class': fieldHasAlterInRow('unit', row) }">
													<el-option
														v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)"
														:key="dict.value" :label="dict.label" :value="dict.value" />
												</el-select>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column min-width="150" align="center">
										<template #header> <span class="hl-table_header">*</span>材质 </template>
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.compositionId`"
												:rules="subFormRules.compositionId" class="mb-0px!">
												<CompositionSelect
v-model="row.compositionId"
													@update:new-value="handleSelectedcomposition($index, $event)"
													:disabled="detailDisabled || priceDisabled"
													:class="{ 'alter-class': fieldHasAlterInRow('compositionId', row) }" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="备注" min-width="180" align="center">
										<template #default="{ row, $index }">
											<el-form-item
:prop="`${$index}.remark`" :rules="subFormRules.remark"
												class="mb-0px!">
												<el-input
:disabled="detailDisabled || priceDisabled" v-model="row.remark"
													placeholder="请输入备注"
													:class="{ 'alter-class': fieldHasAlterInRow('remark', row) }" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="操作" align="center" width="150">
										<template #default="scope">
											<el-button
												v-if="'update,create'.indexOf(query.active) > -1 && !formData.hasAlter"
												link type="danger" size="small"
												@click.prevent="onDeleteItem(scope.$index)">
												删除
											</el-button>
										</template>
									</el-table-column>
								</el-table>
							</el-form>
						</el-card>
					</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>
						<el-card class="hl-incard" :class="{ 'alter-class': fieldHasAlter('attachments') }">
							<el-col v-if="'update,create,alter'.indexOf(query.active) > -1">
								<el-upload
v-if="formData.hasContract == 1" ref="contractUploadRef"
									:file-list="contractUploadFiles" multiple :action="uploadUrl" :headers="{
                    Authorization: 'Bearer ' + getAccessToken(),
                    'tenant-id': getTenantId()
                  }" name="files" :show-file-list="false" :auto-upload="false" :data="contractUploadData"
									:on-change="contractUploadChange" :on-error="handleError"
									:on-success="handleSuccess" :before-upload="before" class="upload-file-uploader">
									<el-button type="primary">
										<Icon icon="ep:upload-filled" />上传合同
									</el-button>
								</el-upload>
								<el-upload
v-if="formData.hasTechnologyProtocol == 1" ref="protocolUploadRef" multiple
									:action="uploadUrl" :headers="{
                    Authorization: 'Bearer ' + getAccessToken(),
                    'tenant-id': getTenantId()
                  }" name="files" :show-file-list="false" :auto-upload="false" :data="protocolUploadData"
									:on-change="protocolUploadChange" :on-error="handleError"
									:on-success="handleSuccess" :before-upload="before" class="upload-file-uploader">
									<el-button type="primary">
										<Icon icon="ep:upload-filled" />上传技术协议
									</el-button>
								</el-upload>
							</el-col>
							<el-table
:data="formData.attachments" v-loading.fullscreen.lock="uploading"
								element-loading-text="附件上传中..." element-loading-background="rgba(122, 122, 122, 0.6)"
								class="hl-table">
								<el-table-column prop="name" label="文件名称" align="center" />
								<el-table-column prop="businessFileType" label="文件类型" align="center">
									<template #default="scope">
										{{
                      getDictLabel(DICT_TYPE.HELI_BUSINESS_FILE_TYPE, scope.row.businessFileType)
                    }}
									</template>
								</el-table-column>
								<el-table-column
prop="createTime" align="center" label="上传时间"
									:formatter="dateFormatter" />
								<el-table-column label="操作" align="center">
									<template #default="scope">
										<el-button
v-if="'update,create,alter'.indexOf(query.active) > -1" link
											type="danger" size="small"
											@click="handleDeleteAttachment(scope.$index, scope.row.businessFileType)">
											删除
										</el-button>
										<el-button
v-if="!!scope.row.id" link type="primary" size="small"
											@click="downloadAttachment(scope.row.name, scope.row.url)">
											下载
										</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-card>
					</el-col>
				</el-row>
			</el-card>
			<el-card class="hl-card-info" v-if="query.active != 'detailArchive'">
				<template #header>
					<div class="hl-card-info-icona"></div><span class="hl-card-info-text">操作日志</span>
				</template>
				<el-row>
					<el-col>
						<el-card class="hl-incard">
							<el-table
v-if="formData && formData.operateLogs" :data="formData.operateLogs"
								class="hl-table" :style="{ height: formData.operateLogs.length > 10 ? '450px' : '' }">
								<el-table-column prop="type" label="操作" align="center">
									<template #default="scope">
										{{ getDictLabel(DICT_TYPE.SYSTEM_OPERATE_TYPE, scope.row.type) }}
									</template>
								</el-table-column>
								<el-table-column prop="userNickname" label="操作人" align="center" />
								<el-table-column
label="操作时间" align="center" prop="startTime" width="220"
									:formatter="dateFormatter" />
								<el-table-column prop="content" label="操作意见" align="center" />
							</el-table>
						</el-card>
					</el-col>
				</el-row>
			</el-card>
		</el-form>
		<div class="hl-footer text-center">
			<el-button @click="() => router.back()" size="large">取 消</el-button>
			<el-button
v-if="'update,create'.indexOf(query.active) > -1 && formData.orderStatus <= 4"
				@click="submitForm('SAVE')" type="success" size="large" :disabled="saveDisabled">保 存</el-button>
      <el-button
v-if="'price'.indexOf(query.active) > -1"
                 @click="submitForm('PRICE')" type="success" size="large">录 入</el-button>
			<el-button
v-if="'update,create'.indexOf(query.active) > -1 && formData.orderStatus < 8"
				@click="submitForm('SUBMIT_AUDIT')" type="primary" size="large" :disabled="submitDisabled">送 审</el-button>
			<el-button
v-if="query.active == 'audit' && formData.orderStatus == 8" @click="submitForm('AUDIT')"
				type="primary" size="large">审 核</el-button>
			<el-button
v-if="query.active == 'approve' && formData.orderStatus == 16" @click="submitForm('APPROVE')"
				type="primary" size="large">批 准</el-button>
			<el-button
v-if="query.active == 'alter' && formData.orderStatus == 32" @click="submitForm('ALTER')"
				type="danger" size="large">发起变更</el-button>
			<el-button
v-if="
          'audit,approve'.indexOf(query.active) > -1 &&
          (formData.orderStatus == 8 || formData.orderStatus == 16)
        " @click="activeOpinionDialogVisible = true" type="danger" size="large">打 回</el-button>
			<el-button
v-if="query.active == 'terminate' && formData.orderStatus == 32" @click="submitForm('TERMINATE')"
				type="danger" size="large">直接终止</el-button>
		</div>
	</el-card>

	<el-dialog v-model="activeOpinionDialogVisible" title="打回原因" width="30%" center>
		<el-input
type="textarea" v-model="formData.activeOpinion" placeholder="请输入打回原因" show-word-limit
			maxlength="200" />
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="activeOpinionDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm('REPULSE') && (activeOpinionDialogVisible = false)">确认打回
				</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
	import {
		inject
	} from 'vue'
	import {
		getIntDictOptions,
		getStrDictOptions,
		DICT_TYPE,
		getDictLabel
	} from '@/utils/dict'
	import * as ProjectOrderApi from '@/api/heli/projectorder'
  import {
    betweenDay, betweenDay1,
    dateFormatter,
    formatDate
  } from '@/utils/formatTime'
  import {
    defaultProps,
    handleTree, userProps
  } from '@/utils/tree'
	import * as DeptApi from '@/api/system/dept'
	import * as UserApi from '@/api/system/user'
	import * as CustomerApi from '@/api/heli/customer/index'
	import * as CompositionApi from '@/api/heli/composition/index'
	import {
		getAccessToken,
		getTenantId
	} from '@/utils/auth'
	import {
		UploadUserFile
	} from 'element-plus'
	import {
		deleteFileLogic,
		downloadFile,
		getFilePage
	} from '@/api/infra/file'
	import {
		propTypes
	} from '@/utils/propTypes'
	import download from '@/utils/download'
	import {
		useUserStore
	} from '@/store/modules/user'
	import {
		getUserProfile
	} from '@/api/system/user/profile'
	import {
		getOperateLogPage
	} from '@/api/system/operatelog'
	import UserSelect from '@/views/heli/hlvuestyle/userSelect.vue'
	import CompositionSelect from '@/views/heli/hlvuestyle/compositionSelect.vue'
	import EquipSelect from '@/views/heli/hlvuestyle/equipSelect.vue'
	import ClientSelect from '@/views/heli/hlvuestyle/clientSelect.vue'
  import request from "@/config/axios";
  import {getDeptId} from "@/api/system/user";

	const {
		t
	} = useI18n() // 国际化
	const message = useMessage() // 消息弹窗
	const {
		query
	} = useRoute()
	const router = useRouter()
	const reload: any = inject('reload')
	const activeOpinionDialogVisible = ref(false) // 审批意见弹窗
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		code: undefined,
		orderStatus: 4,
		deliveryStatus: 1,
		businessDeptId: undefined,
		customerId: undefined,
		projectName: undefined,
    projectNameSim:undefined,
		businessLine: undefined,
		blueprintNo: undefined,
		hasPrice: 1,
		price: undefined,
		currency: '1',
		projectStartTime: undefined,
		projectEndTime: undefined,
		isUrgency: 0,
		property: 1,
		referenceTechnology: undefined,
		hasAlter: 0,
		lastAlterTime: undefined,
		qualityRequirement: undefined,
		remark: undefined,
		hasContract: 0,
		hasTechnologyProtocol: 0,
		hasBlueprint: 0,
		blueprintRemark: undefined,
		status: 1,
		businessMan: undefined,
		createTime: new Date(),
		projectOrderSubs: [],
		attachments: [],
		operateLogs: [],
		contractNo: undefined,
		active: '',
		activeOpinion: '',
		isSnapshot: 0,
		snapshotId: undefined,
		snapshotCode: undefined,
		orderTime: new Date(),
		snapshotOrderTime: undefined,
		alterFieldNames: [],
		shouFuKuan: undefined,
		shouFuKuanBiLi: undefined,
		threeFuKuan: undefined,
		threeFuKuanBiLi: undefined,
		fiveFuKuan: undefined,
		fiveFuKuanBiLi: undefined,
		threeFuKuanTime: undefined,
		fiveFuKuanTime: undefined,
		shouFuKuanTime: undefined,
		twoFuKuan: undefined,

		twoFuKuanBiLi: undefined,

		twoFuKuanTime: undefined,
		fourFuKuan: undefined,

		fourFuKuanBiLi: undefined,

		fourFuKuanTime: undefined,

		sixFuKuan: undefined,

		sixFuKuanBiLi: undefined,

		sixFuKuanTime: undefined,

		sumMoney:undefined,
		sumBl:undefined
	})
	const formRules = reactive({
		businessDeptId: [{
			required: true,
			message: '提出部门不能为空',
			trigger: 'blur'
		}],
		customerId: [{
			required: true,
			message: '客户名称不能为空',
			trigger: 'blur'
		}],
		projectName: [{
			required: true,
			message: '项目名称不能为空',
			trigger: 'blur'
		}],
    projectNameSim: [{
      required: true,
      message: '项目简码不能为空',
      trigger: 'blur'
    }],
		businessLine: [{
			required: true,
			message: '所属业务线不能为空',
			trigger: 'change'
		}],
		hasPrice: [{
			required: true,
			message: '是否有价格不能为空',
			trigger: 'blur'
		}],
		projectStartTime: [{
			required: true,
			message: '项目开始日期不能为空',
			trigger: 'blur'
		}],
		projectEndTime: [{
			required: true,
			message: '项目结束日期不能为空',
			trigger: 'blur'
		}],
		isUrgency: [{
			required: true,
			message: '是否紧急不能为空',
			trigger: 'blur'
		}],
		property: [{
			required: true,
			message: '性质不能为空',
			trigger: 'blur'
		}],
		hasAlter: [{
			required: true,
			message: '是否已变更不能为空',
			trigger: 'blur'
		}],
		hasContract: [{
			required: true,
			message: '有无合同不能为空',
			trigger: 'blur'
		}],
		hasTechnologyProtocol: [{
			required: true,
			message: '有无技术协议不能为空',
			trigger: 'blur'
		}],
		hasBlueprint: [{
			required: true,
			message: '有无图纸/数模不能为空',
			trigger: 'blur'
		}],
		status: [{
			required: true,
			message: '状态,1表示正常，2表示禁用不能为空',
			trigger: 'blur'
		}],
		businessMan: [{
			required: true,
			message: '业务员不能为空',
			trigger: 'blur'
		}]
	})
	const formRef = ref() // 表单 Ref
	const subFormLoading = ref(false) // 子表单的加载中
	const subFormRules = reactive({
		name: [{
			required: true,
			message: '子项目名称不能为空',
			trigger: 'blur'
		}],
    nameSim: [{
      required: true,
      message: '子项目简码不能为空',
      trigger: 'blur'
    }],
		amount: [{
			required: true,
			message: '数量不能为空',
			trigger: 'blur'
		}],
		unit: [{
			required: true,
			message: '单位不能为空',
			trigger: 'blur'
		}],
		compositionId: [{
			required: true,
			message: '材质不能为空',
			trigger: 'blur'
		}],
		status: [{
			required: true,
			message: '状态,1表示正常，2表示禁用不能为空',
			trigger: 'blur'
		}]
	})
	//首付款算比例
	const handleBlur = (event) => {
		console.log("首付款")

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.shouFuKuan = undefined;
			return;
		}
		;
		if (formData.value.shouFuKuan > 0) {
			let bollen = sumBl();
			//判断是否超出合同比例
			if(!bollen){
				jsEndMoney();
				formData.value.shouFuKuan = formData.value.price;
				formData.value.shouFuKuanBiLi = 100;
				return;
			}
				formData.value.shouFuKuanBiLi = ((formData.value.shouFuKuan / formData.value.price) * 100).toFixed(2);

		} else {
			formData.value.shouFuKuanBiLi = undefined;

		}


		// 可以在这里进行例如数据保存等操作
	};

	//比例算首付款
	const handleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.shouFuKuan = undefined;
			return;
		}
		;
		if (formData.value.shouFuKuanBiLi > 0) {

			formData.value.shouFuKuan = ((formData.value.shouFuKuanBiLi / 100) * formData.value.price).toFixed(2);
			let bollen = sumBl();
			//判断是否超出合同比例
			if(!bollen){
				jsEndMoney();
				formData.value.shouFuKuan = formData.value.price;
				formData.value.shouFuKuanBiLi = 100;
				return;
			}
		} else {
			formData.value.shouFuKuan = undefined;

		}
	};
	//第三笔付款算比例
	const threehandleBlur = (event) => {
		;
		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.threeFuKuan = undefined;
			return;
		}
		if (formData.value.twoFuKuan > 0) {

			if (formData.value.threeFuKuan > 0) {
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.threeFuKuan,formData.value.threeFuKuanBiLi);
					formData.value.threeFuKuan = formData.value.sumMoney;
					formData.value.threeFuKuanBiLi = formData.value.sumBl;
					return;
				}
				formData.value.threeFuKuanBiLi = ((formData.value.threeFuKuan / formData.value.price) * 100).toFixed(
				2);
			} else {
				formData.value.threeFuKuanBiLi = undefined;
			}
		} else {
			message.error('请先填写第二笔付款金额！');
			formData.value.threeFuKuan = undefined;
		}
	};
	//比例算第三笔付款
	const threehandleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.threeFuKuanBiLi = undefined;
			return;
		}
		if (formData.value.twoFuKuan > 0) {
			if (formData.value.threeFuKuanBiLi > 0) {
				formData.value.threeFuKuan = ((formData.value.threeFuKuanBiLi / 100) * formData.value.price).toFixed(
				2);
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.threeFuKuan,formData.value.threeFuKuanBiLi);
					formData.value.threeFuKuan = formData.value.sumMoney;
					formData.value.threeFuKuanBiLi = formData.value.sumBl;
					return;
				}
			} else {
				formData.value.threeFuKuan = undefined;

			}
		} else {
			message.error('请先填写第二笔付款金额！');
			formData.value.threeFuKuanBiLi = undefined;
		}
	};



	//第五笔付款算比例
	const fivehandleBlur = (event) => {
		;
		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.fiveFuKuan = undefined;
			return;
		}
		if (formData.value.fourFuKuan > 0) {
			if (formData.value.fiveFuKuan > 0) {
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.fiveFuKuan,formData.value.fiveFuKuanBiLi);
					formData.value.fiveFuKuan = formData.value.sumMoney;
					formData.value.fiveFuKuanBiLi = formData.value.sumBl;
					return;
				}
				formData.value.fiveFuKuanBiLi = ((formData.value.fiveFuKuan / formData.value.price) * 100).toFixed(2);
			} else {
				formData.value.fiveFuKuanBiLi = undefined;
			}
		} else {
			message.error('请先填写第四笔付款金额！');
			formData.value.fiveFuKuan = undefined;
		}
	};
	//比例算第五笔付款
	const fivehandleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.fiveFuKuanBiLi = undefined;
			return;
		}
		if (formData.value.fourFuKuan > 0) {
			if (formData.value.fiveFuKuanBiLi > 0) {
				formData.value.fiveFuKuan = ((formData.value.fiveFuKuanBiLi / 100) * formData.value.price).toFixed(2);
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.fiveFuKuan,formData.value.fiveFuKuanBiLi);
					formData.value.fiveFuKuan = formData.value.sumMoney;
					formData.value.fiveFuKuanBiLi = formData.value.sumBl;
					return;
				}
			} else {
				formData.value.fiveFuKuan = undefined;

			}
		} else {
			message.error('请先填写第四笔付款金额！');
			formData.value.fiveFuKuanBiLi = undefined;
		}
	};



	//第二笔付款算比例
	const twohandleBlur = (event) => {
		;
		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.twoFuKuan = undefined;
			return;
		}
		if (formData.value.shouFuKuan > 0) {
			if (formData.value.twoFuKuan > 0) {
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.twoFuKuan,formData.value.twoFuKuanBiLi);
					formData.value.twoFuKuan = formData.value.sumMoney;
					formData.value.twoFuKuanBiLi = formData.value.sumBl;
					return;
				}
				formData.value.twoFuKuanBiLi = ((formData.value.twoFuKuan / formData.value.price) * 100).toFixed(2);
			} else {
				formData.value.twoFuKuanBiLi = undefined;
			}
		} else {
			message.error('请先填写首付款金额！');
			formData.value.twoFuKuan = undefined;
		}
	};
	//比例算第二笔付款
	const twohandleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.twoFuKuanBiLi = undefined;
			return;
		}
		if (formData.value.shouFuKuan > 0) {
			if (formData.value.twoFuKuanBiLi > 0) {
				formData.value.twoFuKuan = ((formData.value.twoFuKuanBiLi / 100) * formData.value.price).toFixed(2);
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.twoFuKuan,formData.value.twoFuKuanBiLi);
					formData.value.twoFuKuan = formData.value.sumMoney;
					formData.value.twoFuKuanBiLi = formData.value.sumBl;
					return;
				}
			} else {
				formData.value.twoFuKuan = undefined;

			}
		} else {
			message.error('请先填写首付款金额！');
			formData.value.twoFuKuanBiLi = undefined;
		}
	};


	//第四笔付款算比例
	const fourhandleBlur = (event) => {
		;
		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.fourFuKuan = undefined;
			return;
		}
		if (formData.value.threeFuKuan > 0) {
			if (formData.value.fourFuKuan > 0) {
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.fourFuKuan,formData.value.fourFuKuanBiLi);
					formData.value.fourFuKuan = formData.value.sumMoney;
					formData.value.fourFuKuanBiLi = formData.value.sumBl;
					return;
				}
				formData.value.fourFuKuanBiLi = ((formData.value.fourFuKuan / formData.value.price) * 100).toFixed(2);
			} else {
				formData.value.fourFuKuanBiLi = undefined;
			}
		} else {
			message.error('请先填写第三笔付款金额！');
			formData.value.fourFuKuan = undefined;
		}
	};
	//比例算第四笔付款
	const fourhandleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.fourFuKuanBiLi = undefined;
			return;
		}
		if (formData.value.threeFuKuan > 0) {
			if (formData.value.fourFuKuanBiLi > 0) {
				formData.value.fourFuKuan = ((formData.value.fourFuKuanBiLi / 100) * formData.value.price).toFixed(2);
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.fourFuKuan,formData.value.fourFuKuanBiLi);
					formData.value.fourFuKuan = formData.value.sumMoney;
					formData.value.fourFuKuanBiLi = formData.value.sumBl;
					return;
				}
			} else {
				formData.value.fourFuKuan = undefined;

			}
		} else {
			message.error('请先填写第三笔付款金额！');
			formData.value.fourFuKuanBiLi = undefined;
		}
	};


	//第六笔付款算比例
	const sixhandleBlur = (event) => {
		;
		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.sixFuKuan = undefined;
			return;
		}
		if (formData.value.fourFuKuan > 0) {
			if (formData.value.sixFuKuan > 0) {
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.sixFuKuan,formData.value.sixFuKuanBiLi);
					formData.value.sixFuKuan = formData.value.sumMoney;
					formData.value.sixFuKuanBiLi = formData.value.sumBl;
					return;
				}
				formData.value.sixFuKuanBiLi = ((formData.value.sixFuKuan / formData.value.price) * 100).toFixed(2);
			} else {
				formData.value.sixFuKuanBiLi = undefined;
			}
		} else {
			message.error('请先填写第五笔付款金额！');
			formData.value.sixFuKuan = undefined;
		}
	};
	//比例算第六笔付款
	const sixhandleBlurBL = (event) => {

		if (!formData.value.price && formData.value.price !== 0) {
			message.error('请先输入合同价格')
			formData.value.sixFuKuanBiLi = undefined;
			return;
		}
		if (formData.value.fourFuKuan > 0) {
			if (formData.value.sixFuKuanBiLi > 0) {
				formData.value.sixFuKuan = ((formData.value.sixFuKuanBiLi / 100) * formData.value.price).toFixed(2);
				let bollen = sumBl();
				//判断是否超出合同比例
				if(!bollen){
					jsEndMoney(formData.value.sixFuKuan,formData.value.sixFuKuanBiLi);
					formData.value.sixFuKuan = formData.value.sumMoney;
					formData.value.sixFuKuanBiLi = formData.value.sumBl;
					return;
				}
			} else {
				formData.value.sixFuKuan = undefined;

			}
		} else {
			message.error('请先填写第五笔付款金额！');
			formData.value.sixFuKuanBiLi = undefined;
		}
	};


	//根据付款计算总比例，如果超过100%提示用户重新输入
	const sumBl = () =>{

		let money = toSafeNumber(formData.value.shouFuKuan)+toSafeNumber(formData.value.twoFuKuan)+toSafeNumber(formData.value.threeFuKuan)
		            +toSafeNumber(formData.value.fourFuKuan)+toSafeNumber(formData.value.fiveFuKuan)+toSafeNumber(formData.value.sixFuKuan);
		let bl = ((money / formData.value.price) * 100).toFixed(2);
		let bollen = true;
		if(bl>100){
			message.error('当前付款金额或比例已经超出合同价格本身，系统已自动更正请检查！');
			bollen = false
		}
		return bollen;
	}
	//当超出100%后系统自动计算剩余应收金额和比例并返回
	const jsEndMoney = (num: number,bl: number) =>{

		let money = toSafeNumber(formData.value.shouFuKuan)+toSafeNumber(formData.value.twoFuKuan)+toSafeNumber(formData.value.threeFuKuan)
		            +toSafeNumber(formData.value.fourFuKuan)+toSafeNumber(formData.value.fiveFuKuan)+toSafeNumber(formData.value.sixFuKuan);
		formData.value.sumMoney = (toSafeNumber(formData.value.price)-toSafeNumber(money))+toSafeNumber(num);
		let BiLi = toSafeNumber(formData.value.shouFuKuanBiLi)+ toSafeNumber(formData.value.twoFuKuanBiLi)+ toSafeNumber(formData.value.threeFuKuanBiLi)
					+ toSafeNumber(formData.value.fourFuKuanBiLi)+ toSafeNumber(formData.value.fiveFuKuanBiLi)+ toSafeNumber(formData.value.sixFuKuanBiLi);
		formData.value.sumBl = ((toSafeNumber(100)-toSafeNumber(BiLi))+toSafeNumber(bl)).toFixed(2);
		console.log('计算出的比例');
		console.log(formData.value.sumBl);
		console.log('算出的金额')
		console.log(formData.value.sumMoney);
	}

	const toSafeNumber = (value) => {
  if (typeof value === 'number') {
    return value;
  }
  if (typeof value === 'string' && /^\d+(\.\d+)?$/.test(value)) {
    return Number(value);
  }
  return 0; // 如果不是有效数字，默认返回0，可以根据需求调整
};

	const fieldHasAlter = (fieldName) => {
		return formData.value.alterFieldNames && formData.value.alterFieldNames.indexOf(fieldName) > -1
	}

	const fieldHasAlterInRow = (fieldName, row) => {
		return row.alterFieldNames && row.alterFieldNames.indexOf(fieldName) > -1
	}

	const deptList = ref < Tree[] > ([]) // 树形结构
  const userList = ref<UserApi.UserVO[]>([]) // 用户列表

	// const customerList = ref<CustomerApi.CustomerVO[]>([])
	// const customerSelectList = ref<CustomerApi.CustomerVO[]>([])
	// const customerSelectLoading = ref(false)

	// const remoteCustomerSearch = (query: string) => {
	//   if (query) {
	//     customerSelectLoading.value = true
	//     setTimeout(() => {
	//       customerSelectLoading.value = false
	//       customerSelectList.value = customerList.value.filter((item) => {
	//         return item.name.toLowerCase().includes(query.toLowerCase())
	//       })
	//     }, 200)
	//   } else {
	//     customerSelectList.value = customerList.value
	//   }
	// }

	/** 子表的表单 */
	const projectOrderSubFormRef = ref()
  const userInit = ref()
	/** 打开弹窗 */
	const queryData = async (type: string, id ? : number) => {
		dialogTitle.value = t('action.' + type)
		formType.value = type
		resetForm()
		// 修改时，设置数据
		formLoading.value = true
		try {
			if (id) {
				formData.value = await ProjectOrderApi.getProjectOrder(id)

				if (formData.value.hasAlter == 1) {
					alterDisabled.value = true
				}

				// 子项列表
				formData.value.projectOrderSubs =
					await ProjectOrderApi.getProjectOrderSubListByProjectOrderId(id)

				// 如为归档
				let businessType = 'PROJECT_ORDER'
				if (type == 'detailArchive') {
					businessType = 'PROJECT_ORDER_SNAPSHOT'
				} else {
					// 操作日志
					let logParams = {
						pageNo: 1,
						pageSize: 99,
						businessId: id,
						businessType: businessType
					}
					formData.value.operateLogs = (await getOperateLogPage(logParams)).list
				}

				// 附件信息
				let attParams = {
					pageNo: 1,
					pageSize: 99,
					businessId: id,
					businessType: businessType
				}
				formData.value.attachments = (await getFilePage(attParams)).list
			}
			// 加载部门树
			deptList.value = handleTree(await DeptApi.getSimpleDeptList())
      userInit.value = await UserApi.getDeptName("市场部")
			// 获得客户列表
			// let customerParams = {
			//   pageNo: 1,
			//   pageSize: 10,
			//   status: '1'
			// }
			// const customerData = await CustomerApi.getCustomerPage(customerParams)
			// customerList.value = customerData.list
			// customerSelectList.value = customerData.list

			// // 绑定默认部门

			// const userProfile = await getUserProfile(formData.value.businessMan)
			// if (userProfile.dept) {
      for (let i = 0; i < userInit.value.length; i++) {
        if (userInit.value[i].deptName=='市场部'){
          formData.value.businessDeptId = userInit.value[i].deptId//userProfile.dept.id
          break
        }
      }
      getUserList(formData.value.businessDeptId);
			// }
		} finally {
			formLoading.value = false
		}
	}

// function getUserList(newValue: any){
//   console.log(1)
//     console.log(newValue?.id)
//     // userList.value =(await UserApi.getDeptId())
//     console.log(userList)
//   }
  const getUserList = async ( id) => {
    if (id!=null&&id!=''){
      userList.value =handleTree(await UserApi.getDeptId(id))
    }
  }
  watch(() => formData.value.businessDeptId, (newValue) => {
    getUserList(newValue)
  });
	const submitForm = async (active) => {
    if (active=='SAVE'){
      submitDisabled.value = true
    }
    if (active=='SUBMIT_AUDIT'){
      saveDisabled.value = true
    }

		// 校验子表单
		try {
      // 校验表单
      formData.value.active = active
     await formRef.value.validate()
			await projectOrderSubFormRef.value.validate()
		} catch (e) {
      saveDisabled.value = false
      submitDisabled.value = false
			return
		}

		// 提交请求
		formLoading.value = true
		try {
			// 如不是退回 清理审批意见
			if (active != 'REPULSE') {
				formData.value.activeOpinion = ''
			}
			// 如变更 置为已变更
			if (active == 'ALTER') {
				formData.value.hasAlter = 1
			}
			const data = formData.value as unknown as ProjectOrderApi.ProjectOrderVO

			if ('SUBMIT_AUDIT,ALTER'.indexOf(active) > -1) {
				// 子项目信息不能为空
				if (!data.projectOrderSubs || data.projectOrderSubs.length == 0) {
					message.error('子项目信息不能为空')
					return
				}
			}

			if ((active == 'SAVE' || active == 'SUBMIT_AUDIT') && active != 'ALTER') {
				// 不能提交存在数量为0的数据
				if (data.projectOrderSubs && data.projectOrderSubs.length > 0) {
					if (data.projectOrderSubs.some((sub) => !sub.amount || sub.amount <= 0)) {
						message.error('子项目数量不能为0')
						return
					}
				}
			}

			// 变更
			if (active == 'ALTER') {
				// 总数量不能为0
				if (data.projectOrderSubs && data.projectOrderSubs.length > 0) {
					const total = data.projectOrderSubs.reduce((acc, cur) => {
						return acc + cur.amount
					}, 0)
					if (total <= 0) {
						message.error('子项目数量和不能为0')
						return
					}
				}
			}

			// 附件校验
			if ('SUBMIT_AUDIT,ALTER'.indexOf(active) > -1) {
				if (formData.value.hasContract) {
					const hasContractFile = formData.value.attachments.some((file) => {
						return file.businessFileType == 'CONTRACT'
					})
					if (!hasContractFile) {
						message.error('请上传合同')
						return
					}
				}
				if (formData.value.hasTechnologyProtocol) {
					const hasProtocolFile = formData.value.attachments.some((file) => {
						return file.businessFileType == 'TECHNOLOGY_PROTOCOL'
					})
					if (!hasProtocolFile) {
						message.error('请上传技术协议')
						return
					}
				}
			}

			const orderId = await ProjectOrderApi.operateProjectOrder(data)
			message.success(t('common.operationSuccess'))
			// 上传附件
			if (contractUploadFiles.value.length > 0) {
				contractUploadData.value.businessId = orderId
				await contractUploadRef.value!.submit()
			}
			if (protocolUploadFiles.value.length > 0) {
				protocolUploadData.value.businessId = orderId
				await protocolUploadRef.value!.submit()
			}

			// 如非保存 返回列表页
			if (active != 'SAVE') {

        if (active=='SUBMIT_AUDIT'){
          saveDisabled.value = false
        }
				router.back()
			} else {

        // 成功后刷新
				query.active = 'update'
				query.id = orderId
				if (sumbefore.value == 0) {
          await reload()
				}
        saveDisabled.value = false
        submitDisabled.value = false
			}
		} catch (e) {
      saveDisabled.value = false
      submitDisabled.value = false
    }
    finally {
			formLoading.value = false
		}
	}

	/** 新增子项按钮操作 */
	const onAddItem = () => {
		const row = {
			id: undefined,
			projectOrderId: undefined,
			name: undefined,
			deviceModel: undefined,
			amount: undefined,
			compositionId: undefined,
			unit: '21',
			remark: undefined,
			status: 1,
			alterFieldNames: []
		}
		row.projectOrderId = formData.value.id
		formData.value.projectOrderSubs.push(row)
	}

	/** 删除子项操作 */
	const onDeleteItem = async (index) => {
		let deletedItems = formData.value.projectOrderSubs.splice(index, 1)
		let id = deletedItems[0].id;
		if (id) await ProjectOrderApi.deleteProjectOrderSub(id)
	}
	// ====================附件信息 开始=======================================
	const uploading = ref(false)
	const uploadUrl = ref(
		import.meta.env.VITE_UPLOAD_BATCH_URL)
	const contractUploadRef = ref()
	const contractUploadFiles = ref < UploadUserFile[] > ([])
	const contractUploadData = ref({
		businessType: 'PROJECT_ORDER',
		businessId: formData.value.id,
		businessFileType: 'CONTRACT'
	})

	const protocolUploadRef = ref()
	const protocolUploadFiles = ref < UploadUserFile[] > ([])
	const protocolUploadData = ref({
		businessType: 'PROJECT_ORDER',
		businessId: formData.value.id,
		businessFileType: 'TECHNOLOGY_PROTOCOL'
	})

	const contractUploadChange = (file, files) => {
		contractUploadFiles.value = files
		refreshAttachments(files, 'CONTRACT')
	}
	const protocolUploadChange = (file, files) => {
		protocolUploadFiles.value = files
		refreshAttachments(files, 'TECHNOLOGY_PROTOCOL')
	}

	// 记录待上传、成功上传及失败上传的文件数量
	const sumbefore = ref(0)
	const successfulUploadsCount = ref(0)
	const failedUploadsCount = ref(0)
	const failedAttachments = ref < UploadUserFile[] > ([])
	const failedAttachmentsName = ref()
	// 处理单个文件上传成功的情况
	const handleSuccess = (response: any, file: UploadUserFile) => {
		successfulUploadsCount.value++

		// console.log('上传成功数量', successfulUploadsCount.value)
	}

	// 处理单个文件上传失败的情况
	const handleError = (error: Error, file: UploadUserFile) => {
		failedUploadsCount.value++
		if (failedUploadsCount.value > 0) {
			// 当有上传错误时
			// 将失败的附件添加到failedAttachments.value数组中
			failedAttachments.value.push(file)
			failedAttachmentsName.value = failedAttachments.value.map((value) => value.name)
		}
		// console.log('上传失败数量', failedUploadsCount.value)
	}

	// 文件上传前的钩子
	const before = (rawFile) => {
		sumbefore.value++
	}

	const refreshAttachments = (files, type) => {
		formData.value.attachments = formData.value.attachments.filter((value, index, array) => {
			return value.businessFileType != type || value.id
		})
		// for (let i = 0; i < files.length; i++) {
		//   let file = files[i]
		//   file.businessFileType = type
		//   file.createTime = new Date()
		//   formData.value.attachments.push(file)
		// }
		// // 排序
		// formData.value.attachments.sort((v1, v2) => {
		//   return v1.createTime - v2.createTime > 0
		// })

		// formData.value.attachments = formData.value.attachments.filter((value) => value.id)

		for (let i = 0; i < files.length; i++) {
			let file = files[i]
			file.businessFileType = type
			file.createTime = new Date()
			formData.value.attachments.push(file)
		}
		// 排序
		formData.value.attachments.sort((v1, v2) => v1.createTime - v2.createTime)

		// 文件上传一遍 上传总数等于要上传文件时 刷新页面
		const sum = successfulUploadsCount.value + failedUploadsCount.value
		// console.log('上传总数', sum)
		// console.log('要上传文件数量', sumbefore.value)
		if (sumbefore.value !== sum && sumbefore.value !== 0 && sum !== 0) {
			// console.log('要上传文件数量不等于上传总数时等待',uploading.value)
			uploading.value = true
		} else if (sum == sumbefore.value && sumbefore.value > 0 && sum > 0) {
			// console.log('要上传文件数量等于上传总数 刷新页面并给出提示')
			if (failedUploadsCount.value > 0) {
				ElMessageBox.alert(
					// 使用错误信息作为提示内容
					`文件名为：${failedAttachmentsName.value.join(' / ')}上传失败`,
					`文件格式不正确或网络问题 请您稍后再试`, {
						dangerouslyUseHTMLString: false, // 由于我们不是使用HTML字符串，所以这里设置为false
						confirmButtonText: '知道了',
						center: true
					}
				)
			}
			reload()
			uploading.value = false
		}
	}

	// 删除附件
	const handleDeleteAttachment = async (index, type) => {
		const deletedAttachments = formData.value.attachments.splice(index, 1)
		for (let i = 0; i < deletedAttachments.length; i++) {
			const attachment = deletedAttachments[i]
			if (attachment.id) {
				// 清理已上传文件
				await deleteFileLogic(attachment.id)
			}
			// 清理待上传文件
			contractUploadFiles.value = contractUploadFiles.value.filter((file1) => {
				return file1.name != attachment.name || file1.businessFileType != type
			})

			protocolUploadFiles.value = protocolUploadFiles.value.filter((file2) => {
				return file2.name != attachment.name || file2.businessFileType != type
			})
		}
	}

	// 下载文件
	const downloadAttachment = async (name, url) => {
		       const baseUrl = import.meta.env.VITE_BASE_URL;
    url =baseUrl+'/admin-api/'+ url.split('/admin-api/')[1];    const data = await downloadFile(url)
		download.any(data, name)
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			code: undefined,
			orderStatus: 4,
			deliveryStatus: 1,
			businessDeptId: undefined,
			customerId: undefined,
			projectName: undefined,
			businessLine: undefined,
			blueprintNo: undefined,
			hasPrice: 1,
			price: undefined,
			currency: '1',
			projectStartTime: undefined,
			projectEndTime: undefined,
			isUrgency: 0,
			property: 1,
			referenceTechnology: undefined,
			hasAlter: 0,
			lastAlterTime: undefined,
			qualityRequirement: undefined,
			remark: undefined,
			hasContract: 0,
			hasTechnologyProtocol: 0,
			hasBlueprint: 0,
			blueprintRemark: undefined,
			status: 1,
			businessMan: undefined,
			createTime: new Date(),
			projectOrderSubs: [],
			attachments: [],
			operateLogs: [],
			contractNo: undefined,
			active: '',
			activeOpinion: '',
			isSnapshot: 0,
			snapshotId: undefined,
			snapshotCode: undefined,
			orderTime: new Date(),
			snapshotOrderTime: undefined,
			alterFieldNames: []
		}
		formRef.value?.resetFields()
	}

	const openMe = (url) => {
		window.open(url)
	}
  const auditDisabled=ref(true)
	const alterDisabled = ref(false)
	const detailDisabled = ref(false)
  const priceDisabled = ref(false)
  const saveDisabled = ref(false)
  const submitDisabled = ref(false)
	onMounted(() => {
		if (query.active == 'alter') {
			alterDisabled.value = true
		}
    if (query.active == 'price') {
      priceDisabled.value = true
    }
		if ('detail,audit,approve,terminate,detailArchive'.indexOf(query.active) > -1) {
			detailDisabled.value = true
		}
    if ('audit,approve'.indexOf(query.active) > -1){
      auditDisabled.value = true
    }
		queryData(query.active, query.id)
		// 绑定默认业务员
		// if (!formData.value.businessMan) {
		// 	formData.value.businessMan = useUserStore().getUser.id // 当前登录的编码
		// }
	})

	// 材质传递的值
	const handleSelectedcomposition = (currentIndex: number, newValue: any) => {
		formData.value.projectOrderSubs[currentIndex].compositionId = newValue?.id
	}
	//职工
	const handleSelectedUser = (newValue: any) => {
		formData.value.businessMan = newValue?.id
	}
	// 设备
	const handleSelectedequip = (currentIndex: number, newValue: any) => {
		// console.log(currentIndex, newValue)
		formData.value.projectOrderSubs[currentIndex].deviceModel = newValue?.id
	}
	//客户
	const handleSelectedClient = (newValue: any) => {
		formData.value.customerId = newValue?.id
	}
</script>
<style>
	a {
		color: #409eff;
		text-decoration: none;
	}

	.upload-file-uploader {
		margin-bottom: 10px;
		display: inline-block;
		margin-right: 20px;
	}

	.alter-class {
		position: relative;
		border: solid 1px orange !important;
		outline: solid 1px orange !important;
	}

	/* .hl-card .el-table__body tr.alter-class1 {
  border: solid 3px orange !important;
} */
</style>
<style scoped>
	.hl-card /deep/ .el-table__body tr.alter-class1 {
		position: relative;
		/*重点*/
		z-index: 2;
		/*重点*/
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		--el-table-row-hover-bg-color: transparent;
	}

	.hl-card /deep/ .el-table__body tr.alter-class1::after {
		position: absolute;
		content: ' ';
		width: calc(100% - 6px);
		/*改动处*/
		height: calc(100% - 6px);
		left: 2px;
		/*改动处*/
		background: transparent;
		border: 3px solid orange !important;
	}
</style>
