<template>
	<div class="page-container column-container">
		<section class="list-part-container column-container" style="flex: 1">
			<!-- 搜索区 -->
			<el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
				<el-form-item class="section-title" label="外协商管理" />
				<el-form-item label="外协商名称：">
					<el-input placeholder="请输入关键字" v-model.trim="queryParams.name" style="width: 120px" clearable
						@keyup.enter="handleQuery" @keydown.enter.prevent />
				</el-form-item>
				<el-form-item label="助记码：">
					<el-input placeholder="请输入助记码" v-model.trim="queryParams.mnemonicCode" style="width: 120px" clearable
						@keyup.enter="handleQuery" @keydown.enter.prevent />
				</el-form-item>
				<el-form-item label="外协厂编码：">
					<el-input placeholder="请输入外协厂编码" v-model.trim="queryParams.code" style="width: 120px" clearable
						@keyup.enter="handleQuery" @keydown.enter.prevent />
				</el-form-item>
				<el-form-item>
					<el-button type="info" icon="Search" @click="handleQuery">搜索</el-button>
					<el-button type="primary" icon="Plus" @click="handleShowSupplierDialog(null)">添加</el-button>
				</el-form-item>
			</el-form>
			<!-- 列表区 -->
			<div class="el-table-container">
				<div class="el-table-inner-container">
					<el-table ref="supplierTable" v-loading="loading" border :data="supplierList" highlight-current-row
						height="100%" @current-change="handleCurrentSupplierChange">
						<el-table-column type="index" label="行号" width="50" align="center" />
						<el-table-column label="外协商名称" width="320" align="center" prop="name" />
						<el-table-column label="外协厂编码" width="120" align="center" prop="code" />
						<el-table-column label="发货方式" width="96" align="center" prop="deliveryMethod">
							<template #default="scope">
								<dict-tag :options="delivery_method" :value="scope.row.deliveryMethod" />
							</template>
						</el-table-column>
						<el-table-column label="结算方式" width="96" align="center" prop="deliveryMethod">
							<template #default="scope">
								<dict-tag :options="settlement_type" :value="scope.row.settlementType" />
							</template>
						</el-table-column>
						<el-table-column label="损耗上限" width="96" align="center" prop="lossLimit">
							<template #default="scope"> {{ scope.row.lossLimit }}% </template>
						</el-table-column>
						<el-table-column label="默认联系人" width="120" align="center" prop="contactName" />
						<el-table-column label="默认联系电话" width="120" align="center" prop="contactPhoneNumber" />
						<el-table-column label="备注" align="center" prop="remark" />
						<el-table-column label="操作" width="350" align="center">
							<template #default="scope">
								<el-button v-hasPermi="['business:supplier:edit']" link type="primary" icon="User"
									@click="handleSetSupplierAdmin(scope.row)">
									设置管理员
								</el-button>
								<el-button v-hasPermi="['business:supplier:edit']" link type="success" icon="Iphone"
									@click="handleSetSupplierContacts(scope.row)">
									设置联系人
								</el-button>
								<el-button v-hasPermi="['business:supplier:edit']" link type="warning" icon="Edit"
									@click="handleShowSupplierDialog(scope.row)">
									编辑
								</el-button>
								<el-button v-hasPermi="['business:supplier:remove']" link type="danger" icon="Delete"
									@click="handleDelete(scope.row)">
									删除
								</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
		</section>
		<!-- 分页 -->
		<pagination v-show="supplierTotal > 0" :total="supplierTotal" v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize" @pagination="getList" />

		<section class="list-part-container row-container" style="flex: 1">
			<section class="list-part-container" style="flex: 2">
				<!-- 下边页面开始 -->
				<el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
					<el-form-item class="section-title" label="产品" />
					<el-form-item label="产品描述：">
						<el-input placeholder="请输入关键字" v-model.trim="queryProductParams.productDescription" style="width: 120px"
							clearable @keyup.enter="handleQuery" @keydown.enter.prevent />
					</el-form-item>
					<el-form-item>
						<el-button type="info" icon="Search" @click="handleQueryProducts">搜索</el-button>
						<el-button type="primary" icon="Plus" @click="handleShowProductsDialog(null)"
							:disabled="!currentSupplier.id">
							添加产品
						</el-button>
					</el-form-item>
				</el-form>
				<div class="el-table-container">
					<div class="el-table-inner-container">
						<el-table ref="productTable" :data="supplierProductList ? supplierProductList : []"
							v-loading="supplierProductLoading" highlight-current-row height="100%" size="small"
							header-row-class-name="list-header-row" @current-change="handleCurrentProductChange">
							<el-table-column type="index" label="行号" width="50" align="center" />
							<el-table-column label="料号" width="120" align="center" prop="productCode" />
							<el-table-column label="产品描述" align="center" prop="productDescription" />
							<el-table-column label="操作" width="72px" align="center">
								<template #default="scope">
									<el-button link type="danger" icon="Delete" @click="handleDelProduct(scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
				<!-- 分页 -->
				<pagination v-show="productTotal > 0" :total="productTotal" v-model:page="queryProductParams.pageNum"
					v-model:limit="queryProductParams.pageSize" @pagination="getCurrentSupplierProduct" />
			</section>
			<section class="list-part-container" style="flex: 3">
				<el-form class="list-search-container list-search-container-child" :model="queryParams" ref="queryRef"
					:inline="true">
					<el-form-item class="section-title" label="外协工序" />
					<el-form-item>
						<el-button type="primary" icon="Plus" @click="handleShowProcessesDialog"
							:disabled="!currentProduct.id || processEditStatus">
							添加工序
						</el-button>
						<el-button v-if="!processEditStatus" type="warning" icon="Edit"
							:disabled="!currentProduct.id || supplierProductProcessList.length === 0"
							@click="processEditStatus = true">
							编辑
						</el-button>
						<template v-if="processEditStatus">
							<el-button type="success" icon="Finished" @click="handleSaveProcess">保存</el-button>
							<el-button type="danger" icon="Close" @click="processEditStatus = false">取消编辑</el-button>
						</template>
					</el-form-item>
				</el-form>
				<div class="el-table-container">
					<div class="el-table-inner-container">
						<el-table :data="supplierProductProcessList" v-loading="supplierProductProcessLoading" highlight-current-row
							height="100%">
							<el-table-column type="index" label="行号" width="50" align="center" />
							<el-table-column label="工序编码" width="120" align="center" prop="processCode" />
							<el-table-column label="工序简称" width="120" align="center" prop="processAlias" />
							<el-table-column label="结算方式" width="120" align="center" prop="settlementType">
								<template #default="scope">
									<el-select v-if="processEditStatus" v-model="scope.row.settlementType" clearable placeholder="请选择">
										<el-option v-for="dict in settlement_type" :key="dict.value" :label="dict.label"
											:value="dict.value" />
									</el-select>
									<dict-tag v-else :options="settlement_type" :value="scope.row.settlementType" />
								</template>
							</el-table-column>
							<el-table-column label="单价(元)" width="120" align="center" prop="price">
								<template #default="scope">
									<el-input-number v-if="processEditStatus" v-model="scope.row.price" :precision="8" :min="0.0"
										:step="0.00000001" controls-position="right" />
									<span v-else>{{ scope.row.priceLabel }}</span>
								</template>
							</el-table-column>
							<el-table-column label="备注" align="center" prop="remark">
								<template #default="scope">
									<el-input v-if="processEditStatus" v-model="scope.row.remark" />
									<span v-else>{{ scope.row.remark }}</span>
								</template>
							</el-table-column>
							<el-table-column label="操作" width="64px" align="center">
								<template #default="scope">
									<el-button link type="danger" icon="Delete" @click="handleDelProcess(scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</section>
		</section>
		<!-- 供应商表单 -->
		<dialog-form ref="formRef" @handleSaveSuccess="getList" :delivery-method="delivery_method"
			:settlement-type="settlement_type" />
		<!-- 产品添加对话框 -->
		<dialog-products ref="productsRef" :supplier-id="currentSupplier.id" :multiple-selected="handleProductSelected" />
		<!-- 工序添加对话框 -->
		<dialog-processes ref="processesRef" :product-id="currentProduct.productId" :supplier-id="currentSupplier.id"
			:multiple-selected="handleProcessSelected" />
		<!-- 管理员设置 -->
		<dialog-set-admin ref="setAdminRef" />
		<!-- 联系人设置 -->
		<contacts-form ref="setContactsRef" @handleSaveSuccess=getList() />
	</div>
