<template>
	<div>
		<el-form ref="inputForm" :model="inputForm" v-loading="loading" :class="method === 'view' ? 'readonly' : ''"
			:disabled="status === 'audit' || status === 'taskFormDetail'" label-width="100px" @submit.native.prevent>
			<el-divider content-position="left">
				<i class="el-icon-document"></i> 基础信息
			</el-divider>
			<el-row :gutter="26">
				<el-col :span="12">
					<el-form-item label="报损编号" prop="lossNo">
						<el-input v-model="inputForm.lossNo" placeholder="自动生成" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="经办人" prop="handledBy">
						<el-input v-model="inputForm.handledBy" disabled />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="经办部门" prop="handledByOffice">
						<SelectTree ref="officeTree" :disabled="true"
							:props="{ value: 'id', label: 'name', children: 'children' }"
							:url="`/system-server/sys/office/treeData?type=2`" :value="inputForm.handledByOffice"
							:accordion="true" size="default" @getValue="value => (inputForm.handledByOffice = value)" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="报损时间" prop="lossDate"
						:rules="[{ required: true, message: '请选择报损时间', trigger: 'blur' }]">
						<el-date-picker v-model="inputForm.lossDate" type="date" value-format="YYYY-MM-DD"
							style="width: 100%" placeholder="选择日期" :disabled="formReadOnly || method === 'view'" />
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="备注" prop="remarks">
						<el-input v-model="inputForm.remarks" type="textarea" :rows="4" maxlength="500" show-word-limit
							:disabled="formReadOnly || method === 'view'" placeholder="请输入备注信息" />
					</el-form-item>
				</el-col>
			</el-row>

			<el-divider content-position="left">
				<i class="el-icon-document"></i> 报损明细
				<el-button style="margin-left: 20px" type="primary" plain
					:disabled="method === 'view' || formReadOnly || inputForm.detailInfos.length > 0"
					@click="insertEvent()">
					新增
				</el-button>
			</el-divider>

			<el-row :gutter="15">
				<el-col :span="24">
					<vxe-table ref="detailTable" border show-overflow class="vxe-table-element"
						:data="inputForm.detailInfos" style="margin-left: 5em" :key="clientTableKey"
						highlight-current-row
						:edit-config="{ trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-' }"
						:edit-rules="validRules">
						<vxe-table-column field="recipientAgent" title="报损人" :edit-render="{}"
							:rules="[{ required: true, message: '请选择报损人', trigger: 'blur' }]">
							<template #edit="scope">
								<el-input v-model="scope.row.recipientAgent"
									:disabled="formReadOnly || method === 'view'"
									@focus="userPullListForm(scope.$rowIndex)" />
							</template>
						</vxe-table-column>
						<vxe-table-column field="recipientOffice" title="报损人部门" :edit-render="{}">
							<template #edit="scope">
								<el-input v-model="scope.row.recipientOffice" disabled />
							</template>
						</vxe-table-column>
						<vxe-table-column field="collectType" title="物品类型" :edit-render="{}"
							:rules="[{ required: true, message: '请选择物品类型', trigger: 'blur' }]">
							<template #edit="scope">
								<el-input v-model="scope.row.collectType" :disabled="formReadOnly || method === 'view'"
									@focus="typePullForm(scope.$rowIndex)" />
							</template>
						</vxe-table-column>
						<vxe-table-column field="goodsName" title="物品名称" :edit-render="{}"
							:rules="[{ required: true, message: '请选择物品名称', trigger: 'blur' }]">
							<template #edit="scope">
								<el-input v-model="scope.row.goodsName" :disabled="formReadOnly || method === 'view'"
									@focus="openPurchasePageForm(scope.$rowIndex, scope.row)" />
							</template>
						</vxe-table-column>
						<vxe-table-column field="spec" title="包装规格" :edit-render="{}">
							<template #edit="scope">
								<el-input v-model="scope.row.spec" disabled />
							</template>
						</vxe-table-column>
						<vxe-table-column field="produceDate" title="生产日期" :edit-render="{}">
							<template #edit="scope">
								<el-date-picker v-model="scope.row.produceDate" type="date" value-format="YYYY-MM-DD"
									style="width: 100%" disabled />
							</template>
						</vxe-table-column>
						<vxe-table-column field="lossNumber" title="报损数量" :title-suffix="numberTitleSuffix"
							:edit-render="{}" :rules="[{ required: true, message: '请输入报损数量', trigger: 'blur' }]">
							<template #edit="scope">
								<el-input v-model="scope.row.lossNumber" maxlength="10"
									:disabled="formReadOnly || method === 'view'"
									@blur="handleLossNumberBlur(scope.row)" />
							</template>
						</vxe-table-column>
						<!-- <vxe-table-column field="currentInventory" title="当前库存" :edit-render="{}">
							<template #edit="scope">
								<el-input v-model="scope.row.currentInventory" disabled />
							</template>
						</vxe-table-column> -->
						<!-- <vxe-table-column field="company" title="单位" :edit-render="{}"
							:rules="[{ required: true, message: '请输入单位', trigger: 'blur' }]">
							<template #edit="scope">
								<el-input v-model="scope.row.company" disabled />
							</template>
						</vxe-table-column> -->
						<vxe-table-column title="操作" width="220">
							<template #default="scope">
								<vxe-button size="small" status="danger" :disabled="formReadOnly || method === 'view'"
									@click="removeEvent(scope.row, scope.$rowIndex)">
									删除
								</vxe-button>
								<vxe-button size="small" status="primary" :disabled="formReadOnly || method === 'view'"
									@click="openUpload(scope.$rowIndex)">
									上传附件
								</vxe-button>
								<vxe-button v-if="formReadOnly" size="small" status="primary"
									@click="seeFileInfo(scope.$rowIndex)">
									查看附件
								</vxe-button>
							</template>
						</vxe-table-column>
					</vxe-table>
				</el-col>
			</el-row>
		</el-form>

		<PurchasePageForm ref="purchasePageForm" @getProject="getContract" />
		<MaterialManagementDialog ref="materialManagementDialog" @getUpload="getUpload" />
		<UpLoadComponent ref="uploadComponent" />
		<MaterialTypePullForm ref="materialTypePullForm" @getProgramForType="getProgramForType" />
		<UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser" />
	</div>
