<template>
	<el-container class="aminui-main-container">
		<el-header class="aminui-main-container__query-header">
			<div class="left-panel">
				<el-button text icon="el-icon-arrow-left" @click="$emit('closed')">返回</el-button>
				<scTitle>供应商信息</scTitle>
			</div>
		</el-header>

		<el-main>
			<el-scrollbar>
				<el-form :class="mode == 'detail' && 'dialog-form-disabled'" ref="dialogForm" :model="form" :rules="rules" :disabled="mode == 'detail'" label-width="140px">
					<scTitle>基本信息</scTitle>
					<el-row :gutter="15">
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="企业编码:">
								<el-input v-model="form.supplierNo" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="供方名称:" prop="supplierName">
								<el-input v-model="form.supplierName" placeholder="请输入供应商名称"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="所属组织:">
								<tree-select ref="deptTreeSelect" v-model="form.deptId" :apiObj="$API.system.dept" isDept check-strictly clearable placeholder="请选择所属组织"></tree-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="成立日期:">
								<el-date-picker v-model="form.establishDate" value-format="YYYY-MM-DD" placeholder="请选择成立日期"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="统一社会信用代码:" prop="creditCode">
								<el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="营业执照有效期:">
								<el-date-picker v-model="form.licenceDate" value-format="YYYY-MM-DD" placeholder="请选择营业执照有效期"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="注册资金:">
								<el-input-number v-model="form.registerAmount" :precision="2" :step="0.1" :controls="false" clearable placeholder="请输入注册资金"></el-input-number>
								<span class="input-number-suffix">万元</span>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="服务类别:">
								<tree-select v-model="form.supplierTypeId" :apiObj="$API.supplier.type" check-strictly clearable placeholder="请选择服务类别"></tree-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="合作单位类别:">
								<dict-select v-model="form.companyType" dic="company_type" filterable placeholder="请选择合作单位类别"></dict-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="主要联系人:">
								<el-input v-model="form.contactName" placeholder="请输入主要联系人"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="联系电话:">
								<el-input v-model="form.contactPhone" placeholder="请输入联系电话"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="身份证号:">
								<el-input v-model="form.contactIdCard" clearable placeholder="请输入身份证号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="省市区:" prop="province">
								<el-select v-model="form.province" filterable clearable placeholder="选择省市区" @change="changeProvince">
									<el-option v-for="(item, index) in province" :key="index" :label="item.name" :value="item.name"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="地级市:" prop="city">
								<el-select v-model="form.city" filterable clearable placeholder="选择地级市" @change="changeCity">
									<el-option v-for="(item, index) in city" :key="index" :label="item.name" :value="item.name"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="区/县:">
								<el-select v-model="form.region" filterable clearable placeholder="选择区县">
									<el-option v-for="(item, index) in region" :key="index" :label="item.name" :value="item.name"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="邮政编码:">
								<el-input v-model="form.postcode" clearable placeholder="请输入邮政编码"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="公司电话:">
								<el-input v-model="form.telephone" clearable placeholder="请输入公司电话"></el-input>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="单位性质:" prop="nature">
								<dict-select v-model="form.nature" dic="unit_nature" filterable placeholder="请选择单位性质"></dict-select>
							</el-form-item>
						</el-col>
						<el-col :lg="8" :md="12" :xs="24">
							<el-form-item label="是否客户:" required>
								<el-radio-group v-model="form.isCustomer">
									<el-radio label="是" :value="true"></el-radio>
									<el-radio label="否" :value="false"></el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24">
							<el-form-item label="经营范围:">
								<el-input v-model="form.businessScope" clearable placeholder="请输入经营范围"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24">
							<el-form-item label="公司地址:">
								<el-input v-model="form.address" clearable placeholder="请输入公司地址"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24">
							<el-form-item label="备注:">
								<el-input v-model="form.remark" type="textarea" :rows="4" clearable placeholder="请输入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<scTitle>银行账户</scTitle>
					<el-row :gutter="15">
						<el-col :xs="24">
							<el-form-item prop="bankList" label-width="60px">
								<sc-form-table ref="formTable" v-model="form.bankList" :hideAdd="mode == 'detail'" :hideDelete="mode == 'detail'" @rowAdd="table_add">
									<el-table-column label="省名称" prop="provInputName" width="120" align="center"></el-table-column>
									<el-table-column label="市名称" prop="name" width="120" align="center"></el-table-column>
									<el-table-column label="联行号" prop="sysBankCode" min-width="130" align="center"></el-table-column>
									<el-table-column label="开户行名称" prop="bankName" min-width="180" align="center" show-overflow-tooltip></el-table-column>
									<el-table-column label="开户行全称" prop="bankName2" min-width="180" align="center" show-overflow-tooltip></el-table-column>
									<el-table-column label="开户名称" prop="accountName" min-width="180">
										<template #default="scope">
											<el-input v-model="scope.row.accountName" placeholder="开户名称"></el-input>
										</template>
									</el-table-column>
									<el-table-column label="银行账号" prop="accountCode" min-width="180">
										<template #default="scope">
											<el-input v-model="scope.row.accountCode" placeholder="银行账号"></el-input>
										</template>
									</el-table-column>
                                    <el-table-column label="账户属性" prop="accountNature" min-width="180">
										<template #default="scope">
                                            <dict-select v-model="scope.row.accountNature" dic="account_nature" filterable placeholder="账户属性"></dict-select>
										</template>
									</el-table-column>
								</sc-form-table>
							</el-form-item>
						</el-col>
					</el-row>

					<el-header>
						<div class="left-panel"><scTitle>资质附件</scTitle></div>
						<div class="right-panel">
							<el-icon><el-icon-warning /></el-icon>可上传CAD图纸、三维模型、视频、word/pdf/ppt/excel文件
						</div>
					</el-header>
					<el-row :gutter="15">
						<el-col :xs="24">
							<el-form-item label-width="60px">
								<sc-upload-file v-model="form.folders['supplier/attach'].entities">
									<el-button size="large" text icon="el-icon-upload">上传附件</el-button>
								</sc-upload-file>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-scrollbar>
		</el-main>

		<el-footer v-if="mode == 'add' || mode == 'edit'">
			<el-button @click="$emit('closed')">取消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">保存</el-button>
		</el-footer>
	</el-container>

	<bank-dialog v-if="dialog" ref="bankDialog" :selected="form.bankList" @success="bank_add" @closed="dialog = false"></bank-dialog>
