<template>
	<div>

		<SearchBox ref="SearchBoxRef" formName="query" :formData="query" @PopupNo="PopupNo" @reset="reset">
		</SearchBox>

		<ButtonBar @search="handleSearch" @add="handleAdd" @cotChange="cotChange"
			@handlePaymentMethod3="handlePaymentMethod3" @handleExportBatch="handleExportBatch"
			@handleExportAll="handleExportAll" @handleHistory="handleHistory"></ButtonBar>

		<el-card :body-style="cardBodyStyle">
			<el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
				height="63vh">
				<el-table-column type="selection" fixed></el-table-column>
				<el-table-column type="index" label="序号" align="center" width="60" fixed>
					<template #default="scope">
						<span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
					</template>
				</el-table-column>
				<el-table-column v-if="true" prop="contrNo" label="合同编号" width="150" header-align="center"
					align="center" show-overflow-tooltip fixed>
				</el-table-column>
				<el-table-column v-if="true" prop="contrNm" label="合同名称" width="180" header-align="center"
					align="center" show-overflow-tooltip fixed>
				</el-table-column>
				<el-table-column v-if="true" prop="supplierNm" label="交易方名称" width="250" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="contrTy" label="合同类型" width="100" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="conSts" label="合同状态" width="120" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="khContrNo" label="对方合同编号" width="150" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="approveDt" label="审批结束时间" width="150" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="delvDate" label="预计交货日期" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="invMth" label="结算方式" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="analyDataAccord" label="化验结算依据" width="120" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="weightDataAccord" label="计量结算依据" width="120" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="priceDcnMth" label="定价方式" width="100" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="delvMth" label="交货方式" width="100" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="delvPlace" label="交货地点" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="ifAnnual" label="是否长协" width="100" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="ifBid" label="是否招投标" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="false" prop="salMth" label="销售方式" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="signReqNo" label="签约请示" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="totalAmt" label="合同金额" width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="qty" label="重量" width="120" header-align="center" align="right"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="contrReq" label="合同要求" width="100" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="contrDt" label="合同日期" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="checkYn" label="争议所在地法院" width="150" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="riskInfo" label="风险提示" width="100" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="tempNm" label="合同模板名称" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="addTime" label="录入日期" width="120" header-align="center"
					align="center" show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="addName" label="录入人" width="100" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="ifSupplemental" label="是否补录" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
					<template #default="{ row }">
						<el-button plain type="warning" @click="handleEdit(row)"
							v-if="(row.workId === '' || row.workModel.opType === '1') && (row.conSts === 'A' || row.conSts === 'R' || row.conSts === 'F')">编辑
						</el-button>
						<el-button plain type="danger" @click="handleDelete(row)"
							v-if="(row.workId === '' || row.workModel.opType === '1') && (row.conSts === 'A' || row.conSts === 'R' || row.conSts === 'F')">删除
						</el-button>
						<el-button plain type="success" @click="check(row)"
							v-if="(row.workId === '' || row.workModel.opType === '1') && (row.conSts === 'A' || row.conSts === 'R' || row.conSts === 'F')">发起
						</el-button>
						<el-button plain type="primary" @click="handleDetail(row)"
							v-if="row.workId !== '' && !(row.conSts === 'A' || row.conSts === 'R')">详情</el-button>
						<el-button plain type="info" @click="handleCancel(row)"
							v-if="row.workId !== '' && row.workModel.opType !== '1' && row.workModel.flowStatus !== '170'">撤回</el-button>
						<el-dropdown
							v-if="row.workId !== '' && !(row.conSts === 'A' || row.conSts === 'R') && row.contrTy == '10'"
							style="padding-left: 5px">
							<el-button plain type="warning" >
								补充协议打印<el-icon class="el-icon--right"><arrow-down /></el-icon>
							</el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item @click="download(row, 'all')">承兑/现汇</el-dropdown-item>
									<el-dropdown-item @click="download(row, 'cash')">现汇</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-card :body-style="cardBodyStyle">
			<el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
				background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
				@current-change="handleCurrentChange">
			</el-pagination>
		</el-card>

		<el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" top="5vh"
			@open="openDialog" @close="closeDialog">
			<el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
				<el-form-item label="合同类型" prop="contrTy">
					<el-select v-model="form.contrTy" placeholder="请选择" clearable style="width: 200px"
						@change="handleChange">
						<el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
			</el-form>
		</el-dialog>

		<el-dialog fullscreen :close-on-click-modal="false" draggable :title="title" v-model="dialogVisibleSal"
			top="5vh" @open="openDialog" @close="closeDialog">
			<el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef"
				:rules="rulesSal">
				<el-form-item label="合同类型" prop="contrTy">
					<el-select v-model="form.contrTy" :placeholder="form.contrTy" clearable style="width: 200px;"
						class="dicSelect" disabled>
						<el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="合同编号" prop="contrNo">
					<el-input v-model="form.contrNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="合同名称" prop="contrNm">
					<el-input v-model="form.contrNm" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="交易方名称" prop="supplierNm">
					<el-input v-model="form.supplierNm" clearable readonly style="width: 200px;">
						<template #append>
							<el-button :icon="Search" @click="handleSearchSupplier" :disabled="form.conSts === 'R'" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="对方合同编号" prop="khContrNo">
					<el-input v-model="form.khContrNo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同状态" prop="conSts">
					<el-select v-model="form.conSts" placeholder="" clearable style="width: 200px" class="dicSelect"
						disabled>
						<el-option v-for="item in dicList.contrSts" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="审批结束时间" prop="approveDt">
					<el-date-picker v-model="form.approveDt" type="datetime" style="width: 200px;"
						value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="预计交货日期" prop="delvDate">
					<el-date-picker v-model="form.delvDate" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD"></el-date-picker>
				</el-form-item>
				<el-form-item label="结算方式" prop="invMth">
					<el-select v-model="form.invMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.SAL_INV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="化验结算依据" prop="analyDataAccord">
					<el-select v-model="form.analyDataAccord" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.ANALY_DATA_ACCORD" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="计量结算依据" prop="weightDataAccord">
					<el-select v-model="form.weightDataAccord" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.WEIGHT_DATA_ACCORD" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="定价方式" prop="priceDcnMth">
					<el-select v-model="form.priceDcnMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.PRICE_DCN_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货方式" prop="delvMth">
					<el-select v-model="form.delvMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.DELV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货地点" prop="delvPlace">
					<el-input v-model="form.delvPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="到达地" prop="toPlace">
					<el-input v-model="form.toPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="出发地" prop="fromPlace">
					<el-input v-model="form.fromPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="是否长协" prop="ifAnnual">
					<el-select v-model="form.ifAnnual" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否招投标" prop="ifBid">
					<el-select v-model="form.ifBid" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<!--
				<el-form-item label="销售方式" prop="salMth">
					<el-select v-model="form.salMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.SAL_SAL_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				-->
				<el-form-item label="质量要求" prop="qualityReq">
					<el-input v-model="form.qualityReq" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="签约请示" prop="signReqNo">
					<el-input v-model="form.signReqNo" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchSignRequest" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="合同金额" prop="totalAmt">
					<el-input-number v-model="form.totalAmt" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="重量" prop="qty">
					<el-input-number v-model="form.qty" :precision="2" :step="0.1" controls-position="right" clearable
						style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="合同要求" prop="contrReq">
					<el-input v-model="form.contrReq" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同日期" prop="contrDt">
					<el-date-picker v-model="form.contrDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" @change="handleContrDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="终止日期" prop="endDt" :error="endDtError">
					<el-date-picker v-model="form.endDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" :disabled-date="disabledDate" @change="handleEndDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="争议所在地法院" prop="checkYn">
					<el-select v-model="form.checkYn" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.CHECK_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="风险提示" prop="riskInfo">
					<el-input v-model="form.riskInfo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同模版" prop="tempNm">
					<el-input v-model="form.tempNm" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchCotTmp" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="录入日期" prop="addTime">
					<el-date-picker v-model="form.addTime" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="录入人" prop="addName">
					<el-input v-model="form.addName" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="是否补录">
					<el-checkbox v-model="ifSupplemental" @change="updateIfSupplemental"
						:disabled="disabledIfSupplemental" />
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input type="textarea" v-model="form.remark" clearable style="width: 1250px" rows="5"></el-input>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="primary" @click="handlePrintPreview" v-if="form.id">打印预览</el-button>
					<el-button plain type="success" @click="handleSave(ruleFormRef)" v-if="!readonly">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
					<el-button plain type="info" @click="handleCancelSave" v-if="form.id">关闭</el-button>
				</div>
			</template>

			<el-tabs v-model="activeName" @tab-click="handleClick" v-if="form.id">
				<el-tab-pane label="合同明细" name="first">
					<addLineVue :cotHead="form">
					</addLineVue>
				</el-tab-pane>
				<el-tab-pane label="收付款方式" name="second">
					<addVue :cotHead="form">
					</addVue>
				</el-tab-pane>
				<el-tab-pane label="文件上传" name="third">
					<el-card :body-style="cardBodyStyle">

						<Attachment ref="AttachmentRefManual" :fId="fId"></Attachment>
					</el-card>
				</el-tab-pane>
				<el-tab-pane label="合同条款" name="fourth">
					<addHouse :cotHead="form"></addHouse>
				</el-tab-pane>
			</el-tabs>
		</el-dialog>

		<el-dialog fullscreen :close-on-click-modal="false" draggable :title="title" v-model="dialogVisiblePur"
			top="5vh" @open="openDialog" @close="closeDialog">
			<el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef"
				:rules="rulesPur">
				<el-form-item label="合同类型" prop="contrTy">
					<el-select v-model="form.contrTy" :placeholder="form.contrTy" clearable style="width: 200px;"
						class="dicSelect" disabled>
						<el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="合同编号" prop="contrNo">
					<el-input v-model="form.contrNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="合同名称" prop="contrNm">
					<el-input v-model="form.contrNm" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="交易方名称" prop="supplierNm">
					<el-input v-model="form.supplierNm" clearable readonly style="width: 200px;">
						<template #append>
							<el-button :icon="Search" @click="handleSearchSupplier" :disabled="form.conSts === 'R'" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="对方合同编号" prop="khContrNo">
					<el-input v-model="form.khContrNo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同状态" prop="conSts">
					<el-select v-model="form.conSts" placeholder="" clearable style="width: 200px" class="dicSelect"
						disabled>
						<el-option v-for="item in dicList.contrSts" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="审批结束时间" prop="approveDt">
					<el-date-picker v-model="form.approveDt" type="datetime" style="width: 200px;"
						value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="预计交货日期" prop="delvDate">
					<el-date-picker v-model="form.delvDate" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD"></el-date-picker>
				</el-form-item>
				<el-form-item label="结算方式" prop="invMth">
					<el-select v-model="form.invMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.SAL_INV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="化验结算依据" prop="weightDataAccord">
					<el-select v-model="form.weightDataAccord" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.WEIGHT_DATA_ACCORD" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="计量结算依据" prop="analyDataAccord">
					<el-select v-model="form.analyDataAccord" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.ANALY_DATA_ACCORD" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="定价方式" prop="priceDcnMth">
					<el-select v-model="form.priceDcnMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.PRICE_DCN_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货方式" prop="delvMth">
					<el-select v-model="form.delvMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.DELV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货地点" prop="delvPlace">
					<el-input v-model="form.delvPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="到达地" prop="toPlace">
					<el-input v-model="form.toPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="出发地" prop="fromPlace">
					<el-input v-model="form.fromPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="是否长协" prop="ifAnnual">
					<el-select v-model="form.ifAnnual" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否招投标" prop="ifBid">
					<el-select v-model="form.ifBid" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否内部生产" prop="internalProduction">
					<el-select v-model="form.internalProduction" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="是否采购备件" prop="purTy">
					<el-select v-model="form.purTy" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item> -->
				<el-form-item label="签约请示" prop="signReqNo">
					<el-input v-model="form.signReqNo" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchSignRequest" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="合同金额" prop="totalAmt">
					<el-input-number v-model="form.totalAmt" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="重量" prop="qty">
					<el-input-number v-model="form.qty" :precision="2" :step="0.1" controls-position="right" clearable
						style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="合同要求" prop="contrReq">
					<el-input v-model="form.contrReq" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同日期" prop="contrDt">
					<el-date-picker v-model="form.contrDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" @change="handleContrDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="终止日期" prop="endDt" :error="endDtError">
					<el-date-picker v-model="form.endDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" :disabled-date="disabledDate" @change="handleEndDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="争议所在地法院" prop="checkYn">
					<el-select v-model="form.checkYn" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.CHECK_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				
				<el-form-item label="风险提示" prop="riskInfo">
					<el-input v-model="form.riskInfo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同模版" prop="tempNm">
					<el-input v-model="form.tempNm" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchCotTmp" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="录入日期" prop="addTime">
					<el-date-picker v-model="form.addTime" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="录入人" prop="addName">
					<el-input v-model="form.addName" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="是否补录">
					<el-checkbox v-model="ifSupplemental" @change="updateIfSupplemental"
						:disabled="disabledIfSupplemental" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="primary" @click="handlePrintPreview" v-if="form.id">打印预览</el-button>
					<el-button plain type="success" @click="handleSave(ruleFormRef)" v-if="!readonly">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
					<el-button plain type="info" @click="handleCancelSave" v-if="form.id">关闭</el-button>
				</div>
			</template>

			<el-tabs v-model="activeName" @tab-click="handleClick" v-if="form.id">
				<el-tab-pane label="合同明细" name="first">
					<addLineVue :cotHead="form" @receive-from-child="retu">
					</addLineVue>
				</el-tab-pane>
				<el-tab-pane label="收付款方式" name="second">
					<addVue :cotHead="form">
					</addVue>
				</el-tab-pane>
				<el-tab-pane label="文件上传" name="third">
					<el-card :body-style="cardBodyStyle">

						<Attachment ref="AttachmentRefManual" :fId="fId"></Attachment>
					</el-card>
				</el-tab-pane>

				<el-tab-pane label="合同条款" name="fourth">
					<addHouse :cotHead="form"></addHouse>
				</el-tab-pane>
			</el-tabs>
		</el-dialog>

		<el-dialog fullscreen :close-on-click-modal="false" draggable :title="title" v-model="dialogVisibleService"
			top="5vh" @open="openDialog" @close="closeDialog">
			<el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef"
				:rules="rulesService">
				<el-form-item label="合同类型" prop="contrTy">
					<el-select v-model="form.contrTy" :placeholder="form.contrTy" clearable style="width: 200px;"
						class="dicSelect" disabled>
						<el-option v-for="item in dicList.CONTRACT_TYPE" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="合同编号" prop="contrNo">
					<el-input v-model="form.contrNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="合同名称" prop="contrNm">
					<el-input v-model="form.contrNm" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="交易方名称" prop="supplierNm">
					<el-input v-model="form.supplierNm" clearable readonly style="width: 200px;">
						<template #append>
							<el-button :icon="Search" @click="handleSearchSupplier" :disabled="form.conSts === 'R'" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="对方合同编号" prop="khContrNo">
					<el-input v-model="form.khContrNo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同状态" prop="conSts">
					<el-select v-model="form.conSts" placeholder="" clearable style="width: 200px" class="dicSelect"
						disabled>
						<el-option v-for="item in dicList.contrSts" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="审批结束时间" prop="approveDt">
					<el-date-picker v-model="form.approveDt" type="datetime" style="width: 200px;"
						value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="预计交货日期" prop="delvDate">
					<el-date-picker v-model="form.delvDate" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD"></el-date-picker>
				</el-form-item>
				<el-form-item label="结算方式" prop="invMth">
					<el-select v-model="form.invMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.SAL_INV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="定价方式" prop="priceDcnMth">
					<el-select v-model="form.priceDcnMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.PRICE_DCN_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货方式" prop="delvMth">
					<el-select v-model="form.delvMth" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.DELV_MTH" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="交货地点" prop="delvPlace">
					<el-input v-model="form.delvPlace" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="是否长协" prop="ifAnnual">
					<el-select v-model="form.ifAnnual" placeholder="请选择" clearable style="width: 200px;">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否招投标" prop="ifBid">
					<el-select v-model="form.ifBid" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.COM_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="签约请示" prop="signReqNo">
					<el-input v-model="form.signReqNo" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchSignRequest" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="合同金额" prop="totalAmt">
					<el-input-number v-model="form.totalAmt" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="重量" prop="qty">
					<el-input-number v-model="form.qty" :precision="2" :step="0.1" controls-position="right" clearable
						style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="合同要求" prop="contrReq">
					<el-input v-model="form.contrReq" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同日期" prop="contrDt">
					<el-date-picker v-model="form.contrDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" @change="handleContrDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="终止日期" prop="endDt" :error="endDtError">
					<el-date-picker v-model="form.endDt" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" :disabled-date="disabledDate" @change="handleEndDt"></el-date-picker>
				</el-form-item>
				<el-form-item label="争议所在地法院" prop="checkYn">
					<el-select v-model="form.checkYn" placeholder="请选择" clearable style="width: 200px">
						<el-option v-for="item in dicList.CHECK_YN" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="风险提示" prop="riskInfo">
					<el-input v-model="form.riskInfo" clearable style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="合同模版" prop="tempNm">
					<el-input v-model="form.tempNm" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleSearchCotTmp" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="录入日期" prop="addTime">
					<el-date-picker v-model="form.addTime" type="date" style="width: 200px;" value-format="YYYY-MM-DD"
						format="YYYY-MM-DD" disabled></el-date-picker>
				</el-form-item>
				<el-form-item label="录入人" prop="addName">
					<el-input v-model="form.addName" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="是否补录">
					<el-checkbox v-model="ifSupplemental" @change="updateIfSupplemental"
						:disabled="disabledIfSupplemental" />
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="primary" @click="handlePrintPreview" v-if="form.id">打印预览</el-button>
					<el-button plain type="success" @click="handleSave(ruleFormRef)" v-if="!readonly">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
					<el-button plain type="info" @click="handleCancelSave" v-if="form.id">关闭</el-button>
				</div>
			</template>

			<el-tabs v-model="activeName" @tab-click="handleClick" v-if="form.id">
				<el-tab-pane label="合同明细" name="first">
					<addLineVue :cotHead="form">
					</addLineVue>
				</el-tab-pane>
				<el-tab-pane label="收付款方式" name="second">
					<addVue :cotHead="form">
					</addVue>
				</el-tab-pane>
				<el-tab-pane label="文件上传" name="third">
					<el-card :body-style="cardBodyStyle">
						<Attachment ref="AttachmentRefManual" :fId="fId"></Attachment>
					</el-card>
				</el-tab-pane>
				<el-tab-pane label="合同条款" name="fourth">
					<addHouse :cotHead="form"></addHouse>
				</el-tab-pane>
			</el-tabs>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" draggable title="历史版本" width="1200px" v-model="dialogVisibleHistory"
			top="5vh" @open="openDialogHistory">
			<el-table :data="tableDataHistory" border highlight-current-row
				@selection-change="handleSelectionChangeHistory">
				<el-table-column type="index" label="序号" align="center" width="60">
					<template #default="scope">
						<span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
					</template>
				</el-table-column>
				<el-table-column v-for="(item, index) in column" :prop="item.prop" :label="item.label"
					:width="item.width" header-align="center" align="center" show-overflow-tooltip
					:formatter="formatter">
				</el-table-column>
				<el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
					<template #default="{ row }">
						<el-button plain type="primary" @click="handleDetail(row)" v-if="row.workId != ''">查看</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-card :body-style="cardBodyStyle">
				<el-pagination :current-page="currentPageHistory" :page-size="pageSizeHistory"
					:page-sizes="pageSizesHistory" :total="totalRowsHistory" background="background"
					layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChangeHistory"
					@current-change="handleCurrentChangeHistory">
				</el-pagination>
			</el-card>
		</el-dialog>

		<Popup_base_ks ref="PopupRef" :tpTypeShow="true" :tpType="tpType" @receive-from-child="retu"></Popup_base_ks>

		<PopupSignRequest ref="PopupRefSignRequest" @receive-from-child="retuSignRequest" :params="paramsSignRequest">
		</PopupSignRequest>

		<PopupCotTmp ref="PopupRefCotTmp" @receive-from-child="retuCotTmp" :params="queryCotTmp"></PopupCotTmp>
	</div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue"
