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

		<ButtonBar @search="handleSearch" @add="handleAdd" @remove="handleRemoveBatch" @edit="handleEditBatch"></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="signReqNm" label="签约请示名称" width="150" header-align="center"
					align="center" show-overflow-tooltip fixed></el-table-column>
				<el-table-column v-if="true" prop="signReqNo" label="签约请示号" width="150" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120"
					header-align="center" align="center" show-overflow-tooltip>
					<template #default="{ row }">
						<div>
							<el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
								row.workModel.flowStatusName }}</el-tag>
							<el-tag type="success"
								v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
									row.workModel.flowStatusName }}</el-tag>
							<el-tag type="danger"
								v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
									row.workModel.flowStatusName }}</el-tag>
							<el-tag type="warning" v-else>'---'</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column v-if="true" prop="workModel.flowNode" label="当前节点" width="120" header-align="center"
					align="center" show-overflow-tooltip>
					<template #default="{ row }">
						<div>
							<el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
								row.workModel.flowNode
							}}</el-tag>
							<el-tag type="success"
								v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
									row.workModel.flowNode }}</el-tag>
							<el-tag type="danger"
								v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
									row.workModel.flowNode }}</el-tag>
							<el-tag type="warning" v-else>'---'</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column v-if="true" prop="contractParty" label="交易方名称" width="150" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="signDt" label="预计签约日期" width="120" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="reqDt" label="请示日期" width="120" header-align="center" align="center"
					show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="contrPrice" label="预计签约金额" width="120" header-align="center"
					align="right" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="estProfit" label="预计利润" width="120" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="subMatter" label="合同标的物" width="180" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="fundDesc" label="收付款说明" width="180" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="riskPoints" label="主要风险点及应对措施" width="180" header-align="center"
					align="center" show-overflow-tooltip></el-table-column>
				<el-table-column v-if="true" prop="otherInformation" label="其他情况说明" width="180" 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-show="row.workId === '' || row.workModel.opType === '1'">编辑
						</el-button>
						<el-button plain type="danger" @click="handleDelete(row)"
							v-show="row.workId === '' || row.workModel.opType === '1'">删除
						</el-button>
						<el-button plain type="success" @click="handleSubmit(row)"
							v-show="row.workId === '' || row.workModel.opType === '1'">发起
						</el-button>
						<el-button plain type="primary" @click="handleDetail(row)"
							v-show="row.workId !== ''">详情</el-button>
						<el-button plain type="info" @click="handleCancel(row)"
							v-show="row.workId !== '' && row.workModel.opType !== '1' && row.workModel.flowStatus !== '170'">撤回</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 :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="1200px"
			top="5vh" @open="openDialog">
			<el-form :model="form" label-width="160px" label-position="right" inline ref="ruleFormRef" :rules="rules">
				<el-row>
					<el-col :span="6">
						<el-form-item label="签约请示名称" prop="signReqNm">
							<el-input v-model="form.signReqNm" clearable style="width: 140px"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="签约请示号">
							<el-input v-model="form.signReqNo" clearable style="width: 140px" disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="流程状态">
							<el-input v-model="form.workModel.flowStatusName" clearable style="width: 140px"
								disabled></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="交易方名称" prop="contractParty">
							<el-input v-model="form.contractParty" clearable readonly style="width: 140px">
								<template #append>
									<el-button :icon="Search" @click="handleSearchContractParty" />
								</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="预计签约日期" prop="signDt">
							<el-date-picker v-model="form.signDt" type="date" style="width: 140px;"
								value-format="YYYY-MM-DD" format="YYYY-MM-DD">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="请示日期" prop="reqDt">
							<el-date-picker v-model="form.reqDt" type="date" style="width: 140px;" disabled
								value-format="YYYY-MM-DD" format="YYYY-MM-DD">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="预计签约金额（元）" prop="contrPrice">
							<el-input-number v-model="form.contrPrice" :precision="2" :step="0.1"
								controls-position="right" clearable style="width: 140px"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="预计利润" prop="estProfit">
							<el-input-number v-model="form.estProfit" :precision="2" :step="0.1"
								controls-position="right" clearable style="width: 140px"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="合同标的物">
							<el-input v-model="form.subMatter" clearable style="width: 430px"
								type="textarea"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="收付款说明">
							<el-input v-model="form.fundDesc" clearable style="width: 430px"
								type="textarea"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="主要风险点及应对措施">
							<el-input v-model="form.riskPoints" clearable style="width: 430px"
								type="textarea"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="其他情况说明">
							<el-input v-model="form.otherInformation" clearable style="width: 430px"
								type="textarea"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<Attachment ref="AttachmentRefManual" :fId="fId" v-if="form.id"></Attachment>
			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="success" @click="handleSave(ruleFormRef)">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
				</div>
			</template>
		</el-dialog>

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

</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Popup_base_ks from "@/views/bas/Popup_base_ks.vue";
import Attachment from '@/components/Attachment.vue'

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

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

const {
	proxy
} = getCurrentInstance()

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