</template>

<script setup>
import {
	list,
	save,
	remove,
	getSupplierProduct,
	saveSupplierProduct,
	removeSupplierProduct,
	getSupplierProductProcess,
	saveSupplierProductProcess,
	removeSupplierProductProcess
} from '@/api/business/supplier'
import dialogForm from './form'
import dialogProducts from './DialogProducts'
import dialogProcesses from './DialogProcesses'
import dialogSetAdmin from './DialogSetAdmin'
import contactsForm from './contactsForm'
const { proxy } = getCurrentInstance()
const { delivery_method } = proxy.useDict('delivery_method')
const { settlement_type } = proxy.useDict('settlement_type')

/** 外协商查询对象 */
const queryParams = ref({
	name: '',
	mnemonicCode: '',
	pageNum: 1,
	pageSize: 10
})
/** 产品查询对象 */
const queryProductParams = ref({
	supplierId: '0',
	productDescription: '',
	pageNum: 1,
	pageSize: 10
})
/** 产品工序查询对象 */
const queryProductProcessParams = ref({
	supplierId: '0',
	productId: null,
	pageNum: 1,
	pageSize: 10
})
/** 外协商变量 */
const loading = ref(false)
const supplierTable = ref(null)
const supplierList = ref([])
const supplierTotal = ref(0)
const currentSupplier = ref({})

