<template>
	<div>
		<el-card :body-style="cardBodyStyle">
			<el-form :inline="true">
				<el-form-item label="申请单号" style="margin-bottom: 5px;" prop="reqNo">
					<el-input v-model="query.reqNo" placeholder="请输入申请单号" clearable></el-input>
				</el-form-item>
				<el-form-item label="申请日期" style="margin-bottom: 0px;">
					<el-date-picker v-model="query.reqDate" type="daterange" style="width: 200px;"
						value-format="YYYY-MM-DD" format="YYYY-MM-DD" start-placeholder="开始时间"
						end-placeholder="结束时间"></el-date-picker>
				</el-form-item>
				<el-form-item label="收款单位" style="margin-bottom: 5px;" prop="tradePartnerName">
					<el-input v-model="query.tradePartnerName" placeholder="请输入收款单位" clearable></el-input>
				</el-form-item>
			</el-form>
		</el-card>

		<ButtonBar @search="handleSearch" @add="handleAdd"></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">
					<template #default="scope">
						<span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
					</template>
				</el-table-column>
				<el-table-column v-if="true" prop="reqNo" label="申请单号" width="200" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="payMth" label="付款方式" width="120" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="false" prop="compCd" label="公司代码" width="200" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="compNm" label="公司名称" width="120" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="addDeptName" label="部门名称" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="false" prop="reqDate" label="申请日期" width="120" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="payAmount" label="申请金额" width="120" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="addName" label="申请人" width="120" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="remark" label="备注" width="240" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="tradePartnerCode" label="单位编码" width="200" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="tradePartnerName" label="收款单位" width="150" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="accountNo" label="收款账号" width="200" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="bankNo" label="开户联行号" width="200" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="bankNm" label="开户行" width="120" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="payProv" label="省" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="payCity" label="市" width="100" header-align="center" align="center"
					show-overflow-tooltip>
				</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'">编辑
						</el-button>
						<el-button plain type="danger" @click="handleDelete(row)"
							v-if="row.workId === '' || row.workModel.opType === '1'">删除
						</el-button>
						<el-button plain type="success" @click="handleSubmit(row)"
							v-if="row.workId === '' || row.workModel.opType === '1'">发起
						</el-button>
						<el-button plain type="primary" @click="handleDetail(row)"
							v-if="row.workId !== ''">详情</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-button plain type="success" @click="handlePrintPreview(row)"
							v-if="row.workId !== '' && row.workModel.flowStatus === '170'">打印</el-button>
						<el-button plain type="warning" @click="handleAttachment(row)">附件</el-button>
					</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 fullscreen :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="1200px"
			top="5vh" @open="openDialog" @close="handleCancelSave">
			<el-form :model="form" label-width="110px" label-position="right" inline ref="ruleFormRef" :rules="rules">
				<el-row>
					<el-col :span="12">
						<el-card :body-style="cardBodyStyle" style="height:100%">
							<span>付款申请</span>
							<el-divider></el-divider>
							<el-form-item label="申请单号">
								<el-input v-model="form.reqNo" clearable style="width: 200px" disabled></el-input>
							</el-form-item>
							<el-form-item label="付款方式" prop="payMth">
								<el-select v-model="form.payMth" placeholder="请选择" style="width: 200px;">
									<el-option v-for="item in dicList.COM_PAY_MTH" :key="item.dicCode"
										:label="item.dicName" :value="item.dicCode" />
								</el-select>
							</el-form-item>
							<el-form-item label="公司名称" prop="compNm">
								<el-input v-model="form.compNm" clearable style="width: 200px" disabled></el-input>
							</el-form-item>
							<el-form-item label="部门名称" prop="addDeptName">
								<el-input v-model="form.addDeptName" clearable style="width: 200px" disabled></el-input>
							</el-form-item>
							<el-form-item label="申请金额">
								<el-input v-model="form.payAmount" clearable style="width: 200px" disabled></el-input>
							</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-input type="textarea" v-model="form.remark" clearable
									style="width: 540px"></el-input>
							</el-form-item>
						</el-card>
					</el-col>

					<el-col :span="12">
						<el-card :body-style="cardBodyStyle" style="height:100%">
							<span>账号信息</span>
							<el-divider></el-divider>
							<el-row>
								<el-col :span="12">
									<el-form-item label="单位编码" prop="tradePartnerCode">
										<el-input v-model="form.tradePartnerCode" clearable style="width: 200px"
											disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="收款单位" prop="tradePartnerName">
										<el-input v-model="form.tradePartnerName" clearable style="width: 200px"
											readonly>
											<template #append>
												<el-button :icon="Search" @click="handleSearchTradePartner" />
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="收款账号" prop="accountNo">
										<el-input v-model="form.accountNo" clearable style="width: 200px"
											disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="开户联行号" prop="bankNo">
										<el-input v-model="form.bankNo" clearable style="width: 200px" readonly>
											<template #append>
												<el-button :icon="Search" @click="handleSearchPayBank" />
											</template>
										</el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="开户行" prop="bankNm">
										<el-input v-model="form.bankNm" clearable style="width: 200px"
											disabled></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="省" prop="payProv">
										<el-select v-model="form.payProv" placeholder="请选择" style="width: 200px;"
											class="dicSelect" disabled>
											<el-option v-for="item in dicList.PROVINCE_CODE" :key="item.dicCode"
												:label="item.dicName" :value="item.dicCode" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="12">
									<el-form-item label="市" prop="payCity">
										<el-input v-model="form.payCity" clearable style="width: 200px"
											disabled></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</el-card>
					</el-col>
				</el-row>
			</el-form>

			<el-card :body-style="cardBodyStyle">
				<el-button plain type="primary" @click="handleAddLine" style="margin-bottom: 5px;">新增</el-button>
				<el-table :data="tableDataLine" border highlight-current-row
					@selection-change="handleSelectionChangeLine">
					<el-table-column type="selection" fixed></el-table-column>
					<el-table-column type="index" label="序号" align="center" width="60">
						<template #default="scope">
							<span>{{ scope.$index + (currentPageLine - 1) * pageSizeLine + 1 }}</span>
						</template>
					</el-table-column>
					<el-table-column v-if="true" prop="reqDate" label="申请支付日期" width="120" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="purContrCd" label="采购合同" min-width="200" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="purContrNm" label="采购合同名称" min-width="200" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="amount" label="合同额" min-width="120" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="payedAmount" label="已付金额" min-width="120" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="reqAmount" label="本次申请金额" min-width="120" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="reqTy" label="申请类型" min-width="100" header-align="center"
						align="center" show-overflow-tooltip :formatter="formatter">
					</el-table-column>
					<el-table-column v-if="true" prop="reqSts" label="申请状态" min-width="100" header-align="center"
						align="center" show-overflow-tooltip>
					</el-table-column>
					<el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
						<template #default="{ row }">
							<el-button plain type="warning" @click="handleEditLine(row)">编辑</el-button>
							<el-button plain type="danger" @click="handleDeleteLine(row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-card>

			<el-card :body-style="cardBodyStyle">
				<el-pagination :current-page="currentPageLine" :page-size="pageSizeLine" :page-sizes="pageSizesLine"
					:total="totalRowsLine" background="background" layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChangeLine" @current-change="handleCurrentChangeLine">
				</el-pagination>
			</el-card>

			<el-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisibleLine" width="800px"
				top="5vh" @open="openDialogLine">
				<el-form :model="formLine" label-width="110px" label-position="right" inline ref="ruleFormRefLine"
					:rules="rulesLine">
					<el-form-item label="采购合同" prop="purContrCd">
						<el-input v-model="formLine.purContrCd" clearable style="width: 200px" readonly>
							<template #append>
								<el-button :icon="Search" @click="handleSearchCot" />
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="采购合同名称" prop="purContrNm">
						<el-input v-model="formLine.purContrNm" clearable style="width: 200px" disabled></el-input>
					</el-form-item>
					<el-form-item label="合同额" prop="amount">
						<el-input v-model="formLine.amount" clearable style="width: 200px" disabled></el-input>
					</el-form-item>
					<el-form-item label="已付金额" prop="payedAmount">
						<el-input v-model="formLine.payedAmount" clearable style="width: 200px" disabled></el-input>
					</el-form-item>
					<el-form-item label="本次申请金额" prop="reqAmount">
						<el-input v-model="formLine.reqAmount" clearable style="width: 200px"></el-input>
					</el-form-item>
					<el-form-item label="申请类型" prop="reqTy">
						<el-select v-model="formLine.reqTy" placeholder="请选择" style="width: 200px;">
							<el-option v-for="item in dicList.PUR_PAY_TYPE" :key="item.dicCode" :label="item.dicName"
								:value="item.dicCode" />
						</el-select>
					</el-form-item>
					<el-form-item label="申请状态" prop="reqSts">
						<el-input v-model="formLine.reqSts" clearable style="width: 200px" disabled></el-input>
					</el-form-item>
					<el-form-item label="申请日期" prop="reqDate">
						<el-date-picker v-model="formLine.reqDate" type="date" style="width: 200px;"
							value-format="YYYY-MM-DD" format="YYYY-MM-DD" disabled></el-date-picker>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="success" @click="handleCheckLine(ruleFormRef)"
							:disabled="saveLineButton">保存</el-button>
						<el-button type="danger" @click="handleCancelSaveLine">取消</el-button>
					</div>
				</template>
			</el-dialog>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="success" plain @click="handleSave(ruleFormRef)">保存</el-button>
					<el-button type="danger" plain @click="handleCancelSave">取消</el-button>
				</div>
			</template>
		</el-dialog>

		<Popup_base_ks ref="PopupRef" @receive-from-child="retu"></Popup_base_ks>

		<PopupPayBank ref="PopupRefPayBank" @receive-from-child="retuPayBank"></PopupPayBank>

		<PopupCot ref="PopupRefCot" @receive-from-child="retuCot" :params="params"></PopupCot>

		<el-dialog :close-on-click-modal="false" draggable title="附件" v-model="dialogVisibleAttachment" width="1200px"
			top="5vh" @open="openDialog">
			<Attachment ref="AttachmentRefManual" :fId="fId" :uploadButton="uploadButton"></Attachment>
		</el-dialog>

	</div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Attachment from '@/components/Attachment.vue'
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue"
import PopupPayBank from '@/views/pur/components/PopupPayBank.vue'
import PopupCot from '@/views/cot/components/PopupCot.vue'