onMounted(() => {
	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 query = ref({
	signReqNo: '',
	signReqNm: '',
	contractParty: '',
	subMatter: '',
	reqDt: '',
	addName: ''
})
const tableData = ref([])
const handleSearch = () => {
	currentPage.value = 1
	getTableData()
}
const getTableData = () => {
	var url = 'cot/SignRequest/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') {
			console.log(response.data.data.records)
			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: '',
	signReqNm: '',
	signDt: '',
	otherInformation: '',
	estProfit: null,
	ProcessInstanceSts: '',
	benefitNo: '',
	riskPoints: '',
	fundDesc: '',
	benefitName: '',
	contractParty: '',
	subMatter: '',
	contrPrice: null,
	processRemark: '',
	reqDt: '',
	signReqNo: '',
	compCd: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	workModel: {
		flowStatusName: ''
	}
})
const ruleFormRef = ref()
const rules = reactive({
	signReqNm: [{
		required: true,
		message: '请输入签约请示名称',
		trigger: 'change' | 'blur'
	}],
	contractParty: [{
		required: true,
		message: '请选择交易方名称',
		trigger: 'change' | 'blur'
	}],
	signDt: [{
		required: true,
		message: '请输入预计签约日期',
		trigger: 'change' | 'blur'
	}],
	reqDt: [{
		required: true,
		message: '请输入请示日期',
		trigger: 'change' | 'blur'
	}],
	contrPrice: [{
		required: true,
		message: '请输入预计签约金额',
		trigger: 'change' | 'blur'
	}],
})
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 = {
		signReqNm: '',
		signDt: '',
		otherInformation: '',
		estProfit: null,
		ProcessInstanceSts: '',
		benefitNo: '',
		riskPoints: '',
		fundDesc: '',
		benefitName: '',
		contractParty: '',
		subMatter: '',
		contrPrice: null,
		processRemark: '',
		reqDt: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
		signReqNo: '',
		addName: '',
		compCd: deptTree[0].deptCode,
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		workModel: {
			flowStatusName: ''
		}
	}

	title.value = '新增'
	dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */
// 手动上传
const fId = ref('')
const AttachmentRefManual = ref(null)
const openDialog = () => {
}
const handleSave = (ruleFormRef) => {
	ruleFormRef.validate((valid, fields) => {
		if (valid) {
			var url = 'cot/SignRequest/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()
					fId.value = form.value.id
					AttachmentRefManual.value.upload()
					// dialogVisible.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})

		} else {
			console.log('error submit!', fields)
		}
	})
}
const handleCancelSave = () => {
	dialogVisible.value = false
}
const handleEdit = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}

	title.value = '编辑'
	fId.value = row.id
	form.value = { ...row }
	dialogVisible.value = true
}
const handleDelete = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
).then(() => {
		var url = 'cot/SignRequest/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 handlePaymentMethod1 = (row) => {
	ElMessageBox.confirm(
		'确定提交审批?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	)
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '已取消',
			})
		})
}
/**
 * 保存、修改、删除
 */


/**
 * 保存、修改、删除
 */
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}
const handleRemoveBatch = () => {
	if (multipleSelection.value.length < 1) {
		ElMessage({
			type: 'warning',
			message: '请选择要删除的数据!'
		})
		return
	}

	const flag = multipleSelection.value.find(row => !(row.workId === '' || row.workModel.opType === '1'))
	if (flag) {
		ElMessage({
			type: 'warning',
			message: '存在签约请示不能进行删除!'
		})
		return
	}


	ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		var ids = []
		multipleSelection.value.forEach((item, index) => {
			ids.push(item.id)
		})
		var url = 'cot/SignRequest/removeBatch'
		var param = {
			ids: JSON.stringify(ids)
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				ElMessage({
					type: 'success',
					message: '操作成功!',
				});
				getTableData()
				dialogVisible.value = false
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				});
			}
		})
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消删除'
		})
	})
}
const handleEditBatch = () => {
	if (multipleSelection.value.length != 1) {
		ElMessage({
			type: 'warning',
			message: '请选择一条数据编辑!'
		})
		return
	}

	const row = multipleSelection.value[0]

	if (!(row.workId === '' || row.workModel.opType === '1')) {
		ElMessage({
			type: 'warning',
			message: '该行不能进行编辑!'
		})
		return
	}

	handleEdit(row)
}
const handleUpload = () => {
	console.log('handleUpload')
}
const handleDownload = () => {
	console.log('handleDownload')
}
const handleImport = () => {
	console.log('handleImport')
}
const handleExport = () => {
	console.log('handleExport')
}
/**
 * 保存、修改、删除
 */


/**
 * 客商
 */
const tpType = ref('')
const PopupRef = ref(null)
const handleSearchContractParty = () => {
	PopupRef.value.open()
}
const retu = (val) => {
	form.value.contractParty = val.tradePartnerName
}
/**
 * 客商
 */


/**
 * 工作流相关
 */
const flowId = ref('signRequest')
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') {
			// 将结果返回的workId和trackId保存
			var url = 'cot/SignRequest/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((error) => {
		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></style>