import PopupSignRequest from '@/views/cot/components/PopupSignRequest.vue'
import PopupCotTmp from '@/views/cot/components/PopupCotTmp.vue'
import addLineVue from '@/views/cot/input/line.vue'
import addVue from '@/views/cot/input/invtype.vue'
import addHouse from '@/views/cot/input/house.vue'

import {
	ref,
	reactive,
	onMounted,
	getCurrentInstance,
	watch
} from 'vue'
import { Search } from '@element-plus/icons-vue'

const {
	proxy
} = getCurrentInstance()

import tools from '@/tools'
import { workflowSubmit, workflowCancel } from "@/tools/workflow.js"

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

import Attachment from '@/components/Attachment.vue'
import SearchBox from "@/components/SearchBox.vue";
import { ElMessage } from 'element-plus'
const SearchBoxRef = ref(null)
const activeName = ref('first')

onMounted(() => {
	getMenuTable()
	getDictList()
	getCompanyInfo()
	handleSearch()
})


/**
 * 查询公司代码
 */
const userId = window.localStorage.getItem('userId')
const userCode = window.localStorage.getItem('userCode')
const userName = window.localStorage.getItem('userDesc')
const dept = JSON.parse(window.localStorage.getItem('dept'))
const deptTree = JSON.parse(window.localStorage.getItem('deptTree'))
const company = ref({
	sfhAddr: null
})
const getCompanyInfo = () => {
	var url = 'bas/Partner/queryBytradePartnerCode'
	var param = {
		tradePartnerCode: 'D01000004'
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == 0) {
			company.value = response.data.data
		} else {
			ElMessage({
				type: 'error',
				message: '查找失败' + response.data.msg
			});
		}
	});
}
/**
 * 查询公司代码
 */