</template>

<script>
	import { province } from "@/utils/district";
	import bankDialog from "./bank";

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

		data(){
			return {
				mode: "add",
				isSaveing: false,
				province,

				form: {
					id: null,
					supplierNo: null,
					supplierName: null,
					deptId: null,
					deptCode: null,
					establishDate: null,
					creditCode: null,
					licenceDate: null,
					registerAmount: null,
					supplierTypeId: null,
					companyType: null,
					contactName: null,
					contactPhone: null,
					contactIdCard: null,
					province: null,
					provinceCode: null,
					city: null,
					cityCode: null,
					region: null,
					regionCode: null,
					postcode: null,
					telephone: null,
					nature: null,
					isCustomer: false,
					businessScope: null,
					address: null,
					remark: null,
					bankList: [],
					folders: {
						"supplier/attach": {
							entities: []
						}
					}
				},

				rules: {
					supplierName: [{ required: true, message: "请输入供应商名称" }],
					creditCode: [{ required: true, message: "请输入统一社会信用代码" },
						{ validator: (rule, value, callback) => {
							if (value.length != 18) return callback(new Error("请输入18位统一社会信用代码"));
							callback();
						}}
					],
					supplierTypeId: [{ required: true, message: "请选择服务类别" }],
					province: [{ required: true, message: "请选择省市区" }],
					city: [{ required: true, message: "请选择地级市" }],
					nature: [{ required: true, message: "请选择单位性质" }],
					bankList: [{ required: true, message: "请选择银行账户" },
						{ validator: (rule, value, callback) => {
							if (value.findIndex(v => !v.accountName || !v.accountCode || !v.accountNature) != -1) return callback(new Error("请完善银行账户信息"));
							callback();
						}}
					]
				},

				dialog: false
			}
		},

		computed: {
			depts() {
				return this.$refs.deptTreeSelect && this.$refs.deptTreeSelect.treeList || [];
			},

			city() {
				if (this.form.province && this.province.length) return this.province.find(p => p.name == this.form.province).districtList;
				return [];
			},

			region() {
				if (this.form.city && this.city.length) return this.city.find(p => p.name == this.form.city).districtList;
				return [];
			}
		},
		
		methods: {
			formatDeptCode() {
				return this.depts && this.depts.find(d => d.deptId == this.form.deptId) && this.depts.find(d => d.deptId == this.form.deptId).code || "";
			},

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

			// 表单注入数据
			async setData({ id }) {
				const { supplier, bankList } = await this.$API.supplier.list.detail({ id });

				for (const key in this.form) {
					if (key == "folders") {
						if (supplier[key]) {
							this.form[key] = {
								"supplier/attach": {
									entities: supplier[key]["supplier/attach"].entities.map(({ id, mineType, name, path }) => ({ id, mineType, name, path }))
								}
							}
						}
					} else if (key == "bankList") this.form[key] = bankList.map(b => ({ ...b, id: b.bankId }));
					else this.form[key] = supplier[key];
				}
			},

			changeProvince() {
				this.form.city = null;
				this.form.region = null;
			},

			changeCity() {
				this.form.region = null;
			},

			table_add() {
				this.dialog = true;
				this.$nextTick(() => this.$refs.bankDialog.open());
			},

			bank_add(selected) {
				const newBankList = selected.map(s => ({ ...s, bankId: s.id, supplierId: null, accountName: this.form.supplierName }));
				this.form.bankList = this.form.bankList.concat(newBankList);
			},

			submit() {
				this.$refs.dialogForm.validate(valid => {
					if (valid) {
						const data = {};
						for (const key in this.form) {
							if (key == "folders") {
								const newFiles = this.form[key]["supplier/attach"].entities.filter(item => !item.id).map(item => item.path);
								if (newFiles.length) {
									data[key] = {
										"supplier/attach": {
											entities: newFiles.map(ticket => ({ features: { ticket } }))
										}
									};
								}
							} else if (key == "provinceCode" || key == "cityCode" || key == "regionCode") data[key] = this[key.split("Code")[0]].find(d => d.name == this.form[key.split("Code")[0]]) && this[key.split("Code")[0]].find(d => d.name == this.form[key.split("Code")[0]]).adcode || null;
							else if (key == "deptCode") data[key] = this.formatDeptCode();
							else data[key] = this.form[key];
						}
						
						this.isSaveing = true;
						this.$API.supplier.list[this.mode](data).then(() => {
							this.isSaveing = false;
							this.$message.success("操作成功");
							this.$emit("closed");
							this.$nextTick(() => this.$emit("success", this.mode));
						}).catch(() => this.isSaveing = false);
					} else {
						return false;
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.aminui-main-container {
  .aminui-main-container__query-header {
    flex-direction: column;
    margin-bottom: 0;
    padding-top: 15px;

    .left-panel {
      padding-bottom: 15px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .sc-title {
      flex-basis: 100%;
      padding-left: 8px;

      &::before {
        display: none;
      }
    }
  }

  .el-main {
    padding-right: 0;
    background: #fff;

    .sc-title {
      margin-bottom: 15px;
      margin-left: 15px;
      font-size: 14px;
    }

    .el-form {
      margin-top: 15px;
      padding-right: 60px;

      .el-header {
        padding: 0;
        border-bottom: none;

        .sc-title {
          margin-bottom: 0;
        }

        .right-panel {
          font-size: 14px;
          color: #8c8c8c;

          .el-icon {
            margin-right: 4px;
            font-size: 16px;
          }
        }
      }

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

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

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

  .el-footer {
    display: flex;
    justify-content: right;
  }
}

@media (max-width: 992px) {
  .aminui-main-container {
    .el-main {
      padding-right: 15px;

      .sc-title {
        margin-left: 0;
      }

      .el-form {
        padding-right: unset;

        .el-row {
          margin: 0 !important;
        }
      }
    }
  }
}
</style>