<template>
	<scTitle v-if="isIframe" class="iframe-detail-title">{{ stepDic[mode] }}单</scTitle>
	<el-form v-loading="loading" :class="['dialog-form', disabled && 'dialog-form-disabled']" ref="dialogForm" :model="form" :rules="rules" :disabled="disabled" label-width="140px">
		<el-row :gutter="15">
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="送审标题:" prop="approveTitle">
					<el-input v-model="form.approveTitle" placeholder="请输入送审标题"></el-input>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="采购申请名称:" prop="purchaseId">
					<el-select v-model="form.purchaseId" disabled placeholder="若直接点击单据可自动带出，否则需关联选择">
						<el-option :label="apply.name" :value="form.purchaseId"></el-option>
					</el-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="采购所属项目:">
					<el-select v-model="apply.projectId" disabled placeholder="若为项目采购需填写, 自动带出">
						<el-option v-for="item in projects" :key="item.id" :label="item.projectName" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="采购类别:">
					<dict-select ref="dictSelect" v-model="apply.type" dic="procurement_category" disabled placeholder="自动带出"></dict-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="公司/部门名称:">
					<tree-select v-model="apply.deptId" :apiObj="$API.system.dept" isDept disabled placeholder="自动带出"></tree-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="招采类型:">
					<dict-select v-model="apply.purchaseType" dic="procurement_type" disabled placeholder="自动带出"></dict-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="业务所属公司:">
					<tree-select v-model="apply.belongDeptId" :apiObj="$API.system.dept" isDept disabled placeholder="自动带出"></tree-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item label="创建人:" prop="createId">
					<sc-table-select v-model="form.person" :apiObj="tableSelect.apiObj" :table-width="840" :props="tableSelect.props" disabled placeholder="请选择创建人" placement="bottom">
						<template #header="{ queryForm, submit: fetchPerson }">
							<el-row :gutter="15">
								<el-col :md="8" :xs="24">
									<el-form-item>
										<el-input class="search-input-suffix" v-model="queryForm.blurry" clearable placeholder="输入姓名、账号、手机关键字" @keyup.enter="fetchPerson" @clear="fetchPerson">
											<template #suffix>
												<el-icon @click="fetchPerson"><el-icon-search /></el-icon>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</template>

						<el-table-column label="姓名" prop="username" align="center"></el-table-column>
						<el-table-column label="账号" prop="nickName" align="center"></el-table-column>
						<el-table-column label="所属组织" prop="dept.name" align="center"></el-table-column>
						<el-table-column label="手机" prop="phone" align="center"></el-table-column>
					</sc-table-select>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item v-if="mode == 'purchase_bid_notice'" label="中标金额:" prop="bidAmount">
					<el-input-number v-model="form.bidAmount" :precision="2" :step="0.1" :controls="false" placeholder="请输入中标金额"></el-input-number>
					<span class="input-number-suffix">元</span>
				</el-form-item>
				<el-form-item v-else label="预算金额:">
					<el-input-number v-model="apply.budgetAmount" :precision="2" :step="0.1" disabled :controls="false" placeholder="自动带出"></el-input-number>
					<span class="input-number-suffix">元</span>
				</el-form-item>
			</el-col>
			<el-col :lg="lg" :md="12" :xs="24">
				<el-form-item v-if="mode == 'purchase_bid_notice'" label="中标单位:" prop="supplierId">
					<el-select v-model="form.supplierId" filterable multiple placeholder="请选择中标单位" @change="supplierChange">
						<el-option v-for="item in suppliers" :key="item.id" :label="item.supplierName" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item v-else :label="`${stepDic[mode]}名称:`" :prop="`${handlerKey('suffix')}Name`" :rules="{ required: true, message: `请输入${stepDic[mode]}名称`}">
					<el-input v-model="form[`${handlerKey('suffix')}Name`]" :placeholder="`请输入${stepDic[mode]}名称`"></el-input>
				</el-form-item>
			</el-col>
			<template v-if="mode == 'purchase_bid_notice'">
				<el-col :lg="lg" :md="12" :xs="24">
					<el-form-item label="招标平台:" prop="bidPlatform">
						<dict-select v-model="form.bidPlatform" dic="bidding_platform" placeholder="请选择招标平台"></dict-select>
					</el-form-item>
				</el-col>
				<el-col :lg="lg" :md="12" :xs="24">
					<el-form-item label="控制价:">
						<el-input-number v-model="form.controlAmount" :precision="2" :step="0.1" :controls="false" placeholder="请输入控制价"></el-input-number>
						<span class="input-number-suffix">元</span>
					</el-form-item>
				</el-col>
				<el-col :lg="lg" :md="12" :xs="24">
					<el-form-item label="招标代理:" prop="bidAgency">
						<dict-select v-model="form.bidAgency" dic="bidding_agency" placeholder="请选择招标代理"></dict-select>
					</el-form-item>
				</el-col>
			</template>
			<el-col :xs="24">
				<el-form-item label="备注:">
					<el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入"></el-input>
				</el-form-item>
			</el-col>
			<el-col v-if="mode == 'purchase_answer_sign'" :xs="24">
				<el-form-item class="no-upload-btn">
					<template #label>招标文件附件
						<el-tooltip placement="top">
							<template #content>无招标文件附件，不允许提交审核</template>
							<el-icon class="tips__icon"><el-icon-question-filled /></el-icon>
						</el-tooltip>:
					</template>
					<sc-upload-file v-model="bidSign.folders" disabled></sc-upload-file>
				</el-form-item>
			</el-col>
			<el-col :xs="24">
				<el-form-item :class="disabled && 'no-upload-btn'" label="附件上传:">
					<sc-upload-file v-model="form.folders[`purchase/${handlerKey('lowercase')}`].entities" :limit="10">
						<el-button type="primary" icon="el-icon-upload" size="small"></el-button>
					</sc-upload-file>
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>