/**
 * 查询表格字段
 */
const column = ref([])
const getMenuTable = () => {
	var url = 'framework/MenuTable/queryMenuTable'
	var param = {
		menuId: localStorage.getItem('menuId'),
		tName: 'tableDate'
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == '0') {
			column.value = response.data.data
		} else {
			ElMessage({
				type: 'error',
				message: '操作失败' + response.data.msg,
			});
		}
	});
}
/**
 * 查询表格
 */

/**
 *  查询字典
 */
const dicList = ref({
	CONTRACT_TYPE: [],
	contrSts: [],
	SAL_INV_MTH: [],
	PRICE_DCN_MTH: [],
	DELV_MTH: [],
	WEIGHT_DATA_ACCORD: [],
	ANALY_DATA_ACCORD: [],
	SAL_SAL_MTH: [],
	COM_YN: [],
	CHECK_YN: []
})
const getDictList = () => {
	var url = 'framework/Common/querySelectorList'
	var param = {
		type: JSON.stringify(['CONTRACT_TYPE', 'contrSts', 'SAL_INV_MTH', 'PRICE_DCN_MTH', 'DELV_MTH', 'WEIGHT_DATA_ACCORD', 'ANALY_DATA_ACCORD', 'SAL_SAL_MTH', 'COM_YN', 'CHECK_YN'])
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			dicList.value = response.data.data
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
const formatter = (row, column, cellValue, index) => {
	if (!cellValue || cellValue == null || cellValue == '') {
		return cellValue
	}
	switch (column.property) {
		case 'contrTy':
			cellValue = dicList.value.CONTRACT_TYPE.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'conSts':
			cellValue = dicList.value.contrSts.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'invMth':
			cellValue = dicList.value.SAL_INV_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'priceDcnMth':
			cellValue = dicList.value.PRICE_DCN_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'delvMth':
			cellValue = dicList.value.DELV_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'weightDataAccord':
			cellValue = dicList.value.WEIGHT_DATA_ACCORD.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'analyDataAccord':
			cellValue = dicList.value.ANALY_DATA_ACCORD.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'salMth':
			cellValue = dicList.value.SAL_SAL_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'ifAnnual':
			cellValue = dicList.value.COM_YN.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'ifBid':
			cellValue = dicList.value.COM_YN.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'checkYn':
			cellValue = dicList.value.CHECK_YN.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'addTime':
			cellValue = cellValue.split(' ')[0]
			break
		case 'ifSupplemental':
			cellValue = cellValue === '1' ? '是' : '否'
			break

	}

	return cellValue
}
/**
 *  查询字典
 */



/**
 *   查询
 */
const query = ref({
	contrTy: '',
	contrNo: '',
	contrNm: '',
	khContrNo: '',
	supplierNm: '',
	contrDt: '',
	conSts: ['A', 'B', 'D', 'F', 'R']
})

const tableData = ref([])
const handleSearch = () => {
	tableData.value = []
	currentPage.value = 1
	getTableData()
}
const getTableData = () => {
	var url = 'cot/Head/query'
	var param = {
		page: currentPage.value,
		rows: pageSize.value,
		params: JSON.stringify(query.value)
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			tableData.value = response.data.data.records
			totalRows.value = response.data.data.total
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
/**
 *   查询
 */


/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
	pageSize.value = val
	getTableData()
}
const handleCurrentChange = (val) => {
	currentPage.value = val
	getTableData()
}
/**
 * 分页
 */


/**
 *  新增
 */
const title = ref('')
const readonly = ref(false)
const dialogVisible = ref(false)
const form = ref({
	id: '',
	contrTy: '',
	contrNo: '',
	dataAccord: '',
	approveDt: '',
	checkYn: '',
	riskInfo: '',
	conSts: '',
	signReqNo: '',
	delvDays: '',
	delvDate: '',
	priceDcnMth: '',
	signReqId: '',
	ifAnnual: '',
	delvMth: '',
	contrForm: '',
	processInstanceStatus: '',
	processInstanceId: '',
	ifBid: '',
	tempNm: '',
	invMth: '',
	toPlace: '',
	fromPlace: '',
	tempId: '',
	totalAmt: null,
	qty: null,
	conSts: '',
	remark: '',
	contrReq: '',
	delvPlace: '',
	trsMth: '',
	salMth: '',
	contrDt: '',
	endDt: '',
	qualityReq: '',
	compCd: '',
	deptNm: '',
	deptCd: '',
	supplierNm: '',
	supplierCd: '',
	supplierId: '',
	contrNm: '',
	khContrNo: '',
	analyDataAccord: '',
	weightDataAccord: '',
	internalProduction: '',
	ifSupplemental: '0',
	purTy: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
	modifyName: '',
})

const ruleFormRef = ref()
const rulesSal = reactive({
	contrTy: [{
		required: true,
		message: '请选择合同类型',
		trigger: 'change' | 'blur'
	}],
	contrNm: [{
		required: true,
		message: '请输入合同名称',
		trigger: 'change' | 'blur'
	}],
	supplierNm: [{
		required: true,
		message: '请选择交易方名称',
		trigger: 'change' | 'blur'
	}],
	delvDate: [{
		required: true,
		message: '请输入预计交货日期',
		trigger: 'change' | 'blur'
	}],
	invMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	analyDataAccord: [{
		required: true,
		message: '请输入化验结算依据',
		trigger: 'change' | 'blur'
	}],
	weightDataAccord: [{
		required: true,
		message: '请输入计量结算依据',
		trigger: 'change' | 'blur'
	}],
	priceDcnMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	delvMth: [{
		required: true,
		message: '请输入交货方式',
		trigger: 'change' | 'blur'
	}],
	delvPlace: [{
		required: true,
		message: '请输入交货地点',
		trigger: 'change' | 'blur'
	}],
	ifAnnual: [{
		required: true,
		message: '请输入是否为长协合同',
		trigger: 'change' | 'blur'
	}],
	ifBid: [{
		required: true,
		message: '请输入是否招投标',
		trigger: 'change' | 'blur'
	}],
	contrDt: [{
		required: true,
		message: '请输入合同日期',
		trigger: 'change' | 'blur'
	}],
	addTime: [{
		required: true,
		message: '请输入录入日期',
		trigger: 'change' | 'blur'
	}],
	addName: [{
		required: true,
		message: '请输入录入人',
		trigger: 'change' | 'blur'
	}]
})
const rulesPur = reactive({
	contrTy: [{
		required: true,
		message: '请选择合同类型',
		trigger: 'change' | 'blur'
	}],
	contrNm: [{
		required: true,
		message: '请输入合同名称',
		trigger: 'change' | 'blur'
	}],
	supplierNm: [{
		required: true,
		message: '请选择交易方名称',
		trigger: 'change' | 'blur'
	}],
	delvDate: [{
		required: true,
		message: '请输入预计交货日期',
		trigger: 'change' | 'blur'
	}],
	invMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	analyDataAccord: [{
		required: true,
		message: '请输入化验结算依据',
		trigger: 'change' | 'blur'
	}],
	weightDataAccord: [{
		required: true,
		message: '请输入计量结算依据',
		trigger: 'change' | 'blur'
	}],
	priceDcnMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	delvMth: [{
		required: true,
		message: '请输入交货方式',
		trigger: 'change' | 'blur'
	}],
	delvPlace: [{
		required: true,
		message: '请输入交货地点',
		trigger: 'change' | 'blur'
	}],
	ifAnnual: [{
		required: true,
		message: '请输入是否为长协合同',
		trigger: 'change' | 'blur'
	}],
	ifBid: [{
		required: true,
		message: '请输入是否招投标',
		trigger: 'change' | 'blur'
	}],
	contrDt: [{
		required: true,
		message: '请输入合同日期',
		trigger: 'change' | 'blur'
	}],
	// internalProduction: [{
	// 	required: true,
	// 	message: '请输入是否内部生产',
	// 	trigger: 'change' | 'blur'
	// }],
	addTime: [{
		required: true,
		message: '请输入录入日期',
		trigger: 'change' | 'blur'
	}],
	addName: [{
		required: true,
		message: '请输入录入人',
		trigger: 'change' | 'blur'
	}]
})
const rulesService = reactive({
	contrTy: [{
		required: true,
		message: '请选择合同类型',
		trigger: 'change' | 'blur'
	}],
	contrNm: [{
		required: true,
		message: '请输入合同名称',
		trigger: 'change' | 'blur'
	}],
	supplierNm: [{
		required: true,
		message: '请选择交易方名称',
		trigger: 'change' | 'blur'
	}],
	delvDate: [{
		required: true,
		message: '请输入预计交货日期',
		trigger: 'change' | 'blur'
	}],
	invMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	analyDataAccord: [{
		required: true,
		message: '请输入化验结算依据',
		trigger: 'change' | 'blur'
	}],
	weightDataAccord: [{
		required: true,
		message: '请输入计量结算依据',
		trigger: 'change' | 'blur'
	}],
	priceDcnMth: [{
		required: true,
		message: '请输入结算方式',
		trigger: 'change' | 'blur'
	}],
	delvMth: [{
		required: true,
		message: '请输入交货方式',
		trigger: 'change' | 'blur'
	}],
	delvPlace: [{
		required: true,
		message: '请输入交货地点',
		trigger: 'change' | 'blur'
	}],
	ifAnnual: [{
		required: true,
		message: '请输入是否为长协合同',
		trigger: 'change' | 'blur'
	}],
	ifBid: [{
		required: true,
		message: '请输入是否招投标',
		trigger: 'change' | 'blur'
	}],
	contrDt: [{
		required: true,
		message: '请输入合同日期',
		trigger: 'change' | 'blur'
	}],
	addTime: [{
		required: true,
		message: '请输入录入日期',
		trigger: 'change' | 'blur'
	}],
	addName: [{
		required: true,
		message: '请输入录入人',
		trigger: 'change' | 'blur'
	}]
})

const handleAdd = () => {
	if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '请添加登录人所在公司'
		})
		return
	}

	const now = new Date();
	form.value = {
		contrTy: '',
		contrNo: '',
		dataAccord: '',
		approveDt: '',
		checkYn: '',
		riskInfo: '',
		conSts: '',
		signReqNo: '',
		delvDays: '',
		delvDate: '',
		priceDcnMth: '',
		signReqId: '',
		ifAnnual: '',
		delvMth: '',
		contrForm: '',
		processInstanceStatus: '',
		processInstanceId: '',
		ifBid: '',
		tempNm: '',
		invMth: '',
		toPlace: '',
		fromPlace: '',
		tempId: '',
		totalAmt: null,
		qty: null,
		conSts: '',
		remark: '',
		contrReq: '',
		delvPlace: '',
		trsMth: '',
		salMth: '',
		contrDt: '',
		endDt: '',
		qualityReq: '',
		compCd: deptTree[0].deptCode,
		deptCd: dept[0].deptCode,
		deptNm: dept[0].deptName,
		supplierNm: '',
		supplierCd: '',
		supplierId: '',
		contrNm: '',
		khContrNo: '',
		analyDataAccord: '',
		weightDataAccord: '',
		internalProduction: '',
		ifSupplemental: '0',
		purTy: '',
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
		modifyCode: '',
		modifyName: '',
	}

	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields();
	}
	title.value = '新增'
	readonly.value = false
	ifSupplemental.value = false
	disabledIfSupplemental.value = true
	dialogVisible.value = true
}
const tpType = ref('')
const dialogVisibleSal = ref(false)
const dialogVisiblePur = ref(false)
const dialogVisibleService = ref(false)
const handleChange = () => {
	dialogVisible.value = false
	title.value = '新增'
	switch (form.value.contrTy) {
		case '10':
			tpType.value = '10'
			form.value.fromPlace = company.value.sfhAddr != null  ? company.value.sfhAddr :  ''
			dialogVisibleSal.value = true
			break
		case '20':
			tpType.value = '1'
			form.value.toPlace = company.value.sfhAddr != null ? company.value.sfhAddr : ''
			dialogVisiblePur.value = true
			break
		case '30':
			tpType.value = ''
			dialogVisibleService.value = true
			break
	}
}