const supplierProductLoading = ref(false)
const productTable = ref(null)
const supplierProductList = ref([])
const productTotal = ref(0)
const currentProduct = ref({})

const supplierProductProcessLoading = ref(false)
const supplierProductProcessList = ref([])
const currentProcess = ref({})
const processEditStatus = ref(false)

/***********************  方法区  ***********************/
/** 查询外协商管理列表 */
const getList = () => {
	loading.value = true
	list(queryParams.value).then((res) => {
		supplierList.value = res.rows
		supplierTotal.value = res.total
		loading.value = false
		if (supplierList.value.length > 0) {
			proxy.$refs.supplierTable.setCurrentRow(supplierList.value[0])
		}
	})
}
/** 外协商搜索按钮操作 */
const handleQuery = () => {
	queryParams.value.pageNum = 1
	getList()
}

/** 打开供应商对话框 **/
const handleShowSupplierDialog = (data) => {
	proxy.$refs.formRef.open(data)
}

/**
 * 外协商的 current change 事件
 */
const handleCurrentSupplierChange = (row) => {
	if (row) {
		currentSupplier.value = row
		getCurrentSupplierProduct()
	}
}

const handleDelete = (row) => {
	proxy.$modal
		.confirm('确认删除数据项？')
		.then(() => {
			remove(row.id).then((res) => {
				if (res.code === 200) {
					proxy.$modal.msgSuccess('删除成功！')
					getList()
				}
			})
		})
		.catch(() => { })
}

/** 设置管理员 **/
const handleSetSupplierAdmin = (data) => {
	proxy.$refs.setAdminRef.open(data)
}
/**设置联系人 */
const handleSetSupplierContacts = (data) => {
	proxy.$refs.setContactsRef.open(data)
}
/**************************************** 产品相关 ****************************************/
/** 产品打开对话框方法 */
const handleShowProductsDialog = () => {
	proxy.$refs.productsRef.open()
}

