<template>
	<div>
		<el-card :body-style="cardBodyStyle" v-if="!readonly">
			<el-button plain type="primary" @click="handleAdd" :disabled="disabled">新增</el-button>
		</el-card>

		<el-card :body-style="cardBodyStyle">
			<el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
				height="245">
				<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="payFlag" label="收付款节点" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="payMth" label="收付款方式" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="accountPeriod" label="账期" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="scales" label="比例(%)" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="amount" label="金额" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>

				<el-table-column label="操作" header-align="center" align="center" width="200px">
					<template #default="scope">
						<el-button plain type="warning" @click="handleEdit(scope.row)" v-if="!readonly">编辑</el-button>
						<el-button plain type="primary" @click="handleDetail(scope.row)" v-if="readonly">查看</el-button>
						<el-button plain type="danger" @click="handleDelete(scope.row)" v-if="!readonly && !disabled">删除</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="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
				<el-form-item label="收付款节点" prop="payFlag">
					<el-select v-model="form.payFlag" placeholder="请选择" clearable style="width: 200px" :disabled="disabled"
						@change="validateAccountPeriod" >
						<el-option v-for="item in dicList.PAY_FLAG" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" :disabled="item.dicCode === '30' && props.cotHead.contrTy == '20'" />
					</el-select>
				</el-form-item>
				<el-form-item label="收付款方式" prop="payMth">
					<el-select v-model="form.payMth" placeholder="请选择" clearable 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="accountPeriod" :error="accountPeriodError">
					<el-input v-model="form.accountPeriod" clearable style="width: 200px"
						@input="disableValidateAccountPeriod" :readonly="readonly"></el-input>
				</el-form-item>
				<el-form-item label="比例(%)" prop="scales">
					<el-input-number v-model="form.scales" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" @input="updateScales" :readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="金额" prop="amount">
					<el-input-number v-model="form.amount" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" @input="updateAmount" :readonly="readonly"></el-input-number>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="success" @click="handleSave(ruleFormRef)" v-if="!readonly"
						:loading="loading">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'

import {
	ref,
	reactive,
	onMounted,
	getCurrentInstance,
	defineProps,
	watch
} from 'vue'

const {
	proxy
} = getCurrentInstance()

import tools from '@/tools'
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
	getDictList()
	tableData.value = []
	disabled.value = false
	if (props.cotHead.id) {
		handleSearch()
		if(props.cotHead.conSts === 'R') {
			getDelvList(props.cotHead.contrNo.split('X')[0])
		}
	}
})

const props = defineProps({
	cotHead: {
		type: Object,
		required: true,
	},
	dialogVisibleCot: {
		type: Boolean,
		required: true,
	},
	readonly: {
		type: Boolean,
		required: true,
	},
	deleteButton: {
		type: Boolean,
		default: () => false
	}
})