import {
	ref,
	reactive,
	onMounted,
	getCurrentInstance
} 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)

onMounted(() => {
	handleSearch()
	getDicList()
})


/**
 * 查询公司代码
 */
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 dicList = ref({
	COM_PAY_MTH: [],
	PUR_PAY_TYPE: [],
	PROVINCE_CODE: [],
})
const getDicList = () => {
	var url = 'framework/Common/querySelectorList'
	var param = {
		type: JSON.stringify(['COM_PAY_MTH', 'PUR_PAY_TYPE', 'PROVINCE_CODE'])
	}
	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 'payMth':
			cellValue = dicList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'reqTy':
			cellValue = dicList.value.PUR_PAY_TYPE.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'payProv':
			cellValue = dicList.value.PROVINCE_CODE.find(item => item.dicCode == cellValue)?.dicName
			break
	}

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


/**
 *   查询
 */
const query = ref({
	reqNo: '',
	reqDate: '',
	tradePartnerName: ''
})
const tableData = ref([])
const handleSearch = () => {
	console.log(query.value)
	currentPage.value = 1
	getTableData()
}
const getTableData = () => {
	var url = 'pur/PayReqHead/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(5)
const handleSizeChange = (val) => {
	pageSize.value = val
	getTableData()
}
const handleCurrentChange = (val) => {
	currentPage.value = val
	getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const title = ref('')
const dialogVisible = ref(false)
const form = ref({
	id: '',
	compCd: '',
	compNm: '',
	reqNo: '',
	reqPayDate: '',
	reqDate: '',
	reqSts: '',
	payMth: '',
	payAmount: '',
	paySts: '',
	actPayDate: '',
	actPayAmount: '',
	remark: '',
	tradePartnerId: '',
	tradePartnerCode: '',
	tradePartnerName: '',
	accountNo: '',
	bankNo: '',
	bankNm: '',
	payProv: '',
	payCity: '',
	actAccountNo: '',
	actAccountNm: '',
	processInstanceId: '',
	processInstanceStatus: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyId: '',
	modifyCode: '',
	modifyTime: '',
	cancelId: '',
	cancelCode: '',
	cancelName: '',
})
const ruleFormRef = ref()
const rules = reactive({
	reqPayDate: [{
		required: true,
		message: '付款日期必须录入',
	}],
	payMth: [{
		required: true,
		message: '付款方式必须录入',
	}],
	compNm: [{
		required: true,
		message: '公司名称必须录入',
	}],
	addDeptName: [{
		required: true,
		message: '部门名称必须录入',
	}],
	reqDate: [{
		required: true,
		message: '申请日期必须录入',
	}],
	addName: [{
		required: true,
		message: '申请人必须录入',
	}],
	tradePartnerCode: [{
		required: true,
		message: '单位编码必须录入',
	}],
	tradePartnerName: [{
		required: true,
		message: '收款单位必须录入',
	}],
	accountNo: [{
		required: true,
		message: '收款账号必须录入',
	}],
	bankNo: [{
		required: true,
		message: '开户联行号必须录入',
	}],
	bankNm: [{
		required: true,
		message: '开户行必须录入',
	}],
	payProv: [{
		required: true,
		message: '省必须录入',
	}],
	payCity: [{
		required: true,
		message: '市必须录入',
	}],
})
const handleAdd = () => {
	if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '请添加登录人所在公司'
		})
		return
	}

	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}

	const now = new Date();
	form.value = {
		id: '',
		compCd: deptTree[0].deptCode,
		compNm: deptTree[0].deptName,
		reqNo: '',
		reqPayDate: '',
		reqDate: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
		reqSts: '',
		payMth: '',
		payAmount: '',
		paySts: '',
		actPayDate: '',
		actPayAmount: '',
		remark: '',
		tradePartnerId: '',
		tradePartnerCode: '',
		tradePartnerName: '',
		accountNo: '',
		bankNo: '',
		bankNm: '',
		payProv: '',
		payCity: '',
		actAccountNo: '',
		actAccountNm: '',
		processInstanceId: '',
		processInstanceStatus: '',
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].Id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyId: '',
		modifyCode: '',
		modifyTime: '',
		cancelId: '',
		cancelCode: '',
		cancelName: '',
	}
	tableDataLine.value = []
	title.value = '新增'
	dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除、打印、附件
 */