// 日期
const endDtError = ref('')
const disabledIfSupplemental = ref(true)
const handleContrDt = (val) => {
	if (new Date(val).getTime() >= new Date(form.value.endDt)) {
		endDtError.value = '终止日期不能早于合同日期'
		form.value.endDt = ''
		disabledIfSupplemental.value = false
	} else {
		endDtError.value = ''
		ifSupplemental.value = false
		disabledIfSupplemental.value = new Date(val).getTime() > new Date('2025-01-17').getTime()
	}
}
const handleEndDt = (val) => {
	endDtError.value = ''
}
const disabledDate = (time) => {
	return time.getTime() < new Date(form.value.contrDt).getTime() - 24 * 60 * 60 * 1000
}

watch(form.value.contrDt, (newVal) => {
	if (newVal) {
		// 如果合同日期已经选择，则更新终止日期的可选范围
		endDatePickerOptions.disabledDate = (time) => {
			return time.getTime() < new Date(form.value.contrDt).getTime() - 24 * 60 * 60 * 1000
		}
	}
})
/**
 *  新增
 */


/**
 * 保存、查看、删除
 */
const fId = ref('')
const AttachmentRefManual = ref(null)
const openDialog = () => {
}
const closeDialog = () => {
	fId.value = ''
	activeName.value = 'first'
	getTableData()
}

