<template>
	<div>
		<el-card :body-style="cardBodyStyle" v-if="!readonly">
			<el-button plain type="primary" @click="handleAdd">新增</el-button>
			<el-button plain type="danger" @click="handleImportPlan" v-if="props.cotHead.purTy === 'Y'">采购计划转合同明细</el-button>
		</el-card>

		<el-card :body-style="cardBodyStyle">
			<el-table :data="tableData" border highlight-current-row @row-click="handleRowClick" 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="itemNm" label="物料名称" width="100" header-align="center" align="center"
					show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="specType" label="规格型号" width="100" header-align="center"
					align="center" 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="uom" label="计量单位" width="100" header-align="center" align="center"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column v-if="true" prop="taxRate" label="税率" width="120" header-align="center" align="right"
					show-overflow-tooltip :formatter="formatter">
				</el-table-column>
				<el-table-column label="现汇" align="center">
					<el-table-column v-if="true" prop="priceCash" label="不含税单价" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="taxPriceCash" label="含税单价" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="amtCash" label="不含税金额" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="taxAmtCash" label="税额" width="120" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="totalAmtCash" label="含税金额" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
				</el-table-column>
				<el-table-column label="承兑" align="center">
					<el-table-column v-if="true" prop="taxPriceBill" label="含税单价" width="120" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="amtBill" label="不含税金额" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="taxAmtBill" label="税额" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
					<el-table-column v-if="true" prop="totalAmtBill" label="含税金额" width="100" header-align="center"
						align="right" show-overflow-tooltip>
					</el-table-column>
				</el-table-column>
				<el-table-column v-if="true" prop="delvTolMax" label="发货允差上限" width="120" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="delvTolMin" label="发货允差下限" width="120" header-align="center"
					align="right" 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="handleEdit(row)" v-if="!readonly">编辑</el-button>
						<el-button plain type="danger" @click="handleDelete(row)" v-if="!readonly">删除</el-button>
						<el-button plain type="primary" @click="handleDetail(row)" v-if="readonly">查看</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-card :body-style="cardBodyStyle" style="margin-bottom: 20px;">
			<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-card :body-style="cardBodyStyle" v-if="!readonly && props.cotHead.contrTy != '30'">
			<el-button plain type="primary" @click="handleAddSettlement">新增结算标准</el-button>
			<el-button plain type="success" @click="handleAddSettlementTmp">保存至结算模版</el-button>
			<el-button plain type="warning" @click="handleItemSettlementTmp">取结算模版</el-button>
		</el-card>

		<el-card :body-style="cardBodyStyle" v-if="props.cotHead.contrTy != '30'">
			<el-table :data="tableDataSettlement" border highlight-current-row height="245">
				<el-table-column type="index" label="序号" align="center" width="60">
					<template #default="scope">
						<span>{{ scope.$index + (currentPageSettlement - 1) * pageSizeSettlement + 1 }}</span>
					</template>
				</el-table-column>
				<el-table-column v-if="true" prop="settleNo" label="结算项目编码" min-width="100" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="settleItem" label="结算项目" min-width="100" header-align="center"
					align="center" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="settleValueTo" label="结算项目上限" min-width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="settleValueFrom" label="结算项目下限" min-width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="referenceValue" label="基准值" min-width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="settleSpan" label="结算项目跨度" min-width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>
				<el-table-column v-if="true" prop="settleDiffer" label="结算差额" min-width="100" header-align="center"
					align="right" show-overflow-tooltip>
				</el-table-column>

				<el-table-column label="操作" header-align="center" align="center" width="250px" fixed="right">
					<template #default="scope">
						<el-button plain type="warning" @click="handleEditSettlement(scope.row)"
							v-if="!readonly">编辑</el-button>
						<el-button plain type="danger" @click="handleDeleteSettlement(scope.row)"
							v-if="!readonly">删除</el-button>
						<el-button plain type="primary" @click="handleDetailSettlement(scope.row)"
							v-if="readonly">查看</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<el-card :body-style="cardBodyStyle">
			<el-pagination :current-page="currentPageSettlement" :page-size="pageSizeSettlement"
				:page-sizes="pageSizesSettlement" :total="totalRowsSettlement" background="background"
				layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChangeSettlement"
				@current-change="handleCurrentChangeSettlement">
			</el-pagination>
		</el-card>

		<el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="1200px"
			top="5vh" @open="openDialog" @close="handleCancelSave">
			<el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
				<!-- <el-form-item label="合同号">
					<el-input v-model="form.contrNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item> -->
				<el-form-item label="合同行号" prop="conLine">
					<el-input v-model="form.conLine" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="物料编码" prop="itemCd">
					<el-input v-model="form.itemCd" clearable style="width: 200px" disabled>
					</el-input>
				</el-form-item>
				<el-form-item label="物料名称" prop="itemNm">
					<el-input v-model="form.itemNm" clearable style="width: 200px" readonly>
						<template #append>
							<el-button :icon="Search" @click="handleItem" />
						</template>
					</el-input>
				</el-form-item>
				<el-form-item label="规格型号" prop="specType">
					<el-input v-model="form.specType" clearable style="width: 200px" :readonly="readonly"></el-input>
				</el-form-item>
				<el-form-item label="数量" prop="qty">
					<el-input-number v-model="form.qty" :precision="3" :step="0.001" controls-position="right" clearable
						style="width: 200px" @input="updateQty" :readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="计量单位" prop="uom">
					<el-select v-model="form.uom" placeholder="请选择" clearable style="width: 200px" :disabled="readonly">
						<el-option v-for="item in dicList.MEASURING_UNIT" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" :disabled = "props.cotHead.contrTy == '20' && (item.dicCode == 'kg' || item.dicCode === 'ton')"/>
					</el-select>
				</el-form-item>
				<el-form-item label="税率" prop="taxRate">
					<el-select v-model="form.taxRate" placeholder="请选择" clearable style="width: 200px"
						@change="updateTaxRate" :disabled = "readonly">
						<el-option v-for="item in dicList.TAX_RATE" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode"/>
					</el-select>
				</el-form-item>
				<el-form-item label="不含税单价" prop="priceCash">
					<el-input-number v-model="form.priceCash" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="含税单价" prop="taxPriceCash">
					<el-input-number v-model="form.taxPriceCash" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" @input="updateTaxPriceCash"
						:readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="不含税金额" prop="amtCash">
					<el-input-number v-model="form.amtCash" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="税额" prop="taxAmtCash">
					<el-input-number v-model="form.taxAmtCash" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="含税金额" prop="totalAmtCash">
					<el-input-number v-model="form.totalAmtCash" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="承兑含税单价">
					<el-input-number v-model="form.taxPriceBill" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" @input="updateTaxPriceBill"
						:readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="承兑不含税金额">
					<el-input-number v-model="form.amtBill" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="承兑税额">
					<el-input-number v-model="form.taxAmtBill" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="承兑含税金额">
					<el-input-number v-model="form.totalAmtBill" :precision="2" :step="0.1" controls-position="right"
						clearable style="width: 200px" disabled></el-input-number>
				</el-form-item>
				<el-form-item label="发货允差上限">
					<el-input-number v-model="form.delvTolMax" controls-position="right" clearable style="width: 200px"
						:readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="发货允差下限">
					<el-input-number v-model="form.delvTolMin" controls-position="right" clearable style="width: 200px"
						:readonly="readonly"></el-input-number>
				</el-form-item>
			</el-form>
			<template #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>
			</template>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" draggable :title="titleSettlement" v-model="dialogVisibleSettlement"
			width="1200px" top="5vh" @open="openDialog">
			<el-form :model="formSettlement" label-width="120px" label-position="right" inline
				ref="ruleFormRefSettlement" :rules="rulesSettlement">
				<!-- <el-form-item label="合同号" prop="contrNo">
					<el-input v-model="formSettlement.contrNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item> -->
				<el-form-item label="合同行号" prop="conLine">
					<el-input v-model="formSettlement.conLine" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="结算项目编码" prop="settleNo">
					<el-input v-model="formSettlement.settleNo" clearable style="width: 200px" disabled></el-input>
				</el-form-item>
				<el-form-item label="结算项目" prop="settleItem">
					<el-select v-model="formSettlement.settleItem" placeholder="请选择" clearable style="width: 200px"
						@change="handleChange"  :disabled="readonly">
						<el-option v-for="item in dicList.SETTLE_ITEM" :key="item.dicCode" :label="item.dicName"
							:value="item.dicCode" />
					</el-select>
				</el-form-item>
				<el-form-item label="结算项目上限" prop="settleValueTo">
					<el-input-number v-model="formSettlement.settleValueTo" :precision="2" :step="0.1" :min="0"
						:max="100" controls-position="right" clearable style="width: 200px"
						@input="validateSettleValueTo" :readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="结算项目下限" prop="settleValueFrom">
					<el-input-number v-model="formSettlement.settleValueFrom" :precision="2" :step="0.1" :min="0"
						:max="100" controls-position="right" clearable style="width: 200px"
						@input="validateSettleValueFrom" :readonly="readonly"></el-input-number>
				</el-form-item>
				<el-form-item label="基准值" prop="referenceValue"> 
					<el-input-number v-model="formSettlement.referenceValue" :precision="2" :step="0.1"
						controls-position="right" clearable style="width: 200px" :readonly="readonly" :disabled="formSettlement.rejectFlag === 'Y'"></el-input-number>
				</el-form-item>
				<el-form-item label="结算项目跨度" prop="settleSpan">
					<el-input-number v-model="formSettlement.settleSpan" :precision="3" :step="0.1"
						controls-position="right" clearable style="width: 200px" :readonly="readonly" :disabled="formSettlement.rejectFlag === 'Y'"></el-input-number>
				</el-form-item>
				<el-form-item label="结算差额" prop="settleDiffer">
					<el-input-number v-model="formSettlement.settleDiffer" :precision="2" :step="0.1"
						controls-position="right" clearable style="width: 200px" :readonly="readonly" :disabled="formSettlement.rejectFlag === 'Y'"></el-input-number>
				</el-form-item>
				<el-form-item label="是否扣重">
					<el-checkbox v-model="weightDeducted" @change="updateWeightDeducted" :disabled="readonly || weightDeductedDisabled"/>
				</el-form-item>
				<el-form-item label="拒收或退货">
					<el-checkbox v-model="rejectFlag" @change="updateRejectFlag" :disabled="readonly"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button plain type="success" @click="handleSaveSettlement(ruleFormRefSettlement)"
					v-if="!readonly">保存</el-button>
				<el-button plain type="danger" @click="handleCancelSave" :readonly="readonly">取消</el-button>
			</template>
		</el-dialog>

		<el-dialog :close-on-click-modal="false" draggable title="保存结算模版" v-model="dialogVisibleSettlementTmp" top="5vh"
			@open="openDialogSettlementTmp" @close="handleCancelSave">
			<el-form :model="formSettlementTmp" label-width="120px" label-position="right" inline
				ref="ruleFormRefSettlementTmp" :rules="rulesSettlementTmp">
				<el-form-item label="结算模版名称" prop="tempNm">
					<el-input v-model="formSettlementTmp.tempNm" clearable style="width: 200px"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button plain type="success" @click="handleSaveSettlementTmp(ruleFormRefSettlementTmp)">保存</el-button>
					<el-button plain type="danger" @click="handleCancelSave">取消</el-button>
				</div>
			</template>
		</el-dialog>

		<Popup_base_wl ref="PopupRef" :salesFlag="props.cotHead.contrTy === '10' ? 'Y' : ''"
			:purchaseFlag="props.cotHead.contrTy === '20' ? 'Y' : ''" @receive-from-child="retu"></Popup_base_wl>

		<PopupSettlementTemp ref="PopupRefSettlementTmp" @receive-from-child="retuSettlementTmp"
			:params="querySettlementTmpLine"></PopupSettlementTemp>

		<PopupPurPlan ref="PopupRefPlan" @receive-from-child="retuPlan" :params="queryPurPlan"></PopupPurPlan>
	</div>