<script>
	import { stepDic } from "@/views/procurement/process/main";
	
	export default {
		emits: ["hasFolders"],
		props: {
			id: { type: String, default: "" }, // 采购id
			mode: { type: String, default: "purchase_matter" },
			lg: { type: Number, default: 8 },
			disabled: { type: Boolean, default: false },
			isIframe: { type: Boolean, default: false }
		},

		data() {
			return {
				loading: false,
				stepDic,
				projects: [],
				suppliers: [],

				tableSelect: {
					apiObj: this.$API.system.user,
					props: { page: "page", label: "nickName" }
				},

				apply: {
					name: null,
					deptId: null,
					belongDeptId: null,
					type: null,
					purchaseType: null,
					budgetAmount: null,
					projectId: null
				},
				bidSign: {
					folders: []
				},
				form: {
					id: null,
					approveTitle: null,
					purchaseId: null,
					person: { ...this.$TOOL.data.get("USER_INFO") },
					createId: this.$TOOL.data.get("USER_INFO").id,
					createName: this.$TOOL.data.get("USER_INFO").nickName,
					bidAmount: null,
					controlAmount: null,
					supplierId: [],
					bidCompanyIds: null,
					bidCompanyName: null,
					bidPlatform: null,
					bidAgency: null,
					remark: null,
					folders: {}
				},
				rules: {
					approveTitle: [{ required: true, message: "请输入送审标题" }],
					purchaseId: [{ required: true, message: "请选择采购申请" }],
					bidAmount: [{ required: true, message: "请输入中标金额" }],
					supplierId: [{ required: true, message: "请选择中标单位" }],
					bidPlatform: [{ required: true, message: "请选择招标平台" }],
					bidAgency: [{ required: true, message: "请选择招标代理" }]
				}
			}
		},

		created() {
			this.form[`${this.handlerKey("suffix")}Name`] = null;
			this.form.folders = {
				[`purchase/${this.handlerKey("lowercase")}`]: {
					entities: []
				}
			}
		},

		mounted() {
			this.getProjects();
			this.getSupplier();
			this.setData();
		},

		methods: {
			handlerKey(format = "hump") {
				const modeArray = this.mode.split("purchase_")[1].split("_");
				const suffixArray = modeArray.slice(1);

				if (format == "lowercase") return modeArray.join("");
				if (format == "suffix") return suffixArray.length && suffixArray[0] + suffixArray.slice(1).map(str => this.$TOOL.capitalizeWords(str)).join("") || modeArray[0];
				return modeArray[0] + suffixArray.map(str => this.$TOOL.capitalizeWords(str)).join("");
			},

			async getProjects() {
				this.projects = await this.$API.system.project.all({ orderBy: "id_desc", projectStatus: "active", deptId: this.$TOOL.data.get("USER_INFO").deptId });
			},

			async getSupplier() {
				this.suppliers = await this.$API.supplier.list.all();
			},

			// 表单注入数据
			async setData() {
				try {
					this.loading = true;
					const res = await this.$API.procurement.apply.detail({ id: this.id });
					this.loading = false;
					for (const key in this.apply) {
						if (key == "name") this.form.purchaseId = res.purchase.id;
						this.apply[key] = res.purchase[key] || null;
					}

					if (this.mode == "purchase_answer_sign") {
						this.bidSign.folders = res.bidSign.folders["purchase/bidsign"].entities.map(({ id, mineType, name, path }) => ({ id, mineType, name, path }))
						if (this.bidSign.folders.length) this.$emit("hasFolders")
					}
	
					if (res[this.handlerKey()].id) {
						this.loading = true;
						const { model } = await this.$API.procurement[this.handlerKey()].detail({ id: res[this.handlerKey()].id });
						this.loading = false;
	
						for (const key in this.form) {
							if (key == "folders") {
								if (model[key]) {
									this.form[key] = {
										[`purchase/${this.handlerKey("lowercase")}`]: {
											entities: model[key][`purchase/${this.handlerKey("lowercase")}`].entities.map(({ id, mineType, name, path }) => ({ id, mineType, name, path }))
										}
									}
								}
							} else if (key == "person") this.form[key] = { id: model.createId, nickName: model.createName };
							else if (key == "supplierId") this.form[key] = model.bidCompanyIds && model.bidCompanyIds.split(",") || [];
							else this.form[key] = model[key] || null;
						}
					}
				} catch (error) {
					this.loading = false;
				}
			},

			supplierChange(e) {
				this.form.bidCompanyIds = e && e.join() || null;
				this.form.bidCompanyName = e && e.map(id => {
					const { supplierName, contactName, contactPhone } = this.suppliers.find(s => s.id == id);
					return`${supplierName}(${contactName}:${contactPhone})`;
				}).join() || null;
			}
		}
	}
</script>

<style lang="scss" scoped>
.dialog-form {
  padding: 10px 30px 10px 10px;

  .input-number-suffix {
    position: absolute;
    right: 30px;
    color: #262626;
  }
}

.no-upload-btn {
  :deep(.el-form-item__label) {
    align-items: center;

    .tips__icon {
      cursor: pointer;
      margin: 0 2px;
      font-size: 16px;
      color: #8c8c8c;
    }
  }

  :deep(.sc-upload-file) {
    .el-upload {
      display: none;
    }

    .el-upload-list.is-disabled {
      margin-top: 0;
    }
  }
}

.dialog-form-disabled {
  padding-bottom: 20px;
}

@media (max-width: 992px) {
  .dialog-form {
    padding: 10px;
  }
}
</style>