<template>
	<div>
		<div class="app-container">
			<div div style="font-size: 25px; text-align: left; position: relative">
				<el-button v-if="view" type="primary" @click="saveData('false')">
					{{ "保存" }}
				</el-button>

				<el-button v-if="view" type="primary" @click="saveData('true')">
					{{ "提交" }}
				</el-button>
				<!-- 附件上传按钮 -->
				<el-button type="primary" @click="openUploadDialog">上传附件</el-button>
			</div>
		</div>
		<el-divider></el-divider>
		<el-form ref="ContractSalaryForm" :rules="rules" :model="ruleFrom" :label-position="labelPosition" label-width="auto" style="width: 100%" :disabled="!view">
			<!-- 基础信息 -->
			<div class="form-dataForm">
				<el-row>基本信息</el-row>
			</div>
			<el-row>
				<el-col :span="8">
					<el-form-item label="报价单号" prop="FBILLNO">
						<el-input v-model="ruleFrom.FBILLNO" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="询价名称" prop="FProjectName">
						<el-input v-model="ruleFrom.FProjectName" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="询价单号" prop="FSrcBillNo">
						<el-input v-model="ruleFrom.FSrcBillNo" readonly />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="供应商编码" prop="FSupplierId">
						<el-input maxlength="64" v-model="ruleFrom.FSupplierId" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="供应商名称" prop="FSupplierName">
						<el-input maxlength="64" v-model="ruleFrom.FSupplierName" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="临时供应商" prop="FTempSupply">
						<el-input maxlength="64" v-model="ruleFrom.FTempSupply" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="开标日期" prop="FOpenDate">
						<el-date-picker style="width: 100%" v-model="ruleFrom.FOpenDate" type="date" format="yyyy年MM月dd日 HH时mm分ss秒" value-format="yyyy-MM-dd HH:mm:ss" readonly> </el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row>
				<el-col :span="8">
					<el-form-item label="报价状态" prop="FPriceStatus">
						<el-input v-model="ruleFrom.FPriceStatus" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="报价日期" prop="FQuoteDate">
						<el-date-picker style="width: 100%" v-model="ruleFrom.FQuoteDate" type="date" format="yyyy年MM月dd日 HH时mm分ss秒" value-format="yyyy-MM-dd HH:mm:ss" readonly>
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="报价截至日期" prop="FExpiryDate">
						<el-date-picker style="width: 100%" v-model="ruleFrom.FExpiryDate" type="date" format="yyyy年MM月dd日 HH时mm分ss秒" value-format="yyyy-MM-dd HH:mm:ss" readonly>
						</el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="联系人" prop="FContact">
						<el-input v-model="ruleFrom.FContact" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="电话" prop="FPhone">
						<el-input v-model="ruleFrom.FPhone" placeholder="请输入电话" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="邮箱" prop="FMail">
						<el-input v-model="ruleFrom.FMail" maxlength="64" placeholder="请输入邮箱" readonly />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="币别" prop="FCurrId">
						<el-input v-model="ruleFrom.FCurrId" readonly></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="含税" prop="FIsIncludedTax" style="text-align: left">
						<el-switch v-model="ruleFrom.FIsIncludedTax" :active-value="'true'" :inactive-value="'false'" active-color="#13ce66" inactive-color="#ff4949" :disabled="true"> </el-switch>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 其他信息 -->
			<el-collapse v-model="activeNames">
				<el-collapse-item title="其他信息" class="form-title" name="1">
					<div class="form-content" v-if="activeNames == '1'">
						<el-divider content-position="left"></el-divider>
						<el-row>
							<el-col :span="8">
								<el-form-item label="采购组织" prop="FPurOrgId">
									<el-input v-model="ruleFrom.FPurOrgId" readonly />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="询价日期" prop="FDate">
									<el-date-picker type="date" format="yyyy年MM月dd日 HH时mm分ss秒" value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleFrom.FDate" style="width: 100%" readonly />
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="询价员" prop="FBuyer">
									<el-input v-model="ruleFrom.FBuyer" readonly />
								</el-form-item>
							</el-col>
						</el-row>
					</div>
				</el-collapse-item>
			</el-collapse>
		</el-form>
		<el-tabs type="border-card" style="margin-top: 50px">
			<el-tab-pane label="明细信息">
				<div>
					<el-table :key="tableKey" :data="list" border fit highlight-current-row show-summary max-height="500px" style="width: 100%">
						<el-table-column prop="FSEQ" label="序号" align="center" width="50" fixed="left"></el-table-column>
						<el-table-column prop="FMaterialId" label="物料代码" min-width="150" fixed="left" align="center"> </el-table-column>
						<el-table-column prop="FMaterialName" label="物料名称" min-width="150" align="center"> </el-table-column>
						<el-table-column prop="FTempMaterial" label="临时物料名称" min-width="150" align="center"> </el-table-column>
						<el-table-column prop="FMaterialModel" label="规格型号" min-width="150" align="center"> </el-table-column>
						<el-table-column prop="FUnitID" label="单位" min-width="150" align="center"> </el-table-column>
						<el-table-column prop="FQty" label="询价数量" min-width="100" align="center"> </el-table-column>
						<el-table-column prop="FPrice" label="不含税单价" min-width="100" align="center">
							<template slot-scope="scop">
								<el-input type="number" v-model="scop.row.FPrice" v-show="priceInput" @input="updatePrice(scop.row)"></el-input>
								<span v-show="!priceInput">{{ scop.row.FPrice }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="FTaxRate" label="税率%" min-width="100" align="center">
							<template slot-scope="scop">
								<el-input type="number" v-model="scop.row.FTaxRate" v-show="priceInput" @input="updatePrice(scop.row)"></el-input>
								<span v-show="!priceInput">{{ scop.row.FTaxRate }}</span>
							</template>
						</el-table-column>
						<el-table-column prop="FTaxPrice" label="含税单价" min-width="110" align="center"> </el-table-column>
						<el-table-column prop="FNote" label="备注" align="center" width="240"> </el-table-column>
						<el-table-column prop="FPayConditionId" label="付款方式" align="center" width="240"> </el-table-column>
					</el-table>
					<!-- 附件上传弹窗 -->
					<el-dialog title="附件上传" :visible.sync="uploadDialogVisible" width="50%" :before-close="handleClose">
						<div>
							<!-- 文件上传组件 -->
							<el-upload class="upload-demo" action="uploadUrl" :auto-upload="false" :on-change="handleChange" multiple :file-list="fileList" :before-upload="handleBeforeUpload">
								<el-button size="small" type="primary">选取文件上传到服务器</el-button>
							</el-upload>
							<!-- 文件列表展示 -->
							<el-table :data="dataList" style="width: 100%; margin-top: 20px">
								<el-table-column prop="FID" label="FID"> </el-table-column>
								<el-table-column prop="FCREATETIME" label="文件名"> </el-table-column>
								<el-table-column prop="FATTACHMENTNAME" label="上传时间"> </el-table-column>
								<el-table-column label="操作">
									<template slot-scope="scope">
										<el-button type="text" @click="showConfirmDialog(scope.row.FID)">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</div>
						<span slot="footer" class="dialog-footer">
							<el-button @click="uploadDialogVisible = false">取消</el-button>
							<el-button type="primary" @click="uploadDialogVisible = false">确定</el-button>
						</span>
					</el-dialog>
				</div>
			</el-tab-pane>
		</el-tabs>

		<el-dialog title="确认删除" :visible.sync="confirmDialogVisible" width="30%">
			<span>确定要删除这个文件吗？</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="confirmDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmDelete">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import { queryData, queryDataItem, saveData, uploadUrl } from "@/api/login";
	import axios from "axios";
	// import { response } from "express";

	export default {
		name: "master",
		components: {},
		data() {
			return {
				//删除弹窗
				confirmDialogVisible: false,
				currentIndex: null,

				uploadDialogVisible: false, // 控制弹窗显示
				// 文件上传部分
				uploadUrl: "/api/admin/upload",
				file: null,
				fileList: [],
				dataList: [],
				labelPosition: "right",
				list: [],
				data: {
					FormId: "kafe2f22a0498441f9109c31cf5586da5",
					FieldKeys: "",
					FilterString: "FBILLNO like'%BJ23060004'",
					OrderString: "",
					TopRowCount: "0",
					StartRow: "0",
					Limit: 100,
				},
				tableKey: 0,
				FBILLNO: undefined,
				username: undefined,
				password: undefined,
				activeNames: "1",
				priceInput: false,
				view: true,
				multipleSelection: [],
				listQuery: {
					currentPage: 1,
					pageSize: 10,
					id: undefined,
					type: undefined,
				},
				ruleFrom: {},
				saveFrom: {
					Creator: "String",
					NeedUpDateFields: [],
					IsAutoSubmitAndAudit: true,
					Model: {
						FID: "",
						FIsConfirm: true,
						FConfirmDate: "",
						FQuoteDate: "",
						FEntity: [],
					},
				},
				rules: {
					FSupplierId: [{ required: true, message: "请输入供应商编码", trigger: ["blur", "change"] }],
					FExpiryDate: [{ required: true, message: "请选择报价截至日期", trigger: ["blur", "change"] }],
					FOpenDate: [{ required: true, message: "请选择开标日期", trigger: ["blur", "change"] }],
				},
			};
		},
		created() {
			if (this.$route.query.FBILLNO !== undefined && this.$route.query.username !== undefined && this.$route.query.password !== undefined) {
				this.FBILLNO = this.$route.query.FBILLNO;
				this.username = this.$route.query.username;
				this.password = this.$route.query.password;
				this.ruleFromData();
				this.listData();
			} else {
				this.handleWarning("请重新登录");
				if (this.$route.query.FBILLNO !== undefined) {
					this.$router.push({
						path: "/?FBILLNO=" + this.$route.query.FBILLNO,
					});
				} else {
					this.handleWarning("请重新打开链接");
					this.$router.push({
						path: "/",
					});
				}
			}
		},
		methods: {
			updatePrice(row) {
				row.FTaxPrice = (Number(row.FPrice || 0) * (1 + Number(row.FTaxRate || 0) / 100)).toFixed(2);
			},
			saveData(IsAutoAdjustField) {
				let query = {
					FID: this.ruleFrom.FID,
					IsAutoAdjustField: IsAutoAdjustField,
					FEntity: [],
				};
				if (IsAutoAdjustField === "true") {
					query.FQuoteDate = this.ruleFrom.FQuoteDate;
				}
				if (this.list && this.list.length > 0) {
					this.list.forEach((item) => {
						query.FEntity.push({
							FEntryID: item.FEntryID,
							FQty: item.FQty,
							FPrice: item.FPrice,
							FTaxRate: item.FTaxRate,
							FTaxPrice: item.FTaxPrice,
						});
					});
				}
				saveData(query).then((res) => {
					if (res.data.Result.ResponseStatus.IsSuccess) {
						this.handleSuccess(IsAutoAdjustField === "true" ? "提交成功" : "保存成功");
						this.listData();
						this.ruleFromData();
					} else {
						this.handleWarning(IsAutoAdjustField === "true" ? "提交失败" : "保存失败");
					}
				});
			},
			ruleFromData() {
				let query = {
					FBILLNO: this.FBILLNO,
					username: this.username,
					password: this.password,
				};
				queryData(query).then((res) => {
					if (!res.data) {
						this.handleWarning("获取数据失败，5秒后跳转至重新登录");
						setTimeout(() => {
							this.$router.push({
								path: "/?FBILLNO=" + this.$route.query.FBILLNO,
							});
						}, 5000);
					} else {
						this.ruleFrom = res.data[0];
						this.view = res.data[0].Status;
						this.priceInput = res.data[0].Status;
					}
				});
			},
			listData() {
				let query = {
					FBILLNO: this.FBILLNO,
					username: this.username,
					password: this.password,
				};
				queryDataItem(query).then((res) => {
					this.list = res.data;
				});
			},
			handleWarning(response) {
				this.$message({
					message: response.message || response,
					type: "warning",
					duration: 2000,
				});
			},
			handleSuccess(response) {
				this.$message({
					message: response.message || response,
					type: "success",
					duration: 2000,
				});
			},
			handleChange(file, fileList) {
				const isLt1M = file.size / 1024 / 1024 < 20; // 检查文件大小是否小于 1MB
				if (!isLt1M) {
					this.$message.error("上传文件大小不能超过 20MB");
					return isLt1M;
				}

				console.log(file, fileList);

				// 创建 FormData 对象
				const formData = new FormData();
				formData.append("file", file.raw); // 添加文件
				formData.append("FBILLNO1", this.FBILLNO); // 添加额外参数

				// 使用 axios 发送请求
				axios
					.post(this.uploadUrl, formData, {
						headers: {
							"Content-Type": "multipart/form-data", // 设置请求头
						},
					})
					.then((response) => {
						if (response.data && response.data.status === 1) {
							this.$message.success("文件上传成功");
							this.fetchFiles();
						} else {
							const errorMessage = response.data && response.data.message ? response.data.message : "未知错误";
							this.$message.error(`文件上传失败: ${errorMessage}`);
						}
					})
					.catch((error) => {
						this.$message.error(`文件上传失败: ${error.message}`);
					});
			},

			//限制文件不能大于1M
			handleBeforeUpload(file) {
				const isLt1M = file.size / 1024 / 1024 < 20; // 检查文件大小是否小于 1MB
				// if (!isLt1M) {
				//   this.$message.error('上传文件大小不能超过 1MB');
				// }
				return isLt1M; // 如果文件大小超过 1MB，返回 false 阻止上传
			},

			//删除操作
			showConfirmDialog(fid) {
				this.currentIndex = fid;
				this.confirmDialogVisible = true;
			},
			confirmDelete() {
				let query = {
					FBILLNO: this.FBILLNO,
					username: this.username,
					password: this.password,
					FID: this.currentIndex,
				};
				if (this.currentIndex !== null) {
					console.log(this.currentIndex);
					axios
						.post("/api/admin/delteFile", query)
						.then((response) => {
							if (response.data && response.data.status === 1) {
								this.$message.success("删除文件成功");
								this.fetchFiles();
							} else {
								const errorMessage = response.data && response.data.message ? response.data.message : "未知错误";
								this.$message.error(`删除文件失败: ${errorMessage}`);
							}
						})
						.catch((error) => {
							this.$message.error(`文件删除失败: ${error.message}`);
						});
				}
				this.confirmDialogVisible = false;
			},

			//打开窗体
			openUploadDialog() {
				this.fetchFiles();
				this.uploadDialogVisible = true;
			},
			//向窗体中填充数据
			fetchFiles() {
				let query = {
					FBILLNO: this.FBILLNO,
					username: this.username,
					password: this.password,
				};
				// 模拟从服务器获取数据
				axios
					.post("/api/admin/CreateFile", query)
					.then((response) => {
						// 假设响应的数据格式与之前相同，需要映射为 fileList 的格式
						// this.fileList = response.data.map(item => ({
						//   FID: item.id,
						//   name: item.fileName,
						//   CreateDate: item.uploadTime
						// }));

						this.dataList = response.data.data;
						// console.log(this.dataList);
						// debugger
					})
					.catch((error) => {
						console.error("获取数据失败，联系开发人员", error);
					});
			},
		},
	};
</script>
<style scoped>
	/* 设置表单的居中 */
	.dataForm-style {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 设置基础信息标题的样式 */
	.form-dataForm {
		width: 100%;
		height: 47px;
		text-align: left;
		line-height: 47px;
		font-size: 17px;
		font-weight: 600;
		margin: 15px 0;
		border-bottom: 1px solid #e6ebf5;
	}

	/* 去掉折叠上边框线 */
	::v-deep .el-collapse {
		border-top: 0;
	}

	/* 修改折叠标题样式 */
	::v-deep .form-title .el-collapse-item__header {
		font-size: 17px;
		font-weight: 600;
	}

	/* 修改折叠标题样式 */
	::v-deep .form-title .el-collapse-item__content {
		border-bottom: 0;
	}

	/* 修改折叠标题箭头样式 */
	::v-deep .form-title .el-collapse-item__header .el-collapse-item__arrow {
		margin: 0 0 0 5px;
	}

	::v-deep .el-divider--horizontal {
		margin: 10px 0;
	}

	/* 去掉数字输入框上下加减按钮 */
	::v-deep input::-webkit-outer-spin-button,
	::v-deep input::-webkit-inner-spin-button {
		-webkit-appearance: none;
	}
</style>