</template>

<script>
import LossService from "@/api/psi/LossService";
import WareHouseService from "@/api/psi/WareHouseService";
import UpLoadComponent from "@/views/common/UpLoadComponent";
import SelectTree from "@/components/treeSelect/treeSelect.vue";
import UserPullForm from "@/views/psiManagement/components/UserPullForm";
import MaterialManagementDialog from "../file/MaterialManagementDialog";
import MaterialTypePullForm from "../info/MaterialTypePullForm";
import PurchasePageForm from "./PurchasePageForm";

export default {
	components: {
		UpLoadComponent,
		SelectTree,
		UserPullForm,
		MaterialManagementDialog,
		MaterialTypePullForm,
		PurchasePageForm,
	},
	props: {
		businessId: {
			type: String,
			default: "",
		},
		formReadOnly: {
			type: Boolean,
			default: false,
		},
		status: {
			type: String,
			default: "",
		},
	},
	data() {
		return {
			numberTitleSuffix: {
				content: "报损数量按最小单位填写",
			},
			validRules: {
				recipientAgent: [{ required: true, message: "报损人不能为空" }],
				collectType: [{ required: true, message: "物品类型不能为空" }],
				goodsName: [{ required: true, message: "物品名称不能为空" }],
				lossNumber: [{ required: true, message: "报损数量不能为空" }],
			},
			method: "",
			loading: false,
			indexRow: "",
			clientTableKey: "",
			keyWatch: "",
			inputForm: {
				handledByOffice: "",
				handledBy: "",
				handledById: "",
				lossNo: "",
				lossDate: "",
				remarks: "",
				detailInfos: [],
				files: [],
				procInsId: "",
				status: "",
			},
		};
	},
	created() {
		this.lossService = new LossService();
		this.wareHouseService = new WareHouseService();
	},
	computed: {
		bus: {
			get() {
				return this.businessId;
			},
			set(val) {
				this.businessId = val;
			},
		},
		officeName() {
			return this.$store.state.user.office.name;
		},
	},
	watch: {
		keyWatch() {
			if (this.commonJS.isNotEmpty(this.bus)) {
				this.init("", this.bus);
			}
		},
		loading(newVal) {
			this.$emit("changeLoading", newVal);
			if (this.$refs.uploadComponent) {
				this.$refs.uploadComponent.changeLoading(newVal);
			}
		},
	},
	methods: {
		getKeyWatch(keyWatch) {
			this.keyWatch = keyWatch;
		},
		createDefaultForm() {
			return {
				handledByOffice: this.$store.state.user.office.id,
				handledBy: this.$store.state.user.name,
				handledById: this.$store.state.user.id,
				lossNo: "",
				lossDate: new Date(),
				remarks: "",
				detailInfos: [],
				files: [],
				procInsId: "",
				status: "",
			};
		},
		init(method, id) {
			this.method = method;
			this.inputForm = this.createDefaultForm();
			this.inputForm.id = id;
			if (this.$refs.uploadComponent) {
				this.$refs.uploadComponent.clearUpload();
			}
			this.$nextTick(() => {
				if (this.$refs.inputForm) {
					this.$refs.inputForm.resetFields();
				}
				if (id && id !== "false") {
					this.loading = true;
					this.lossService
						.findById(id)
						.then(data => {
							this.inputForm = this.recover(this.inputForm, data)

							// this.inputForm = this.recover(this.createDefaultForm(), data);
							this.inputForm.id = data.id;
							this.inputForm.detailInfos = this.inputForm.detailInfos || [];

							this.$refs.uploadComponent.newUpload(this.method ? this.method : "view", this.inputForm.files, "psi");

						})
						.finally(() => {
							this.loading = false;
						});
				} else {
					this.$refs.uploadComponent.newUpload(this.method ? this.method : "view", [], "psi");
				}
			});
		},
		insertEvent() {
			if (this.inputForm.detailInfos.length > 0) {
				this.$message.warning("报损明细只能保留一条");
				return;
			}
			this.$refs.detailTable.insert().then(row => {
				row.recipientAgent = this.$store.state.user.name;
				row.recipientAgentId = this.$store.state.user.id;
				row.recipientOffice = this.officeName;
				row.fileInfoLost = [];
				this.inputForm.detailInfos.push(row);
				this.clientTableKey = Math.random();
			});
		},
		removeEvent(row, rowIndex) {
			this.$refs.detailTable.remove(row);
			this.inputForm.detailInfos.splice(rowIndex, 1);
		},
		openUpload(index) {
			if (this.commonJS.isEmpty(this.inputForm.detailInfos[index].fileInfoLost)) {
				this.inputForm.detailInfos[index].fileInfoLost = [];
			}
			this.$refs.materialManagementDialog.newUpload(
				null,
				this.inputForm.detailInfos[index].fileInfoLost,
				null,
				null,
				null,
				null,
				null,
				false,
				index
			);
		},
		seeFileInfo(index) {
			if (this.commonJS.isEmpty(this.inputForm.detailInfos[index].fileInfoLost)) {
				this.inputForm.detailInfos[index].fileInfoLost = [];
			}
			this.$refs.materialManagementDialog.newUpload(
				"view",
				this.inputForm.detailInfos[index].fileInfoLost,
				null,
				null,
				null,
				null,
				null,
				false,
				index
			);
		},
		getUpload(promise, index) {
			promise.then(list => {
				this.inputForm.detailInfos[index].fileInfoLost = list;
				this.clientTableKey = Math.random();
			});
		},
		doSubmit() {
			this.validateForm().then(valid => {
				if (!valid) {
					return;
				}
				this.loading = true;
				this.inputForm.files = this.$refs.uploadComponent.getDataList();
				this.lossService
					.save(this.inputForm)
					.then(() => {
						this.$message.success("操作成功");
						this.$emit("refreshDataList");
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		close() {
			if (this.$refs.inputForm) {
				this.$refs.inputForm.resetFields();
			}
			this.inputForm = this.createDefaultForm();
			if (this.$refs.uploadComponent) {
				this.$refs.uploadComponent.clearUpload();
			}
		},
		reapplyForm(callback) {
			this.loading = true;
			this.lossService.findById(this.inputForm.id).then(data => {
				if (data.status !== "4") {
					this.loading = false;
					this.$message.error("任务数据已发生变化，请在待办中确认");
					throw new Error("status changed");
				}
				this.startFormTrue(callback);
			});
		},
		startForm(callback) {
			this.loading = true;
			if (this.commonJS.isNotEmpty(this.inputForm.id)) {
				this.lossService.findById(this.inputForm.id).then(data => {
					if (this.commonJS.isNotEmpty(data.status) && !["0", "1", "3"].includes(data.status)) {
						this.loading = false;
						this.$message.error("任务数据已发生变化，请在待办中确认");
						throw new Error("status changed");
					}
					this.startFormTrue(callback);
				});
				return;
			}
			this.startFormTrue(callback);
		},
		saveForm(callback) {
			this.loading = true;
			if (this.$refs.uploadComponent.checkProgress()) {
				this.loading = false;
				return;
			}
			this.inputForm.files = this.$refs.uploadComponent.getDataList();
			this.inputForm.status = "1";
			this.lossService
				.save(this.inputForm)
				.then(() => {
					callback();
					this.$refs.inputForm.resetFields();
				})
				.finally(() => {
					this.loading = false;
				});
		},
		startFormTrue(callback) {
			this.validateForm().then(valid => {
				if (!valid) {
					return;
				}
				this.loading = true;
				this.inputForm.files = this.$refs.uploadComponent.getDataList();
				this.inputForm.status = "2";
				this.lossService
					.save(this.inputForm)
					.then(data => {
						this.inputForm.id = data.businessId;
						callback(data.businessTable, data.businessId, this.inputForm);
						this.$refs.inputForm.resetFields();
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		agreeForm(callback) {
			this.validateForm(false).then(valid => {
				if (!valid) {
					return;
				}
				this.loading = true;
				this.inputForm.files = this.$refs.uploadComponent.getDataList();
				this.inputForm.status = "5";
				this.lossService
					.save(this.inputForm)
					.then(data => {
						callback(data.businessTable, data.businessId, this.inputForm);
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},
		updateStatusById(type, callback) {
			this.loading = true;
			if (this.$refs.uploadComponent.checkProgress()) {
				this.loading = false;
				throw new Error("uploading");
			}
			if (type === "reject" || type === "reback") {
				this.lossService.findById(this.inputForm.id).then(data => {
					if (data.status !== "2") {
						this.loading = false;
						this.$message.error("任务数据已发生变化，请在待办中确认");
						throw new Error("status changed");
					}
					const status = type === "reject" ? "4" : "3";
					this.lossService.updateStatusById({ status, id: this.inputForm.id }).then(() => {
						this.loading = false;
						callback();
					});
				});
				return;
			}
			if (type === "hold") {
				this.lossService.findById(this.inputForm.id).then(data => {
					if (data.status !== "4") {
						this.loading = false;
						this.$message.error("任务数据已发生变化，请在待办中确认");
						throw new Error("status changed");
					}
					this.lossService.updateStatusById({ status: "1", id: this.inputForm.id }).then(() => {
						this.loading = false;
						callback();
					});
				});
			}
		},
		typePullForm(rowIndex) {
			this.indexRow = rowIndex;
			this.$refs.materialTypePullForm.init();
		},
		getProgramForType(row) {
			const detail = this.inputForm.detailInfos[this.indexRow];
			detail.collectTypeId = row.id;
			detail.collectType = row.name;
			detail.goodsName = "";
			detail.spec = "";
			detail.produceDate = "";
			detail.surplusNumber = "";
			this.indexRow = "";
			this.$forceUpdate();
		},
		userPullListForm(rowIndex) {
			this.indexRow = rowIndex;
			this.$refs.userPullForm.init();
		},
		getProgramForUser(rows) {
			const detail = this.inputForm.detailInfos[this.indexRow];
			detail.recipientAgentId = rows[0].id;
			detail.recipientAgent = rows[0].name;
			detail.recipientOffice = rows[0].officeName;
			this.indexRow = "";
			this.$forceUpdate();
		},
		openPurchasePageForm(rowIndex, row) {
			if (this.commonJS.isEmpty(row.collectTypeId)) {
				this.$message.error("请先选择物品类型");
				return;
			}
			this.indexRow = rowIndex;
			this.$refs.purchasePageForm.init(row.collectTypeId);
		},
		getContract(row) {
			const detail = this.inputForm.detailInfos[this.indexRow];
			detail.goodsName = row.tradeName;
			detail.company = row.company || detail.company;
			detail.produceDate = row.produceDate || "";
			detail.shelfLife = row.shelfLife || "";
			detail.shelfLifeUnit = row.shelfLifeUnit || "";
			detail.currentInventory = row.currentInventory || "";
			detail.spec = row.spec || "";
			detail.company = row.company || "";

			// this.loadInventorySummary(detail);
			this.indexRow = "";
			this.$forceUpdate();
		},
		loadInventorySummary(detail) {
			this.wareHouseService
				.getByProduceDateNotMerge({
					current: 1,
					size: 1000,
					tradeName: detail.goodsName,
					wareHouseType: detail.collectTypeId,
				})
				.then(data => {
					const records = data.records || [];
					let total = 0;
					if (records.length > 0) {
						detail.spec = records[0].spec || detail.spec;
						detail.company = records[0].company || detail.company;
					}
					records.forEach(item => {
						const current = Number(item.currentInventory || 0);
						const spec = Number(item.spec || 1);
						total += current * spec;
					});
					detail.surplusNumber = this.formatNumber(total);
				});
		},
		handleLossNumberBlur(row) {
			row.lossNumber = this.normalizeNumber(row.lossNumber);
			if (
				this.commonJS.isNotEmpty(row.surplusNumber) &&
				this.commonJS.isNotEmpty(row.lossNumber) &&
				Number(row.lossNumber) > Number(row.surplusNumber)
			) {
				this.$message.error("报损数量不能大于当前库存");
				row.lossNumber = "";
			}
		},
		normalizeNumber(num) {
			if (this.commonJS.isEmpty(num)) {
				return "";
			}
			let str = num.toString();
			const len1 = str.substr(0, 1);
			const len2 = str.substr(1, 1);
			if (str.length > 1 && len1 === "0" && len2 !== ".") {
				str = str.substr(1, 1);
			}
			if (len1 === ".") {
				str = "";
			}
			if (str.indexOf(".") !== -1) {
				const str2 = str.substr(str.indexOf(".") + 1);
				if (str2.indexOf(".") !== -1) {
					str = str.substr(0, str.indexOf(".") + str2.indexOf(".") + 1);
				}
				if (str2.length > 2) {
					this.$message.warning("数量小数点后只能输入两位");
					return "";
				}
			}
			return str.replace(/[^\d^.]+/g, "");
		},
		formatNumber(value) {
			const num = Number(value || 0);
			if (Number.isNaN(num)) {
				return "0";
			}
			return num % 1 === 0 ? String(num) : num.toFixed(2).replace(/\.?0+$/, "");
		},
		validateForm(checkStock = true) {
			return new Promise(resolve => {
				this.$refs.inputForm.validate(valid => {
					if (!valid) {
						resolve(false);
						return;
					}
					if (this.$refs.uploadComponent.checkProgress()) {
						resolve(false);
						return;
					}
					if (this.commonJS.isEmpty(this.inputForm.detailInfos)) {
						this.$message.error("请填写报损明细");
						resolve(false);
						return;
					}
					const detail = this.inputForm.detailInfos[0];
					if (this.commonJS.isEmpty(detail.recipientAgent)) {
						this.$message.error("请选择报损人");
						resolve(false);
						return;
					}
					if (this.commonJS.isEmpty(detail.collectType)) {
						this.$message.error("请选择物品类型");
						resolve(false);
						return;
					}
					if (this.commonJS.isEmpty(detail.goodsName)) {
						this.$message.error("请选择物品名称");
						resolve(false);
						return;
					}
					if (this.commonJS.isEmpty(detail.lossNumber)) {
						this.$message.error("请输入报损数量");
						resolve(false);
						return;
					}
					if (
						checkStock &&
						this.commonJS.isNotEmpty(detail.surplusNumber) &&
						Number(detail.lossNumber) > Number(detail.surplusNumber)
					) {
						this.$message.error("报损数量不能大于当前库存");
						resolve(false);
						return;
					}
					resolve(true);
				});
			});
		},
	},
};
</script>