const handleSave = (ruleFormRef) => {

	ruleFormRef.validate((valid, fields) => {
		if (valid) {
			var url = 'cot/Head/save'
			var param = {
				json: JSON.stringify(form.value),
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					ElMessage({
						message: '保存成功',
						type: 'success',
					})
					form.value = response.data.data
					fId.value = form.value.id
					AttachmentRefManual.value.upload()
					getTableData()
					dialogVisible.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})

		} else {
			console.log('error submit!', fields)
		}
	})
}

const handleCancelSave = () => {
	fId.value = ''
	activeName.value = 'first'

	dialogVisible.value = false
	dialogVisibleSal.value = false
	dialogVisiblePur.value = false
	dialogVisibleService.value = false
	getTableData()
}

const handleEdit = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}

	title.value = '编辑'
	fId.value = row.id
	readonly.value = false
	form.value = { ...row }
	form.value.modifyCode = userCode
	form.value.modifyName = userName
	ifSupplemental.value = form.value.ifSupplemental === '1'
	disabledIfSupplemental.value = new Date(form.value.contrDt).getTime() > new Date('2025-01-17').getTime()
	switch (row.contrTy) {
		case '10':
			dialogVisibleSal.value = true
			break
		case '20':
			dialogVisiblePur.value = true
			break
		case '30':
			dialogVisibleService.value = true
			break
	}
}
const handleDelete = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	)
		.then(() => {
			var url = 'cot/Head/remove'
			var param = {
				id: row.id
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					ElMessage({
						type: 'success',
						message: '删除成功',
					})
					getTableData()
				} else {
					ElMessage({
						type: 'error',
						message: '删除失败' + response.data.msg
					});
				}
			});
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '已取消',
			})
		})
}