</template>


<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import Popup_base_wl from "@/views/bas/Popup_base_wl.vue";
import PopupSettlementTemp from '@/views/cot/components/PopupSettlementTemp.vue';
import PopupPurPlan from '@/views/pur/components/PopupPurPlan.vue'

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

const {
	proxy
} = getCurrentInstance()

import tools from '@/tools'
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue'

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


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

onMounted(() => {
	getDictList()
	tableData.value = []
	tableDataSettlement.value = []
	if (props.cotHead.id) {
		queryPurPlan.value.tradePartnerCode = props.cotHead.supplierCd
		handleSearch()
	}
})

watch(() => props.cotHead, (newVal, oldVal) => {
	tableData.value = []
	tableDataSettlement.value = []
	if (props.cotHead.id) {
		queryPurPlan.value.tradePartnerCode = props.cotHead.supplierCd
		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({
	MEASURING_UNIT: [],
	TAX_RATE: [],
	SETTLE_ITEM: []
})
const getDictList = () => {
	var url = 'framework/Common/querySelectorList'
	var param = {
		type: JSON.stringify(['MEASURING_UNIT', 'TAX_RATE', 'SETTLE_ITEM'])
	}
	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 'uom':
			cellValue = dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue)?.dicName
			break
		case 'taxRate':
			cellValue = dicList.value.TAX_RATE.find(item => item.dicCode == cellValue)?.dicName
			break
	}

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


/**
 *   查询 —— 合同行
 */
const query = ref({
	// contrId: '',
	contrNo: ''
})
const tableData = ref([])
const handleSearch = () => {
	currentPage.value = 1
	getTableData()
}

const emit = defineEmits(['receiveFromChild'])
const getTableData = () => {
	tableDataSettlement.value = []
	selectedRow.value = null
	// query.value.contrId = props.cotHead.id
	query.value.contrNo = props.cotHead.contrNo

	var url = 'cot/Line/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({
	contrId: '',
	contrNo: '',
	conLine: '',
	itemCd: '',
	itemNm: '',
	itemId: '',
	specType: '',
	qty: '',
	uom: '',
	taxRate: '',
	priceCash: '',
	taxPriceCash: '',
	amtCash: '',
	taxAmtCash: '',
	totalAmtCash: '',
	taxPriceBill: '',
	amtBill: '',
	taxAmtBill: '',
	totalAmtBill: '',
	delvTolMax: '',
	delvTolMin: '',
	notification: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
	modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
	contrNo: [
		{ required: true, message: '合同号必须录入', trigger: 'blur' }
	],
	itemCd: [
		{ required: true, message: '物料编码必须录入', trigger: 'blur' }
	],
	itemNm: [
		{ required: true, message: '物料名称必须录入', trigger: 'blur' }
	],
	qty: [
		{ required: true, message: '数量必须录入', trigger: 'blur' },
	],
	uom: [
		{ required: true, message: '计量单位必须录入', trigger: 'blur' }
	],
	taxRate: [
		{ required: true, message: '税率必须录入', trigger: 'blur' }
	],
	priceCash: [
		{ required: true, message: '不含税单价必须录入', trigger: 'blur' },
	],
	taxPriceCash: [
		{ required: true, message: '含税单价必须录入', trigger: 'blur' },
	],
	amtCash: [
		{ required: true, message: '不含税金额必须录入', trigger: 'blur' },
	],
	taxAmtCash: [
		{ required: true, message: '税额必须录入', trigger: 'blur' },
	],
	totalAmtCash: [
		{ required: true, message: '含税金额必须录入', trigger: 'blur' },
	]
})
const handleAdd = () => {
	if (window.localStorage.getItem('dept') == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '请添加登录人所在公司'
		})
		return
	}

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

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

	form.value = {
		contrId: props.cotHead.id,
		contrNo: props.cotHead.contrNo,
		conLine: '',
		itemCd: '',
		itemNm: '',
		itemId: '',
		specType: '',
		qty: null,
		uom: '',
		taxRate: '',
		priceCash: null,
		taxPriceCash: null,
		amtCash: null,
		taxAmtCash: null,
		totalAmtCash: null,
		taxPriceBill: null,
		amtBill: null,
		taxAmtBill: null,
		totalAmtBill: null,
		delvTolMax: null,
		delvTolMin: null,
		notification: null,
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyCode: '',
		modifyName: '',
	}
	title.value = '新增'
	dialogVisible.value = true
}
/**
 * 新增
 */


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

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

			var url = 'cot/Line/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
					// if (form.value.notification != '') {
					// 	ElMessage({
					// 		message: form.value.notification,
					// 		type: 'error'
					// 	})
					// }
					//emit('receiveFromChild')
					getCotHead(query.value.contrNo)
					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 getCotHead = (contrNo) => {
	var url = 'cot/Head/queryByContrNo'
	var param = {
		contrNo: contrNo
	}
	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			props.cotHead.totalAmt = response.data.data.totalAmt
			props.cotHead.qty = response.data.data.qty
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
const handleCancelSave = () => {
	form.value = {
		contrId: '',
		contrNo: '',
		conLine: '',
		itemCd: '',
		itemNm: '',
		itemId: '',
		specType: '',
		qty: '',
		uom: '',
		taxRate: '',
		priceCash: '',
		taxPriceCash: '',
		amtCash: '',
		taxAmtCash: '',
		totalAmtCash: '',
		taxPriceBill: '',
		amtBill: '',
		taxAmtBill: '',
		totalAmtBill: '',
		delvTolMax: '',
		delvTolMin: '',
		notification: ''
	}
	formSettlement.value = {
		contrId: '',
		contrNo: '',
		conLineId: '',
		conLine: '',
		settleDiffer: '',
		settleNo: '',
		settleValueTo: '',
		settleValueFrom: '',
		settleSpan: '',
		settleItem: '',
	}
	formSettlementTmp.value = {
		tempNm: '',
		contrNo: '',
		contTy: '',
		cmpCd: '',
		cmpNm: '',
		tmpLines: [],
	}

	dialogVisible.value = false
	dialogVisibleSettlement.value = false
	dialogVisibleSettlementTmp.value = false
	// dialogVisibleSettlementTmpLine.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
	dialogVisible.value = true
}
const handleDetail = (row) => {
	if (ruleFormRef.value) {
		ruleFormRef.value.resetFields()
	}
	title.value = '查看'
	form.value = { ...row }
	dialogVisible.value = true
}
const handleDelete = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}).then(() => {
		var url = 'cot/Line/remove'
		var param = {
			id: row.id
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == 0) {
				ElMessage({
					type: 'success',
					message: '删除成功',
				})
				getCotHead(query.value.contrNo)
				getTableData()
			} else {
				ElMessage({
					type: 'error',
					message: '删除失败' + response.data.msg
				});
			}
		});
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消',
		})
	})
}
/**
 * 保存、修改、删除
 */