watch(() => props.cotHead, (newVal, oldVal) => {
	tableData.value = []
	disabled.value = false
	if (props.cotHead.id) {
		handleSearch()
		if(props.cotHead.conSts === 'R') {
			getDelvList(props.cotHead.contrNo.split('X')[0])
		}
	}
})
watch(() => props.cotHead.totalAmt, (newVal, oldVal) => {
	tableData.value = []
	if (props.cotHead.totalAmt != null) {
		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 dicList = ref({
	PAY_FLAG: [],
	COM_PAY_MTH: []
})
const getDictList = () => {
	var url = 'framework/Common/querySelectorList'
	var param = {
		type: JSON.stringify(['PAY_FLAG', 'COM_PAY_MTH'])
	}
	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 'payFlag':
			cellValue = dicList.value.PAY_FLAG.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'payMth':
			cellValue = dicList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
			break
	}

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



/**
* 查询
*/
const query = ref({
	// contrId: '',
	contrNo: ''
})
const tableData = ref([])
const handleSearch = () => {
	currentPage.value = 1
	getTableData()
}
const getTableData = () => {
	// query.value.contrId = props.cotHead.id
	query.value.contrNo = props.cotHead.contrNo

	var url = 'cot/Invtype/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
			// calculateScales()
		} 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: '',
	contrId: '',
	contrCd: '',
	payMth: '',
	payFlag: '',
	accountPeriod: '',
	scales: null,
	amount: null,
	notification: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
	modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
	payFlag: [
		{ required: true, message: '收付款节点必须录入', trigger: 'change' },
	],
	payMth: [
		{ required: true, message: '收付款方式必须录入', trigger: 'change' },
	],
	scales: [
		{ required: true, message: '比例必须录入', trigger: 'blur' },
		{ type: 'number', message: '比例必须是数字', trigger: ['blur', 'change'] },
	],
	amount: [
		{ required: true, message: '金额必须录入', trigger: 'blur' },
		{ type: 'number', message: '金额必须是数字', trigger: ['blur', 'change'] },
	],
})
const handleAdd = () => {
	if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '请添加登录人所在公司'
		})
		return
	}

	if (props.cotHead.contrNo == '') {
		ElMessage({
			type: 'warning',
			message: '请先保存合同头！'
		})
		return
	}

	if (props.cotHead.totalAmt === '') {
		ElMessage({
			type: 'warning',
			message: '合同金额不能为空'
		})
		return
	}

	if (props.cotHead.totalAmt <= 0) {
		ElMessage({
			type: 'warning',
			message: '合同金额必须大于0'
		})
		return
	}

	form.value = {
		id: '',
		contrId: props.cotHead.id,
		contrCd: props.cotHead.contrNo,
		payMth: '',
		payFlag: '',
		accountPeriod: '',
		scales: null,
		amount: null,
		notification: '',
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyCode: '',
		modifyName: '',
	}

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

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