/**
 * 保存、查看、删除
 */


/**
 * 合同变更、批量导出、全部导出
 */
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}
// 合同变更
const cotChange = () => {
	if (multipleSelection.value.length != 1) {
		ElMessage({
			type: 'warning',
			message: '请选择一条数据变更！'
		})
		return
	}

	const flag = multipleSelection.value.find(item => item.conSts === 'B')
	if (flag === undefined) {
		ElMessage({
			type: 'warning',
			message: '合同状态不满足合同变更!'
		})
		return
	}

	if (!multipleSelection.value[0].contrNo.endsWith("XX")) {
		const flag = tableData.value.find(item => item.contrNo == multipleSelection.value[0].contrNo + "XX")
		if (flag) {
			ElMessage({
				type: 'warning',
				message: '已存在变更合同!'
			})
			return
		}
	}

	ElMessageBox.confirm(
		'确定要合同变更?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}).then(() => {
		var url = 'cot/Head/cotChange'
		var param = {
			json: JSON.stringify(multipleSelection.value)
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				ElMessage({
					type: 'success',
					message: '操作成功!',
				});
				getTableData()
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
			}
		})
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消变更',
		})
	})
}
// 批量导出
const handleExportBatch = () => {
	if (multipleSelection.value.length < 1) {
		ElMessage({
			type: 'warning',
			message: '请选择要导出的数据!'
		})
		return
	}

	var ids = []
	multipleSelection.value.forEach((item, index) => {
		ids.push(item.id)
	})
	location.href = import.meta.env.VITE_BASE_API +
		'/cot/Head/exportBatch?ids=' + encodeURIComponent(JSON.stringify(ids))
}
// 全部导出
const handleExportAll = () => {

	location.href = import.meta.env.VITE_BASE_API +
		'/cot/Head/exportAll?userId=' + userId +
		'&menuId=' + localStorage.getItem('menuId') +
		'&params=' + encodeURIComponent(JSON.stringify(query.value))
}