/**
 * 选择行
 */
const selectedRow = ref(null)
const handleRowClick = (row, column, event) => {
	selectedRow.value = row

	querySettlement.value = {
		// contrId: selectedRow.value.contrId,
		// conLineId: selectedRow.value.id,
		contrNo: selectedRow.value.contrNo,
		conLine: selectedRow.value.conLine
	}
	getTableDataSettlement()
	getSettlementList()
}
/**
 * 选择行
 */


/**
 * 查询 - 结算标准
 */
const querySettlement = ref({
	// contrId: '',
	// conLineId: ''
	contrNo: '',
	conLine: ''
})
const tableDataSettlement = ref([])
const getTableDataSettlement = () => {
	var url = 'cot/Settlement/query'
	var param = {
		page: currentPageSettlement.value,
		rows: pageSizeSettlement.value,
		params: JSON.stringify(querySettlement.value)
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == '0') {
			tableDataSettlement.value = response.data.data.records
			totalRowsSettlement.value = response.data.data.total
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}
/**
 * 查询 - 结算标准
 */


/**
 * 分页
 */
const currentPageSettlement = ref(1)
const totalRowsSettlement = ref(0)
const pageSizesSettlement = ref([5, 10, 20, 30, 40])
const pageSizeSettlement = ref(5)
const handleSizeChangeSettlement = (val) => {
	pageSizeSettlement.value = val
	getTableDataSettlement()
}
const handleCurrentChangeSettlement = (val) => {
	currentPageSettlement.value = val
	getTableDataSettlement()
}
/**
 * 分页
 */

/**
 * 新增 - 结算标准
 */
const titleSettlement = ref('新增')
const dialogVisibleSettlement = ref(false)
const formSettlement = ref({
	contrId: '',
	contrNo: '',
	conLineId: '',
	conLine: '',
	settleDiffer: null,
	settleNo: '',
	settleValueTo: null,
	settleValueFrom: null,
	settleSpan: null,
	settleItem: '',
	referenceValue: null,
	rejectFlag: '',
	weightDeducted: '',
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
	modifyName: '',
})
const ruleFormRefSettlement = ref()
const rulesSettlement = reactive({
	contrNo: [{
		required: true,
		message: '合同号必须录入',
	}],
	conLine: [{
		required: true,
		message: '合同行号必须录入',
	}],
	settleNo: [{
		required: true,
		message: '结算项目编码必须录入',
	}],
	settleItem: [{
		required: true,
		message: '结算项目必须录入',
	}],
	settleValueTo: [{
		required: true,
		message: '结算项目上限必须录入',
	}],
	settleValueFrom: [{
		required: true,
		message: '结算项目下限必须录入',
	}],
	referenceValue: [{
		required: true,
		message: '基准值必须录入',
	}],
	settleSpan: [{
		required: true,
		message: '结算项目跨度必须录入',
	}],
	settleDiffer: [{
		required: true,
		message: '结算项目差额必须录入',
	}],
})
const handleAddSettlement = () => {
	if (selectedRow.value == null) {
		ElMessage.warning('请先选择合同明细！')
		return
	}

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

	formSettlement.value = {
		contrNo: selectedRow.value.contrNo,
		conLine: selectedRow.value.conLine,
		contrId: selectedRow.value.contrId,
		conLineId: selectedRow.value.id,
		settleDiffer: null,
		settleNo: '',
		settleValueTo: null,
		settleValueFrom: null,
		settleSpan: null,
		settleItem: '',
		referenceValue: null,
		rejectFlag: 'N',
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyCode: '',
		modifyName: '',
	}
	titleSettlement.value = '新增'
	dialogVisibleSettlement.value = true
}
/**
 * 新增 - 结算标准
 */


/**
 * 保存、编辑、删除 - 结算标准
 */
const handleSaveSettlement = (ruleFormRefSettlement) => {
	ruleFormRefSettlement.validate((valid, fields) => {
		if (valid) {
			var url = 'cot/Settlement/save'
			var param = {
				json: JSON.stringify(formSettlement.value),
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					ElMessage({
						message: '保存成功',
						type: 'success',
					})
					formSettlement.value = response.data.data
					rejectFlag.value = formSettlement.value.rejectFlag === 'Y'
					getTableDataSettlement()
					getSettlementList()
					dialogVisibleSettlement.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})

		} else {
			console.log('error submit!', fields)
		}
	})
}
const handleEditSettlement = (row) => {
	if (ruleFormRefSettlement.value) {
		ruleFormRefSettlement.value.resetFields()
	}
	titleSettlement.value = '编辑'
	formSettlement.value = { ...row }
	formSettlement.value.modifyCode = userCode
	formSettlement.value.modifyCode = userCode
	if(formSettlement.value.settleNo == '110') {
		weightDeductedDisabled.value = false
		weightDeducted.value = formSettlement.value.weightDeducted === '10'
	} else {
		weightDeductedDisabled.value = true
		weightDeducted.value = null
	}
	rejectFlag.value = formSettlement.value.rejectFlag === 'Y'
	readonly.value = false
	dialogVisibleSettlement.value = true
}
const handleDetailSettlement = (row) => {
	if (ruleFormRefSettlement.value) {
		ruleFormRefSettlement.value.resetFields()
	}
	titleSettlement.value = '查看'
	formSettlement.value = { ...row }
	if(formSettlement.value.settleNo == '110') {
		weightDeductedDisabled.value = false
		weightDeducted.value = formSettlement.value.weightDeducted === '10'
	} else {
		weightDeductedDisabled.value = true
		weightDeducted.value = null
	}
	rejectFlag.value = formSettlement.value.rejectFlag === 'Y'
	readonly.value = true
	dialogVisibleSettlement.value = true
}
const handleDeleteSettlement = (row) => {
	ElMessageBox.confirm(
		'确定删除本条记录?',
		'提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
	}
	)
		.then(() => {
			var url = 'cot/Settlement/remove'
			var param = {
				id: row.id
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					ElMessage({
						type: 'success',
						message: '删除成功',
					})
					getTableDataSettlement()
					getSettlementList()
				} else {
					ElMessage({
						type: 'error',
						message: '删除失败' + response.data.msg
					});
				}
			});
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '已取消',
			})
		})
}
/**
 * 保存、编辑、删除 - 结算标准
 */


