<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="业务所属公司:">
					<tree-select v-model="apply.belongDeptId" :apiObj="$API.system.dept" isDept isAllDept disabled placeholder="自动带出"></tree-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="procurement_category" v-model="apply.type" dic="procurement_category" disabled placeholder="自动带出"></dict-select>
				</el-form-item>
			</el-col>
            <el-col v-if="apply.type && !isEngineering" :lg="lg" :md="12" :xs="24">
				<el-form-item label="专项费用类型:" prop="specialFeeType">
					<dict-select ref="special_expenses_type" v-model="apply.specialFeeType" dic="special_expenses_type" disabled placeholder="自动带出"></dict-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="创建人:" prop="createId">
					<el-input v-model="form.createName" disabled></el-input>
				</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>
            <!-- 金额 -->
			<template v-if="mode == 'purchase_matter'">
                <el-col :lg="lg" :md="12" :xs="24">
                    <el-form-item 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 label="金额大写:">
                        <el-input v-model="apply.budgetAmountDx" disabled placeholder="自动带出"></el-input>
                    </el-form-item>
                </el-col>
            </template>
			<el-col v-else :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 collapse-tags collapse-tags-tooltip 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>
            <el-col v-if="mode == 'purchase_bid_sign'" :lg="lg" :md="12" :xs="24">
                <el-form-item label="是否需要成本审批:">
                    <el-radio-group v-model="form.isCostApprovalRequired">
                        <el-radio label="是" value="1"></el-radio>
                        <el-radio label="否" value="0"></el-radio>
                    </el-radio-group>
                </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 v-if="mode == 'purchase_bid_sign' || mode == 'purchase_answer_sign'">
        <el-form v-loading="loading" :class="['dialog-form', !updateFolder && 'dialog-form-disabled']" :model="form" :rules="rules" label-width="140px">
            <el-row>
                <el-col :xs="24">
                    <el-form-item :class="!updateFolder && 'no-upload-btn'" label="初稿:">
                        <sc-upload-file v-model="form.folders[`${handlerKey('lowercase')}/first`].entities" :limit="10" :disabled="!updateFolder">
                            <el-button type="primary" icon="el-icon-upload" size="small"></el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
                <el-col :xs="24">
                    <el-form-item :class="!updateFolder && 'no-upload-btn'" label="终稿:">
                        <sc-upload-file v-model="form.folders[`${handlerKey('lowercase')}/final`].entities" :limit="10" :disabled="!updateFolder">
                            <el-button type="primary" icon="el-icon-upload" size="small"></el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
                <el-col v-if="mode == 'purchase_bid_sign'" :xs="24">
                    <el-form-item :class="!updateFolder && 'no-upload-btn'" label="扫描件:">
                        <sc-upload-file v-model="form.folders[`${handlerKey('lowercase')}/print`].entities" :limit="10" :disabled="!updateFolder">
                            <el-button type="primary" icon="el-icon-upload" size="small"></el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" v-if="isIframe && form.status == 'approve'">
                    <el-form-item class="iframe-item__btn" label-width="0">
                        <template v-if="updateFolder">
                            <el-button @click="updateFolder = !updateFolder">取 消</el-button>
                            <el-button type="primary" :loading="isSaveing" @click="updateFile">确 定</el-button>
                        </template>
                        <template v-else>
                            <el-button type="primary" @click="updateFolder = !updateFolder">编 辑</el-button>
                        </template>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </template>
</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,
                isSaveing: false,
                updateFolder: !this.disabled,
				stepDic,
				projects: [],
				suppliers: [],

				apply: {
					name: null,
					deptId: null,
					belongDeptId: null,
					type: null,
                    specialFeeType: null,
					purchaseType: null,
					budgetAmount: null,
                    budgetAmountDx: null,
					projectId: null
				},
				bidSign: {
					folders: []
				},
				form: {
					id: null,
					approveTitle: null,
					purchaseId: null,
					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,
                    status: 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: "请选择招标代理" }]
				}
			}
		},

        computed: {
			isEngineering() {
				return this.formatType(this.apply.type) == "工程类";
            }
        },

		created() {
			this.form[`${this.handlerKey("suffix")}Name`] = null;
			this.form.folders = {
				[`purchase/${this.handlerKey("lowercase")}`]: {
					entities: []
				}
			}
            
            if (this.mode == "purchase_bid_sign" || this.mode == "purchase_answer_sign") {
                this.form.folders[`${this.handlerKey("lowercase")}/first`] = {
					entities: []
				}
                this.form.folders[`${this.handlerKey("lowercase")}/final`] = {
					entities: []
				}
            }

            if (this.mode == "purchase_bid_sign") {
                this.form.folders[`${this.handlerKey("lowercase")}/print`] = {
					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("");
			},

            formatType(value, refName = "procurement_category") {
				const dicts = this.$refs[refName] && this.$refs[refName].options || [];
				return dicts && dicts.find(d => d.value == value) && dicts.find(d => d.value == value).label || "";
			},

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

			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_bid_sign") this.form["isCostApprovalRequired"] = res.purchase.isCostApprovalRequired;

					if (this.mode == "purchase_answer_sign") {
                        let fileList = [];
                        for (const key in res.bidSign.folders) {
                            fileList = fileList.concat(res.bidSign.folders[key].entities.map(({ id, mineType, name, path }) => ({ id, mineType, name, path })));
                        }
						this.bidSign.folders = fileList.slice();
                        
						if (fileList.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]) {
                                    for (const folder_key in this.form[key]) {
                                        this.form[key][folder_key]["entities"] = model[key][folder_key].entities.map(({ id, mineType, name, path }) => ({ id, mineType, name, path })) || []
                                    }
								}
							} else if (key == "supplierId") this.form[key] = model.bidCompanyIds && model.bidCompanyIds.split(",") || [];
							else this.form[key] = model[key] || null;
						}

					    if (this.mode == "purchase_bid_sign") this.form["isCostApprovalRequired"] = model.isCostApprovalRequired;
					}
				} catch (error) {
					this.loading = false;
				}
			},

			supplierChange(e) {
				this.form.bidCompanyIds = e && e.join() || null;
				this.form.bidCompanyName = e && e.map(id => this.suppliers.find(s => s.id == id) && this.suppliers.find(s => s.id == id).supplierName || null).join() || null;
			},

            updateFile() {
                const data = {};
				for (const key in this.form) {
					if (key == "folders") {
                        for (const folder_key in this.form[key]) {
                            const newFiles = this.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.form[key];
				}

                this.isSaveing = true;
				this.$API.procurement[[this.handlerKey()]].updateFile(data).then(() => {
					this.isSaveing = false;
					this.$message.success("操作成功");
					this.updateFolder = !this.updateFolder;
                    this.setData();
				}).catch(() => this.isSaveing = false);
            }
		}
	}
</script>

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

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

  .iframe-item__btn :deep(.el-form-item__content) {
    justify-content: flex-end;
  }
}

.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 + .dialog-form {
  padding-top: 0;
  padding-bottom: 10px;
}

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

@media (max-width: 992px) {
  .dialog-form {
    padding: 10px 10px 0;
  }

  .dialog-form + .dialog-form {
    padding-top: 0;
    padding-bottom: 10px;
  }
}
</style>