const handlePrintPreview = () => {
	if (form.value.id == undefined) {
		ElMessage({
			type: 'warning',
			message: '请先保存合同头!'
		})
		return
	}

	location.href = import.meta.env.VITE_BASE_API +
		'/cot/Head/downloadCot?userId=' + localStorage.getItem('userId') + '&id=' + encodeURIComponent(form.value.id)
}
/**
 * 合同变更、批量导出、全部导出
 */


/**
 * 客商
 */
const PopupRef = ref(null)
const handleSearchSupplier = () => {
	PopupRef.value.open()
}
const retu = (val) => {
	form.value.supplierId = val.id
	form.value.supplierCd = val.tradePartnerCode
	form.value.supplierNm = val.tradePartnerName

	switch (form.value.contrTy) {
		case '10': // 销售
			form.value.toPlace = val.sfhAddr // 目的地 收货地址
			break
		case '20': // 采购
			form.value.fromPlace = val.sfhAddr // 出发地 发货地址
			break
	}
}


/**
 * 客商
 */


/**
 * 签约请示
 */
const paramsSignRequest = ref({
	contractParty: ''
})
const PopupRefSignRequest = ref(null)
const handleSearchSignRequest = () => {
	paramsSignRequest.value.contractParty = form.value.supplierNm
	PopupRefSignRequest.value.open()
}
const retuSignRequest = (val) => {
	form.value.signReqNo = val.signReqNo
	form.value.signReqId = val.id
}
/**
 * 签约请示
 */


/**
 * 合同模版
 */