/**
 * 新增 - 结算标准模版
 */
const dialogVisibleSettlementTmp = ref(false)
const formSettlementTmp = ref({
	tempNm: '',
	contrNo: '',
	contTy: '',
	cmpCd: '',
	cmpNm: '',
	tmpLines: [],
	addId: '',
	addCode: '',
	addName: '',
	addDeptId: '',
	addDeptCode: '',
	addDeptName: '',
	addTime: '',
	modifyCode: '',
	modifyName: '',
})
const ruleFormRefSettlementTmp = ref()
const rulesSettlementTmp = reactive({
	tempNm: [{
		required: true,
		message: '模版名称必须录入',
	}],
})
const handleAddSettlementTmp = () => {
	if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '请添加登录人所在公司'
		})
		return
	}

	if (JSON.stringify(tableDataSettlement.value) == JSON.stringify(new Array())) {
		ElMessage({
			type: 'warning',
			message: '没有可以保存的结算标准！'
		})
		return
	}

	formSettlementTmp.value = {
		contrNo: props.cotHead.contrNo,
		contTy: props.cotHead.contrTy,
		cmpCd: deptTree[0].deptCode,
		cmpNm: deptTree[0].deptName,
		tempNm: '',
		tmpLines: settlementList.value,
		addId: userId,
		addCode: userCode,
		addName: userName,
		addDeptId: dept[0].id,
		addDeptCode: dept[0].deptCode,
		addDeptName: dept[0].deptName,
		addTime: '',
		modifyCode: '',
		modifyName: '',
	}

	dialogVisibleSettlementTmp.value = true
}