/**
* 保存、修改、删除
*/
const openDialog = () => { }
const loading = ref(false)
const handleSave = (ruleFormRef) => {

	if (accountPeriodError.value == '账期必须录入') {
		return
	}

	ruleFormRef.validate((valid, fields) => {
		if (valid) {
			loading.value = true

			var url = 'cot/Invtype/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
					getTableData()
					loading.value = false
					dialogVisible.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
					loading.value = false
				}
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}
const handleCancelSave = () => {
	dialogVisible.value = false
}
const readonly = ref(props.readonly)
const handleEdit = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}
	title.value = '编辑'
	form.value = { ...row }
	form.value.modifyCode = userCode
	form.value.modifyName = userName
	readonly.value = false
	dialogVisible.value = true
}
const handleDetail = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}
	title.value = '查看'
	form.value = { ...row }
	readonly.value = true
	dialogVisible.value = true
}
const handleDelete = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	).then(() => {
		var url = 'cot/Invtype/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 accountPeriodError = ref('')
const validateAccountPeriod = (val) => {
	if (form.value.id == '') {
		const payFlag = tableData.value.find(item => item.payFlag === form.value.payFlag)
		if (payFlag) {
			ElMessage({
				type: 'warning',
				message: '该收付款节点已存在!'
			})
			form.value.payFlag = ''
			return
		}

		if (props.cotHead.contrTy === '10') {
			const oppositePayFlag = form.value.payFlag === '10' ? '20' : (form.value.payFlag === '20' ? '10' : null);
			const flag = tableData.value.find(item => item.payFlag === oppositePayFlag);
			if (flag) {
				ElMessage({
					type: 'warning',
					message: '预付款和结算款不能同时存在！'
				})
				form.value.payFlag = ''
				return
			}
		}
	}

	const flag = (val === '20' && props.cotHead.priceDcnMth === '20') || val === '30'
	if (flag && form.value.accountPeriod == '') {
		accountPeriodError.value = '账期必须录入'
	} else {
		accountPeriodError.value = ''
	}

	updateScales(form.value.scales)
}

const disableValidateAccountPeriod = (val) => {
	const flag = (form.value.payFlag === '20' && props.cotHead.priceDcnMth === '20') || form.value.payFlag === '30'
	if (flag && form.value.accountPeriod == '') {
		accountPeriodError.value = '账期必须录入'
	} else {
		accountPeriodError.value = ''
	}
}
/**
* 收付款结点为结算后支付、质保金时 账期必须录入
*/


/**
* 比例与金额
*/
const updateScales = (val) => {
	// form.value.scales = form.value.scales && val === null ? form.value.scales : val
	form.value.scales = val
	form.value.amount = form.value.scales === null ? '' : (form.value.scales / 100) * props.cotHead.totalAmt
	updateScalesAndAmount(form.value.scales, form.value.amount)
}

const updateAmount = (val) => {
	// form.value.amount = form.value.amount && val === null ? form.value.amount : val
	form.value.amount = val
	form.value.scales = form.value.amount === null ? '' : (form.value.amount / props.cotHead.totalAmt) * 100
	updateScalesAndAmount(form.value.scales, form.value.amount)
}

const updateScalesAndAmount = (scales, amount) => {
	if (rules.scales.length == 3) {
		rules.scales.pop()
	}
	if (rules.amount.length == 3) {
		rules.amount.pop()
	}
	ruleFormRef.value.clearValidate('scales')
	ruleFormRef.value.clearValidate('amount')

	if (scales == null) {
		ruleFormRef.value.validateField('scales', (valid) => { })
		ruleFormRef.value.validateField('amount', (valid) => { })
		return
	}

	if (Number(scales) <= 0) {
		rules.scales[2] = { message: '比例不能低于0%', trigger: 'blur' }
		ruleFormRef.value.validateField('scales', (valid) => { })

		rules.amount[2] = { message: '金额不能低于0', trigger: 'blur' }
		ruleFormRef.value.validateField('amount', (valid) => { })
		return
	}

	const sumScales = Number(tableData.value.filter(item => item.id != form.value.id).reduce((sum, item) => sum + (item.scales || 0), 0)) + Number(scales)
	const sumAmount = Number(tableData.value.filter(item => item.id != form.value.id).reduce((sum, item) => sum + (item.amount || 0), 0)) + Number(amount)
	
	if (Number(scales) > 100 || sumScales > 100) {
		if(sumAmount === Number(props.cotHead.totalAmt)) {
			form.value.scales = 100 - (sumAmount - scales)
			return
		}

		rules.scales[2] = { message: '累计比例不能超过100%', trigger: 'blur' }
		ruleFormRef.value.validateField('scales', (valid) => { })

		rules.amount[2] = { message: '累计金额不能超过合同金额', trigger: 'blur' }
		ruleFormRef.value.validateField('amount', (valid) => { })
		return
	}

	if (Number(amount) > Number(props.cotHead.totalAmt) || sumAmount > Number(props.cotHead.totalAmt)) {
		if (sumScales === 100) {
			form.value.amount = Number(props.cotHead.totalAmt) - (sumAmount - amount)
			return
		}


		rules.scales[2] = { message: '累计比例不能超过100%', trigger: 'blur' }
		ruleFormRef.value.validateField('scales', (valid) => { })

		rules.amount[2] = { message: '累计金额不能超过合同金额', trigger: 'blur' }
		ruleFormRef.value.validateField('amount', (valid) => { })
		return
	}

	if (form.value.payFlag === '30' && Number(scales) > 20) {
		rules.scales[2] = { message: '质保金比例不能超过20%', trigger: 'blur' }
		ruleFormRef.value.validateField('scales', (valid) => { })

		rules.amount[2] = { message: '质保金金额不能超过合同金额的20%', trigger: 'blur' }
		ruleFormRef.value.validateField('amount', (valid) => { })
		return
	}
}
/**
* 比例与金额
*/
const disabled = ref(false)
const getDelvList = (contrNo) => {
	var url = 'sal/Delv/queryByContrNo'
	var param = {
		contrNo: contrNo
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == 0) {
			const delvList = response.data.data
			if(delvList && delvList.length > 0 ) {
				disabled.value = true
			}
		}
	})
}
</script>

<style></style>