const handleQueryProducts = () => {
	getCurrentSupplierProduct()
}
const getCurrentSupplierProduct = () => {
	supplierProductLoading.value = true
	queryProductParams.value.supplierId = currentSupplier.value.id
	getSupplierProduct(queryProductParams.value).then((res) => {
		supplierProductList.value = res.rows
		productTotal.value = res.total
		if (supplierProductList.value.length > 0) {
			currentProduct.value = supplierProductList.value[0]
			proxy.$refs.productTable.setCurrentRow(supplierProductList.value[0])
		} else {
			supplierProductProcessList.value = []
			currentProduct.value = {}
		}
		supplierProductLoading.value = false
	})
}

/**
 * 产品多选带回保存
 * 将弹出框选中的内容保存到工序表
 */
const handleProductSelected = (selection) => {
	const dataList = []
	selection.forEach((item) => {
		const newProduct = {
			id: null,
			tenantId: currentSupplier.value.tenantId,
			supplierId: currentSupplier.value.id,
			supplierName: currentSupplier.value.name,
			productId: item.id,
			productCode: item.productCode,
			productDescription: item.description
		}
		dataList.push(newProduct)
	})
	saveSupplierProduct(dataList).then((res) => {
		if (res.code === 200) {
			getCurrentSupplierProduct()
		}
	})
}
const handleCurrentProductChange = (row) => {
	if (row) {
		currentProduct.value = row
		getCurrentSupplierProductProcess()
	}
}

const handleDelProduct = (row) => {
	proxy.$modal
		.confirm('确认删除数据项？')
		.then(() => {
			removeSupplierProduct(row.id).then((res) => {
				if (res.code === 200) {
					proxy.$modal.msgSuccess('删除成功！')
					getCurrentSupplierProduct()
				}
			})
		})
		.catch(() => { })
}

/**************************************** 工序相关 ****************************************/
const getCurrentSupplierProductProcess = () => {
	supplierProductProcessLoading.value = true
	queryProductProcessParams.value.supplierId = currentSupplier.value.id
	queryProductProcessParams.value.supplierProductId = currentProduct.value.id
	console.log(queryProductProcessParams.value)
	getSupplierProductProcess(queryProductProcessParams.value).then((res) => {
		supplierProductProcessList.value = res.data
		supplierProductProcessLoading.value = false
	})
}

/** 工序打开对话框方法 */
const handleShowProcessesDialog = (row) => {
	proxy.$refs.processesRef.open(row)
}

/**
 * 产品多选带回保存
 * 将弹出框选中的内容保存到工序表
 */
const handleProcessSelected = (selection) => {
	console.log(selection)
	const dataList = []
	selection.forEach((item) => {
		const newProcess = {
			id: null,
			tenantId: currentSupplier.value.tenantId,
			supplierId: currentSupplier.value.id,
			supplierName: currentSupplier.value.name,
			technologicalProcessId: item.technologicalProcessId,
			technologyVersion: item.technologyVersion,
			productId: currentProduct.value.productId,
			productDescription: currentProduct.value.productDescription,
			processId: item.processId,
			processStepNumber: item.processStepNumber,
			processCode: item.processCode,
			processAlias: item.processAlias,
			price: 0.0,
			settlementType: currentSupplier.value.settlementType,
			remark: '',
			supplierProductId: currentProduct.value.id
		}
		dataList.push(newProcess)
	})
	console.log(dataList)
	saveSupplierProductProcess(dataList).then((res) => {
		if (res.code === 200) {
			getCurrentSupplierProductProcess()
		}
	})
}

// 保存工序
const handleSaveProcess = (row) => {
	saveSupplierProductProcess(supplierProductProcessList.value).then((res) => {
		if (res.code === 200) {
			processEditStatus.value = false
			getCurrentSupplierProductProcess()
		}
	})
}

// 删除工序
const handleDelProcess = (row) => {
	proxy.$modal
		.confirm('确认删除数据项？')
		.then(() => {
			removeSupplierProductProcess(row.id).then((res) => {
				if (res.code === 200) {
					proxy.$modal.msgSuccess('删除成功！')
					getCurrentSupplierProductProcess()
				}
			})
		})
		.catch(() => { })
}

onMounted(() => {
	getList()
})
</script>