const handleSaveSettlementTmp = (ruleFormRefSettlementTmp) => {

	ruleFormRefSettlementTmp.validate((valid, fields) => {
		if (valid) {
			var url = 'cot/Tmp/saveBatch'
			var param = {
				json: JSON.stringify(formSettlementTmp.value),
			}
			proxy.$axios.post(url, param).then(response => {
				if (response.data.code == 0) {
					formSettlementTmp.value = response.data.data
					ElMessage({
						message: '保存成功',
						type: 'success',
					})
					tableDataSettlement.value.forEach(item => {
						item.tempId = formSettlementTmp.value.tempId
						item.tempNm = formSettlementTmp.value.tempNm
					})
					dialogVisibleSettlementTmp.value = false
				} else {
					ElMessage({
						message: '操作失败' + response.data.msg,
						type: 'error'
					})
				}
			})
		} else {
			console.log('error submit!', fields)
		}
	})
}

/**
 * 获取 - 结算标准模版
 */
const querySettlementTmpLine = ref({
	tempNm: '',
	compCd: '',
	contTy: '',
})
const PopupRefSettlementTmp = ref(null)
const handleItemSettlementTmp = () => {
	console.log(selectedRow.value)
	if (selectedRow.value == null) {
		ElMessage.warning('请先选择合同行！')
		return
	}

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

	querySettlementTmpLine.value = {
		tempNm: '',
		contTy: props.cotHead.contrTy,
		compCd: props.cotHead.compCd,
	}

	handleRemoveBatchSettlementTmpLine()
}
const handleRemoveBatchSettlementTmpLine = () => {
	if (!settlementList.value) {
		PopupRefSettlementTmp.value.open()
		return
	}

	ElMessageBox.confirm('取结算模版将删除已有数据, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(() => {
		var ids = []
		settlementList.value.forEach((item, index) => {
			ids.push(item.id)
		})

		var url = 'cot/Settlement/removeBatch'
		var param = {
			ids: JSON.stringify(ids)
		}
		proxy.$axios.post(url, param).then(response => {
			if (response.data.code == '0') {
				ElMessage({
					type: 'success',
					message: '操作成功!',
				})
				getTableDataSettlement()
				getSettlementList()
				PopupRefSettlementTmp.value.open()
			} else {
				ElMessage({
					type: 'error',
					message: '操作失败!' + response.data.msg
				})
			}
		})
	}).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消删除'
		})
	})
}
const formSettlementTmpLine = ref({
	contrId: '',
	contrNo: '',
	conLineId: '',
	conLine: '',
	tempId: '',
})
const retuSettlementTmp = (val) => {
	formSettlementTmpLine.value = {
		contrId: selectedRow.value.contrId,
		contrNo: props.cotHead.contrNo,
		conLineId: selectedRow.value.id,
		conLine: selectedRow.value.conLine,
		tempId: val.id,
	}
	handleSaveSettlementTmpLine()
}
const handleSaveSettlementTmpLine = () => {
	var url = 'cot/Settlement/saveBatchByTempLine'
	var param = {
		params: JSON.stringify(formSettlementTmpLine.value)
	}

	proxy.$axios.get(url, param).then(response => {
		if (response.data.code == '0') {
			const flag = ref(JSON.stringify(response.data.data))
			if (JSON.stringify(tableDataSettlement.value) == flag.value) {
				ElMessage.warning('未获取到结算模板')
				return
			}
			getTableDataSettlement()
			getSettlementList()
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}

/**
 * 物料
 */
const PopupRef = ref(null)
const handleItem = () => {
	PopupRef.value.open()
}
const retu = (val) => {
	form.value.itemId = val.id
	form.value.itemCd = val.itemCd
	form.value.itemNm = val.itemNm
	form.value.uom = val.unit
}


/**
 *  
 */
const settlementList = ref([])
const getSettlementList = () => {
	var url = 'cot/Settlement/queryByParams'
	var param = {
		params: JSON.stringify(querySettlement.value)
	}
	proxy.$axios.post(url, param).then(response => {
		if (response.data.code == '0') {
			settlementList.value = response.data.data
		} else {
			ElMessage.error('操作失败！' + response.data.msg)
		}
	})
}

const weightDeductedDisabled = ref(true)
const weightDeducted = ref(null)
const handleChange = (val) => {
	formSettlement.value.settleNo = val
	validateSettleValue(formSettlement.value.settleValueTo, formSettlement.value.settleValueFrom, formSettlement.value.settleNo)

	
	if(formSettlement.value.settleNo === '110') { // 结算项目为水分
		weightDeductedDisabled.value = false
		weightDeducted.value = true // 默认扣重
	} else { // 结算项目非水分
		weightDeductedDisabled.value = true
		weightDeducted.value = null
		
	}
	
	dicList.value.SETTLE_ITEM.forEach(item => {
		if (item.dicCode == val) {
			formSettlement.value.settleItem = item.dicName
			return
		}
	})
}

const validateSettleValueTo = (val) => {
	formSettlement.value.settleValueTo = val
	validateSettleValue(formSettlement.value.settleValueTo, formSettlement.value.settleValueFrom, formSettlement.value.settleNo)
}
const validateSettleValueFrom = (val) => {
	formSettlement.value.settleValueFrom = val
	validateSettleValue(formSettlement.value.settleValueTo, formSettlement.value.settleValueFrom, formSettlement.value.settleNo)
}

const validateSettleValue = (settleValueTo, settleValueFrom, settleNo) => {
	if (rulesSettlement.settleValueTo.length == 2) {
		rulesSettlement.settleValueTo.pop()
	}
	if (rulesSettlement.settleValueFrom.length == 2) {
		rulesSettlement.settleValueFrom.pop()
	}

	if (settleValueTo != null && settleValueFrom != null && settleValueTo <= settleValueFrom) {
		rulesSettlement.settleValueTo[1] = { message: '结算项目上限大于结算项目下限', trigger: 'blur' }
		ruleFormRefSettlement.value.validateField('settleValueTo', (valid) => { })

		rulesSettlement.settleValueFrom[1] = { message: '结算项目上限大于结算项目下限', trigger: 'blur' }
		ruleFormRefSettlement.value.validateField('settleValueFrom', (valid) => { })
		return
	}

	settlementList.value
		.filter(item => item.id != formSettlement.value.id && item.settleNo === settleNo)
		.forEach(item => {
			if (!(settleValueTo <= item.settleValueFrom || item.settleValueTo <= settleValueFrom)) {
				rulesSettlement.settleValueTo[1] = { message: '结算项目上下限不能交叉', trigger: 'blur' }
				ruleFormRefSettlement.value.validateField('settleValueTo', (valid) => { })

				rulesSettlement.settleValueFrom[1] = { message: '结算项目上下限不能交叉', trigger: 'blur' }
				ruleFormRefSettlement.value.validateField('settleValueFrom', (valid) => { })
				return
			}
		})
}

const rejectFlag = ref(false)
const updateRejectFlag = (val) => {
	if(val) {
		formSettlement.value.rejectFlag = 'Y'
		formSettlement.value.referenceValue = 0
		formSettlement.value.settleSpan = 0
		formSettlement.value.settleDiffer = 0
	} else {
		formSettlement.value.rejectFlag = 'N'
		formSettlement.value.referenceValue = null
		formSettlement.value.settleSpan = null
		formSettlement.value.settleDiffer = null
	}
}

const updateWeightDeducted = (val) => {
	if(val) {
		formSettlement.value.weightDeducted = '10' // 扣重
	} else {
		formSettlement.value.weightDeducted = '20' // 扣钱
	}
}

/**
 *  
 */
const updateTaxPriceCash = (val) => {
	form.value.taxPriceCash = val
	calculatePrice(form.value.taxPriceCash, form.value.taxRate, form.value.qty)
}
const updateTaxRate = (val) => {
	form.value.taxRate = val
	calculatePrice(form.value.taxPriceCash, form.value.taxRate, form.value.qty)
	calculatePriceBill(form.value.taxPriceBill, form.value.taxRate, form.value.qty)
}
const updateQty = (val) => {
	form.value.qty = val
	calculatePrice(form.value.taxPriceCash, form.value.taxRate, form.value.qty)
}

const calculatePrice = (taxPriceCash, taxRate, qty) => {

	if (taxPriceCash != null) {
		form.value.totalAmtCash = qty != null ? Number(taxPriceCash) * Number(qty) : null

		if (taxRate != '') {
			// 不含税单价 = 含税单价 / (1 + 税率)
			form.value.priceCash = Number(taxPriceCash) / (Number(1) + (Number(taxRate) / 100))

			if (qty != null) {
				// 不含税金额 = 不含税单价 * 数量
				form.value.amtCash = Number(form.value.priceCash) * Number(qty)
				// 税额 = 含税金额 - 不含税金额
				form.value.taxAmtCash = Number(form.value.totalAmtCash) - Number(form.value.amtCash)
			} else {
				form.value.amtCash = null
				form.value.taxAmtCash = null
			}
		} else {
			form.value.priceCash = null
			form.value.amtCash = null
			form.value.taxAmtCash = null
		}
	} else {
		form.value.priceCash = null
		form.value.totalAmtCash = null
		form.value.amtCash = null
		form.value.taxAmtCash = null
	}
}


const updateTaxPriceBill = (val) => {
	form.value.taxPriceBill = val
	calculatePriceBill(form.value.taxPriceBill, form.value.taxRate, form.value.qty)
}
const calculatePriceBill = (taxPriceBill, taxRate, qty) => {
	if (taxPriceBill != null && qty != null) {

		// 含税金额 = 含税单价 * 数量
		form.value.totalAmtBill = Number(taxPriceBill) * Number(qty)

		if (taxRate != '') {
			// 不含税单价 = 含税单价 / (1 + 税率)
			const priceBill = Number(taxPriceBill) / (Number(1) + (Number(taxRate) / 100))
			// 不含税金额 = 不含税单价 * 数量
			form.value.amtBill = Number(priceBill) * Number(qty)
			// 税额 = 含税金额 - 不含税金额
			form.value.taxAmtBill = Number(form.value.totalAmtBill) - Number(form.value.amtBill)
		} else {
			form.value.amtBill = null
			form.value.taxAmtBill = null
		}
	} else {
		form.value.totalAmtBill = null
		form.value.amtBill = null
		form.value.taxAmtBill = null
	}
}


// 采购计划转合同明细
const queryPurPlan = ref({
	tradePartnerCode: '',
})
const PopupRefPlan = ref(null)
const handleImportPlan = () => {
    PopupRefPlan.value.open()
}
const retuPlan = (val) => {
	console.log(val)
    // var url = 'cot/Line/saveBatch' 
    // var param = {
	// 	json: JSON.stringify({
	// 		contrId: props.cotHead.id,
	// 		contrNo: props.cotHead.contrNo,
	// 		addId: userId,
	// 		addCode: userCode,
	// 		addName: userName,
	// 		addDeptId: dept[0].id,
	// 		addDeptCode: dept[0].deptCode,
	// 		addDeptName: dept[0].deptName,
	//		cancelFlag: '0'
	// 	}),
    //     json1: JSON.stringify(val),
    // }
    // 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'
    //         })
    //     }
    // })
}
</script>

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