const queryCotTmp = ref({
	cmpCd: '',
	contTy: '',
	tempNm: '',
})
const PopupRefCotTmp = ref(null)
const handleSearchCotTmp = () => {
	queryCotTmp.value.cmpCd = form.value.compCd
	queryCotTmp.value.contTy = form.value.contrTy
	PopupRefCotTmp.value.open()
}
const retuCotTmp = (val) => {
	form.value.tempId = val.id
	form.value.tempNm = val.tempNm
}
const initTableData = () => {
	tableData.value = []

	var url = props.url
	var param = {
		page: currentPage.value,
		rows: pageSize.value,
		params: JSON.stringify(query.value)
	}

	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			tableData.value = response.data.data.records
			totalRows.value = response.data.data.total
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
/**
 * 合同模版
 */

const ifSupplemental = ref(false)
const updateIfSupplemental = (val) => {
	ifSupplemental.val = val
	form.value.ifSupplemental = ifSupplemental.value ? '1' : '0'
}

/**
 * 历史版本
 */
const dialogVisibleHistory = ref(false)
const tableDataHistory = ref([])
const handleHistory = () => {
	if (multipleSelection.value.length != 1) {
		ElMessage({
			type: 'warning',
			message: '请选择一条数据查询!'
		})
		return
	}

	if (multipleSelection.value[0].conSts != 'B') {
		ElMessage({
			type: 'warning',
			message: '只有生效合同才能查询历史版本!'
		})
		return
	}
	dialogVisibleHistory.value = true
	currentPageHistory.value = 1
	getTableDataHistory()

}

const getTableDataHistory = () => {
	var url = 'cot/Head/queryHistory'
	var param = {
		page: currentPageHistory.value,
		rows: pageSizeHistory.value,
		params: JSON.stringify({ contrNo: multipleSelection.value[0].contrNo })
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			tableDataHistory.value = response.data.data.records
			totalRowsHistory.value = response.data.data.total
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}

const currentPageHistory = ref(1)
const totalRowsHistory = ref(0)
const pageSizesHistory = ref([5, 10, 20, 30, 40])
const pageSizeHistory = ref(5)
const handleSizeChangeHistory = (val) => {
	pageSizeHistory.value = val
	getTableDataHistory()
}
const handleCurrentChangeHistory = (val) => {
	currentPage.value = val
	getTableDataHistory()
}


/**
 * 工作流相关
 */
const handlePaymentMethod3 = () => {
	if (multipleSelection.value.length != 1) {
		ElMessage({
			type: 'warning',
			message: '请选择一条数据提交！'
		})
		return
	}

	check(multipleSelection.value[0])
}

const check = (row) => {
	// if (!(item.conSts === 'A' || item.conSts === 'R' || item.conSts === 'F')) {
	// 	ElMessage({
	// 		type: 'warning',
	// 		message: '合同状态不满足提交流程!'
	// 	})
	// 	return
	// }

	var url = 'cot/Head/check'
	var param = {
		contrNo: row.contrNo
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == '0') {
			const scalesFlag = response.data.data.scalesFlag
			const amountFlag = response.data.data.amountFlag
			const settlementFlag = response.data.data.settlementFlag
			const uomFlag = response.data.data.uomFlag
			if (scalesFlag && amountFlag && settlementFlag && uomFlag) {
				// approvalProccess()
				handleSubmit(row)
			} else {
				if (!scalesFlag) {
					ElMessage.warning('收付款累计比例不为100%')
				}
				if (!amountFlag) {
					ElMessage.warning('收付款累计金额与合同金额不一致')
				}

				if (!settlementFlag) {
					ElMessage.warning('结算项目不符合条件')
				}

				if (!uomFlag) {
					ElMessage.warning('该采购合同存在物料单位为湿吨，结算标准未维护水分')
				}
			}

		} else {
			ElMessage({
				type: 'error',
				message: '操作失败!' + response.data.msg
			});
		}
	})
}

const flowId = ref('')
const handleSubmit = (row) => {
	if (row.ifSupplemental == '1') {
		switch (row.contrTy) {
			case '10':
				flowId.value = 'salContractSupplemental'
				break
			case '20':
				flowId.value = 'purContractSupplemental'
				break
			case '30':
				flowId.value = 'serviceContractSupplemental'
				break
		}
	} else {
		switch (row.contrTy) {
			case '10':
				flowId.value = 'salContract'
				break
			case '20':
				flowId.value = 'purContract'
				break
			case '30':
				flowId.value = 'serviceContract'
				break
		}
	}


	ElMessageBox.confirm(
		'确定提交审批?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}).then(() => {
		let variables = {
			id: row.id,
			totalAmt: row.totalAmt
		}
		return workflowSubmit(
			flowId.value,
			'合同流程',
			'初始化提交',
			JSON.stringify(variables),
			row.workId,
			row.trackId)
	}).then((result) => {
		if (result.status === 'success') {
			var url = 'cot/Head/saveProcessInfo'
			var process = {
				'id': row.id,
				'workId': result.workId,
				'trackId': result.trackId,
			}
			var param = {
				json: JSON.stringify(process),
			}
			console.log("process", process)
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code === 0) {
					form.value = response.data.data
					console.log("form.value", form.value)
					ElMessage({
						type: 'success',
						message: '提交审批成功',
					})
					getTableData()
				}
			})
		}
		else {
			ElMessage({
				type: 'error',
				message: '提交审批失败' + result.msg
			});
		}
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消提交',
		})
	})
}

const handleCancel = (row) => {
	ElMessageBox.confirm(
		'确定撤回审批?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	).then(() => {
		return workflowCancel(row.workId, row.trackId);
	}).then((result) => {
		if (result.status === 'success') {
			ElMessage({
				type: 'success',
				message: '撤回审批成功',
			})
			getTableData()
		} else {
			ElMessage({
				type: 'error',
				message: '撤回审批失败' + result.msg
			});
		}
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消提交',
		})
	})
}

const handleDetail = (row) => {
	if (row.ifSupplemental == '1') {
		switch (row.contrTy) {
			case '10':
				flowId.value = 'salContractSupplemental'
				break
			case '20':
				flowId.value = 'purContractSupplemental'
				break
			case '30':
				flowId.value = 'serviceContractSupplemental'
				break
		}
	} else {
		switch (row.contrTy) {
			case '10':
				flowId.value = 'salContract'
				break
			case '20':
				flowId.value = 'purContract'
				break
			case '30':
				flowId.value = 'serviceContract'
				break
		}
	}

	if (row.workId === null) {
		ElMessage({
			type: 'info',
			message: '无法查看',
		})
	} else {

		sessionStorage.setItem('workflowQuery', JSON.stringify({
			flowId: flowId.value,
			workId: row.workId,
			trackId: row.trackId,
			date: new Date().getTime()
		}))

		proxy.$router.push({
			path: '/workflow/detail',
		})
	}
}

const download = (row, val) => {

	var url = 'cot/Line/queryByContrId'
	var param = {
		page: 1,
		rows: 999999,
		params: JSON.stringify({ contrId: row.id })
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			// tableData.value = response.data.data.records
			// totalRows.value = response.data.data.total
			var json = {
				contrNm: row.contrNm,
				contrNo: row.contrNo,
				itemCd: response.data.data.records[0].itemCd,
				itemNm: response.data.data.records[0].itemNm,
				tradePartnerName: row.supplierNm,
				taxRate: response.data.data.records[0].taxRate,
				priceType: val,
			}
			var url2 = import.meta.env.VITE_BASE_API +
				'/sal/UpriceHead/download?json=' + encodeURIComponent(JSON.stringify(json)) + "&user=" + localStorage.getItem('userId');

			// 在新窗口打开该 URL
			window.open(url2, '_blank');

		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})



}


</script>

<style scoped>
::v-deep .dicSelect .el-select__wrapper .el-select__selected-item {
	color: #a8abb2;
}
</style>
