<template>
	<sc-dialog v-model="visible" width="80%" top="13vh" @closed="$emit('closed')">
		<template v-slot:header>
			<el-tabs v-model="activeName" @tab-change="$refs.handlerTracking.getToken()">
				<el-tab-pane :label="`${stepDic[mode]}单`" :name="mode"></el-tab-pane>
				<el-tab-pane v-if="form.processInstanceId" label="流程跟踪" name="handle_tracking"></el-tab-pane>
			</el-tabs>
		</template>

		<el-tabs v-model="activeName">
			<el-tab-pane :name="mode">
				<scHandler ref="scHandler" :id="purchase.id" :mode="mode" :lg="12" :disabled="!showFooter" @hasFolders="hasFolders = true"></scHandler>
			</el-tab-pane>
			<el-tab-pane v-if="form.processInstanceId" name="handle_tracking">
				<tracking ref="handlerTracking" :processInstanceId="form.processInstanceId"></tracking>
			</el-tab-pane>
		</el-tabs>

		<template v-if="showFooter" #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="validateForm('add')">保 存</el-button>
			<el-button v-if="showApprove" type="primary" :loading="isSaveing" :disabled="mode == 'purchase_answer_sign' && !hasFolders" @click="validateForm('saveApprove')">提 交</el-button>
		</template>
	</sc-dialog>

	<approve-iframe v-if="popoverShow" ref="approveIframe" @success="approve" @closed="popoverShow = false"></approve-iframe>
</template>

<script>
	import { stepDic } from "@/views/procurement/process/main";
	import scHandler from "@/components/scChengTou/purchase/handler";
	import Tracking from "@/components/scChengTou/purchase/tracking";

	export default {
		emits: ["success", "closed"],
		components: {
			scHandler,
			Tracking
		},

		data() {
			return {
				stepDic,
				mode: "purchase_matter",
				visible: false,
				isSaveing: false,
				popoverShow: false,

				activeName: "purchase_matter",
				purchase: {},
				form: {},

				hasFolders: false
			}
		},

		computed: {
			showFooter() {
				return !this.form.status || this.form.status == "active";
			},

			showApprove() {
				return (!this.purchase.status || this.purchase.status == "done") || (this.purchase.status == "active" && this.purchase.step == this.mode);
			}
		},

		methods: {
			// 显示
			open(mode = "purchase_matter") {
				this.mode = mode;
				this.activeName = mode;
				this.visible = true;
				return this;
			},

			setData(purchase, model) {
				this.purchase["id"] = purchase.id;
				this.purchase["step"] = purchase.step;
				this.purchase["status"] = purchase.status;
				this.form["id"] = model.id;
				this.form["status"] = model.status;
				this.form["processTaskId"] = model.processTaskId;
				this.form["processInstanceId"] = model.processInstanceId;
				this.form["processTemplateId"] = model.processTemplateId;
			},

			// 表单提交方法
			validateForm(mode) {
				this.$refs.scHandler.$refs.dialogForm.validate(valid => {
					if (valid) {
						if (mode == "saveApprove") {
							if (!this.form.status) {
								this.popoverShow = true;
								this.$nextTick(() => this.$refs.approveIframe.open(this.mode).setData());
							} else this.submit("resubmit", this.form.processTemplateId);
						} else this.submit(mode);
					} else {
						return false;
					}
				});
			},

			submit(mode, templateId, userTaskAssigneePropsList, dataContext) {
				const data = {};
				for (const key in this.$refs.scHandler.form) {
					if (key == "folders") {
                        for (const folder_key in this.$refs.scHandler.form[key]) {
                            const newFiles = this.$refs.scHandler.form[key][folder_key]["entities"].filter(item => !item.id).map(item => item.path);
                            if (newFiles.length) {
                                if (!data[key]) data[key] = {};
                                data[key][folder_key] = {
                                    entities: newFiles.map(ticket => ({ features: { ticket } }))
                                }
                            }
                        }
					} else data[key] = this.$refs.scHandler.form[key];
				}
				if (templateId) data["templateId"] = templateId;
				if (userTaskAssigneePropsList) data["userTaskAssigneePropsList"] = userTaskAssigneePropsList;
				if (dataContext) {
                    data["extData"] = { dataContext };
				    if (this.mode == "purchase_bid_sign") data["extData"]["isCostApprovalRequired"] = this.$refs.scHandler.form.isCostApprovalRequired || "0";
				    if (this.mode == "purchase_matter" || this.mode == "purchase_bid_sign") data["extData"]["specialExpensesType"] = this.$refs.scHandler.formatType(this.$refs.scHandler.apply.specialFeeType, "special_expenses_type");
                }
				if (this.mode == "purchase_bid_notice") data["projectId"] = this.$refs.scHandler.apply.projectId || null;
				if (mode == "resubmit") data["processTaskId"] = this.form.processTaskId;
				
                this.isSaveing = true;
				this.$API.procurement[this.$refs.scHandler.handlerKey()][mode](data).then(() => {
					this.isSaveing = false;
					this.$message.success("操作成功");
					this.visible = false;
					this.$emit("success", mode);
				}).catch(() => this.isSaveing = false);
			},

			approve({ processDefinitionId, userTaskAssigneeDtos }, dataContext) {
				this.submit("saveApprove", processDefinitionId || null, userTaskAssigneeDtos || [], dataContext);
			}
		}
	}
</script>

<style lang="scss" scoped>
.sc-dialog:deep(.el-dialog) {
  .el-dialog__header {
    padding: 0;

    &::after {
      display: none;
    }

    .sc-dialog__headerbtn button {
      margin-left: 0;
    }

    .el-tabs {
      flex-basis: 100%;
      --el-tabs-header-height: 50px;

      .el-tabs__header {
        margin-bottom: 0;

        .el-tabs__nav-wrap::after {
          height: 1px;
        }

        .el-tabs__item {
          padding-bottom: 10px;
        }
      }

      .el-tabs__content {
        display: none;
      }
    }
  }

  .el-dialog__body {
    padding-bottom: 0;

    .el-tabs .el-tabs__header {
      display: none;
    }
  }
}
</style>