const handleSave = (ruleFormRef) => {
	ruleFormRef.validate((valid, fields) => {
		if (valid) {
			var url = 'pur/PayReqHead/save'
			var param = {
				json: JSON.stringify(form.value),
			}

			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					form.value = response.data.data
					ElMessage({
						message: '保存成功',
						type: 'success',
					})
					getTableData()
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}
const handleCancelSave = () => {
	form.value = {
		id: '',
		compCd: '',
		compNm: '',
		reqNo: '',
		reqPayDate: '',
		reqDate: '',
		reqSts: '',
		payMth: '',
		payAmount: '',
		paySts: '',
		actPayDate: '',
		actPayAmount: '',
		remark: '',
		tradePartnerId: '',
		tradePartnerCode: '',
		tradePartnerName: '',
		accountNo: '',
		bankNo: '',
		bankNm: '',
		payProv: '',
		payCity: '',
		actAccountNo: '',
		actAccountNm: '',
		processInstanceId: '',
		processInstanceStatus: '',
		addId: '',
		addCode: '',
		addName: '',
		addDeptId: '',
		addDeptCode: '',
		addDeptName: '',
		addTime: '',
		modifyId: '',
		modifyCode: '',
		modifyTime: '',
		cancelId: '',
		cancelCode: '',
		cancelName: '',
	}
	dialogVisible.value = false
}
const handleEdit = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields();
	}
	title.value = '编辑'
	form.value = { ...row }
	queryLine.value.reqNo = form.value.reqNo
	getTableDataLine()
	dialogVisible.value = true
}
const handleDelete = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	)
		.then(() => {
			var url = 'pur/PayReqHead/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 handlePrintPreview = (row) => {
	location.href = import.meta.env.VITE_BASE_API +
		'/pur/PayReqHead/downloadPayReq?userId=' + localStorage.getItem('userId') + '&id=' + encodeURIComponent(row.id)
}

const fId = ref('')
const uploadButton = ref(null)
const AttachmentRefManual = ref(null)
const dialogVisibleAttachment = ref(false)
const handleAttachment = (row) => {
	fId.value = row.id
	uploadButton.value = row.workId === '' || row.workModel.opType === '1'
	dialogVisibleAttachment.value = true
}
/**
 * 保存、修改、删除、查看、打印、附件
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}
/**
 * 收款单位
 */
const PopupRef = ref(null)
const handleSearchTradePartner = () => {
	PopupRef.value.open()
}
const retu = (val) => {
	form.value.tradePartnerId = val.id
	form.value.tradePartnerName = val.tradePartnerName
	form.value.tradePartnerCode = val.tradePartnerCode
}

/**
 * 银行
 */
const PopupRefPayBank = ref(null)
const handleSearchPayBank = () => {
	PopupRefPayBank.value.open()
}
const retuPayBank = (val) => {
	form.value.accountNo = val.beneficiaryAccount
	form.value.bankNo = val.bankNo
	form.value.bankNm = val.bankNm
	form.value.payProv = val.bankProvince
	form.value.payCity = val.bankCity
}


/**
 *   查询 -- 行
 */
const queryLine = ref({
	reqNo: '',
})
const tableDataLine = ref([])
const getTableDataLine = () => {
	var url = 'pur/PayReqLine/query'
	var param = {
		page: currentPageLine.value,
		rows: pageSizeLine.value,
		params: JSON.stringify(queryLine.value)
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			tableDataLine.value = response.data.data.records
			totalRowsLine.value = response.data.data.total
			form.value.payAmount = JSON.stringify(tableData.value) === JSON.stringify(new Array()) ? '' : tableDataLine.value.reduce((sum, current) => sum + current.reqAmount, 0)
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
/**
 *   查询
 */


/**
 * 分页
 */
const currentPageLine = ref(1)
const totalRowsLine = ref(0)
const pageSizesLine = ref([5, 10, 20, 30, 40])
const pageSizeLine = ref(5)
const handleSizeChangeLine = (val) => {
	pageSizeLine.value = val
	getTableDataLine()
}
const handleCurrentChangeLine = (val) => {
	currentPageLine.value = val
	getTableDataLine()
}
/**
 * 分页
 */


/**
 * 新增
 */
const titleLine = ref('')
const saveLineButton = ref(false)
const dialogVisibleLine = ref(false)
const formLine = ref({
	pId: '',
	reqNo: '',
	purContrCd: '',
	purContrNm: '',
	amount: '',
	payedAmount: '',
	reqAmount: '',
	reqTy: '',
	reqSts: '',
	reqDate: '',
	cotHead: '',
})
const ruleFormRefLine = ref()
const rulesLine = reactive({
	purContrCd: [{
		required: true,
		message: '请输入采购合同',
		trigger: 'change' | 'blur'
	}],
	purContrNm: [{
		required: true,
		message: '请输入采购合同名称',
		trigger: 'change' | 'blur'
	}],
	amount: [{
		required: true,
		message: '请输入合同额',
		trigger: 'change' | 'blur'
	}],
	payedAmount: [{
		required: true,
		message: '请输入已付金额',
		trigger: 'change' | 'blur'
	}],
	reqAmount: [{
		required: true,
		message: '请输入本次申请金额',
		trigger: 'change' | 'blur'
	}],
	reqTy: [{
		required: true,
		message: '请输入申请类型',
		trigger: 'change' | 'blur'
	}],
})
const handleAddLine = () => {
	if (!form.value.reqNo) {
		ElMessage({
			type: 'warning',
			message: '请先保存付款申请单头！'
		})
		return
	}

	if (ruleFormRefLine.value) {
		ruleFormRefLine.value.resetFields()
	}

	const now = new Date();
	formLine.value = {
		pId: form.value.id,
		reqNo: form.value.reqNo,
		purContrCd: '',
		purContrNm: '',
		amount: '',
		payedAmount: '',
		reqAmount: '',
		reqTy: '',
		reqSts: '',
		reqDate: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`

	}
	titleLine.value = '新增'
	dialogVisibleLine.value = true
	saveLineButton.value = false
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
const openDialogLine = () => {
}
const handleCheckLine = (ruleFormRefLine) => {
	var url = 'pur/PayReqLine/check'
	var param = {
		json: JSON.stringify(formLine.value),
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == 0) {
			ElMessage({
				message: '查询成功',
				type: 'success',
			})
			handleSaveLine(ruleFormRefLine)
		} else {
			ElMessage({
				message: '操作失败！' + response.data.msg,
				type: 'error'
			})
		}
	})
}
const handleSaveLine = (ruleFormRefLine) => {

	ruleFormRefLine.validate((valid, fields) => {
		if (valid) {
			var url = 'pur/PayReqLine/save'
			var param = {
				json: JSON.stringify(formLine.value),
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					ElMessage({
						message: '保存成功',
						type: 'success',
					})
					formLine.value = response.data.data
					queryLine.value.reqNo = form.value.reqNo
					getTableDataLine()
					getTableData()
					dialogVisibleLine.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})

		} else {
			console.log('error submit!', fields)
		}
	})
}
const handleCancelSaveLine = () => {
	formLine.value = {
		purContrCd: '',
		purContrNm: '',
		amount: '',
		payedAmount: '',
		reqAmount: '',
		reqNo: form.value.reqNo,
		pId: form.value.id
	}
	dialogVisibleLine.value = false
}
const handleEditLine = (row) => {
	if (ruleFormRefLine.value) {
		ruleFormRefLine.value.resetFields();
	}
	titleLine.value = '编辑'
	formLine.value = { ...row }
	saveLineButton.value = false
	dialogVisibleLine.value = true
}
const handleDeleteLine = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}).then(() => {
		var url = 'pur/PayReqLine/remove'
		var param = {
			id: row.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {
				ElMessage({
					type: 'success',
					message: '删除成功',
				})
				getTableDataLine()
			} else {
				ElMessage({
					type: 'error',
					message: '删除失败' + response.data.msg
				});
			}
		});
	})
	.catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
}
/**
 * 保存、修改、删除
 */


/**
 *  采购合同
 */
const params = ref({
	contrTy: '',
	supplierCd: '',
})
const PopupRefCot = ref(null)
const handleSearchCot = () => {
	params.value = {
		contrTy: '20',
		supplierCd: form.value.tradePartnerCode,
	}
	PopupRefCot.value.open()
}
const retuCot = (val) => {
	formLine.value.purContrCd = val.contrNo
	formLine.value.purContrNm = val.contrNm
	formLine.value.amount = val.totalAmt
	formLine.value.cotHead = val
	calculatePayedAmount(formLine.value.purContrCd)
}
const calculatePayedAmount = (purContrCd) => {
	var url = 'pur/PayReqLine/queryPayedAmount'
	var param = {
		purContrCd: purContrCd,
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == 0) {
			ElMessage({
				message: '查询成功',
				type: 'success',
			})
			formLine.value.payedAmount = response.data.data
		} else {
			ElMessage({
				message: '操作失败' + response.data.msg,
				type: 'error'
			})
		}
	})
}
/**
 * 选择 采购订单头
 */


/**
 * 工作流相关
 */
 const flowId = ref('purPayReqFinance')
const handleSubmit = (row) => {
	ElMessageBox.confirm(
		'确定提交审批?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}).then(() => {
		let variables = {
			id: row.id,
		}
		return workflowSubmit(
			flowId.value,
			'测试流程请示',
			'初始化提交',
			JSON.stringify(variables),
			row.workId,
			row.trackId)
	}).then((result) => {
		if (result.status === 'success') {
			var url = 'pur/PayReqHead/saveProcessInfo'
			var process = {
				'id': row.id,
				'workId': result.workId,
				'trackId': result.trackId,
			}
			var param = {
				json: JSON.stringify(process),
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code === 0) {
					form.value = response.data.data
					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.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',
		})
	}
}
</script>

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