<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.purchaseTracking.getToken()">
				<el-tab-pane label="采购申请信息" name="purchase"></el-tab-pane>
				<el-tab-pane v-if="form.processInstanceId" label="流程跟踪" name="purchase_tracking"></el-tab-pane>
			</el-tabs>
		</template>

		<el-tabs v-model="activeName">
			<el-tab-pane name="purchase">
				<scApply ref="scApply" :id="form.id" :lg="12" :disabled="!showFooter"></scApply>
			</el-tab-pane>
			<el-tab-pane v-if="form.processInstanceId" name="purchase_tracking">
				<tracking ref="purchaseTracking" :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(mode)">保 存</el-button>
			<el-button type="primary" :loading="isSaveing" @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 scApply from "@/components/scChengTou/purchase/apply";
	import Tracking from "@/components/scChengTou/purchase/tracking";

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

		data() {
			return {
				mode: "add",
				visible: false,
				isSaveing: false,
				popoverShow: false,
				
				activeName: "purchase",
				form: {}
			}
		},

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

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

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

			// 表单提交方法
			validateForm(mode) {
                const promiseArr = [this.$refs.scApply.$refs.dialogForm.validate()];
                if (this.$refs.scApply.form.isLawyer == 1) promiseArr.push(this.$refs.scApply.$refs.lawyerSelection.$refs.dialogForm.validate());
                
                Promise.all(promiseArr).then(() => {
                    if (mode == "saveApprove") {
                        if (!this.form.status) {
                            this.popoverShow = true;
                            this.$nextTick(() => this.$refs.approveIframe.open().setData());
                        } else this.submit("resubmit", this.form.processTemplateId);
                    } else this.submit(mode);
                }).catch(() => false);
			},

			submit(mode, templateId, userTaskAssigneePropsList, dataContext) {
				const data = {};
				for (const key in this.$refs.scApply.form) {
					if (key == "folders") {
						for (const folder_key in this.$refs.scApply.form[key]) {
                            const applyFiles = this.$refs.scApply.form[key][folder_key]["entities"].filter(item => !item.id).map(item => item.path);
                            if (applyFiles.length) {
                                if (!data[key]) data[key] = {};
                                data[key][folder_key] = {
                                    entities: applyFiles.map(ticket => ({ features: { ticket } }))
                                }
                            }
                        }
					} else data[key] = this.$refs.scApply.form[key];
				}
				if (templateId) data["templateId"] = templateId;
				if (userTaskAssigneePropsList) data["userTaskAssigneePropsList"] = userTaskAssigneePropsList;
				if (dataContext) {
                    data["extData"] = {
                        dataContext,
                        isCostApprovalRequired: this.$refs.scApply.form.isCostApprovalRequired || "0",
                        specialExpensesType: this.$refs.scApply.formatType(this.$refs.scApply.form.specialFeeType, "special_expenses_type"),
                        externalLawyerSelection: this.$refs.scApply.form.isLawyer + ""
                    };
                }
				if (mode == "resubmit") data["processTaskId"] = this.form.processTaskId;
                
				this.isSaveing = true;
				this.$API.procurement.apply[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>