<!-- 通用弹窗表单 -->
<template>
	<div>
		<Modal
			v-model="modal"
			:width="width"
			:mask-closable="false"
			@on-cancel="cancel"
			class-name="vertical-center-modal"
		>
			<div class="title" slot="header">
				{{ title }}
			</div>
			<div slot="footer" class="footer" v-if="type !== 'form'">
				<Button @click="cfm" class="btn" type="primary">提交</Button>
				<Button @click="cancel" class="btn">取消</Button>
			</div>
			<div slot="footer" class="footer" v-else>
				<Button @click="cancel" class="btn" type="primary">关闭</Button>
			</div>
			<div class="content">
				<Form ref="form" :model="formData" :rules="ruleValidate">
					<Col
						:span="item.span || '24'"
						v-for="(item, index) in config"
						:key="index"
					>
						<FormItem
							:prop="item.key"
							:label="item.label + '：'"
							:label-width="item.hiddenLabel ? 0 : 100"
						>
							<!-- 自定义标签 -->
							<div slot="label">
								{{ item.hiddenLabel ? '' : item.label + '：' }}
							</div>
							<!-- 输入框 -->
							<Input
								v-if="item.type === 'input'"
								v-model="formData[item.key]"
								:placeholder="item.placeholder"
								:type="item.comType"
								:disabled="item.disabled"
							/>
							<!-- 日期选择 -->
							<DatePicker
								v-if="item.type === 'date'"
								v-model="formData[item.key]"
								@on-change="handleDateChange(item.key)"
								:transfer="true"
								:type="item.comType"
								format="yyyy-MM-dd HH:mm:ss"
								:placeholder="item.placeholder"
								style="width: 100%"
							>
							</DatePicker>
							<!-- 下拉框 -->
							<Select
								v-if="item.type === 'select'"
								:transfer="true"
								v-model="formData[item.key]"
								style="max-width: 400px"
								:disabled="item.disabled"
							>
								<Option
									v-for="option in item.list"
									:value="option.value"
									:key="option.value"
									>{{ option.label || '未知' }}</Option
								>
							</Select>
							<!-- 树下拉框 -->
							<my-tree-select
								ref="myTreeSelect"
								v-if="item.type === 'treeSelect'"
								v-model="formData[item.key]"
								:treeData="item.list"
							></my-tree-select>
							<!-- 搜索下拉框 -->
							<Select
								v-if="item.type === 'selectSearch'"
								filterable
								:transfer="true"
								v-model="formData[item.key]"
								style="max-width: 400px"
								:disabled="item.disabled"
							>
								<Option
									v-for="option in item.list"
									:value="option.value"
									:key="option.value"
									>{{ option.label || '未知' }}</Option
								>
							</Select>
							<!-- 单选框 -->
							<RadioGroup
								v-if="item.type === 'radio'"
								v-model="formData[item.key]"
							>
								<Radio
									:label="radio.value"
									v-for="radio in item.list"
									:key="radio.value"
								>
									<span>{{ radio.label }}</span>
								</Radio>
							</RadioGroup>

							<!-- 图片上传 -->
							<div
								class="upload-input"
								v-if="item.type === 'upload' && !item.disabled"
							>
								<Input v-model="formData[item.key]" />
								<Upload
									ref="upload"
									:before-upload="uploadOther"
									:format="['jpg', 'jpeg', 'png']"
									accept=".jpg,.png,.jpeg"
									action=""
									style="display: flex; align-items: center"
								>
									<Button
										type="primary"
										style="
											width: 120px;
											height: 32px;
											border-radius: 0 4px 4px 0;
										"
										>{{ item.text }}</Button
									>
								</Upload>
							</div>
							<div
								class="upload-flie"
								v-if="item.type === 'upload-flie'"
							>
								<Upload
									v-if="type != 'form'"
									ref="upload-flie"
									:before-upload="
										(flie) => upload(flie, item)
									"
									:format="['jpg', 'jpeg', 'png']"
									accept=".jpg,.png,.jpeg"
									action=""
									style="float:left"
								>
									<Tooltip :content="item.text">
										<Button type="primary">上传图片</Button>
									</Tooltip>
								</Upload>
								<span style="margin-left: 10px"> 
									<img 
										:src="formData[item.key]" 
										@click="imgMddalUrl = formData[item.key]; imgMddalType = true;" 
										style="height:50px;cursor: pointer;" alt="">
								</span>
							</div>
							<div
								class="upload-app"
								v-if="item.type === 'upload-app'"
							>
								<Upload
									v-if="type != 'form'"
									ref="upload-flie"
									:before-upload="
										(flie) => uploadApk(flie, item)
									"
									action=""
									style="float:left"
								>
									<Button type="primary">上传apk</Button>
								</Upload>
								<p>{{formData[item.key]}}</p>
							</div>
							<Input
								v-if="item.type === 'upload' && item.disabled"
								v-model="formData[item.key]"
								disabled
							/>
							<!-- 选择物料特殊按钮 -->
							<Button
								type="primary"
								v-if="item.type === 'materialBtn'"
								@click="materialHandle(item)"
								>+&nbsp;&nbsp;选择物料&nbsp;</Button
							>
							<div
								v-if="item.type === 'materialBtn'"
								class="material-list"
								style="
									border: 1px solid #dcdee2;
									border-radius: 4px;
									padding: 0 10px;
									margin-top: 10px;
								"
							>
								<div
									v-if="codeListShow"
									class="material-item"
									v-for="(
										code, codeIndex
									) in formData.materialNames"
									:key="codeIndex"
								>
									{{ code }}
									<Icon
										type="md-close"
										class="icon"
										@click="removeCode(codeIndex)"
									/>
								</div>
							</div>
							<my-modal-material
								v-if="item.type === 'materialBtn'"
								:selected-list="selectedList"
								ref="materialModal"
								:multiple="item.multiple"
								v-model="show"
								@getselectedList="getselectedList"
							></my-modal-material>
							<!-- 选项卡 -->
							<div v-if="item.type === 'tabs'">
								<Tabs :value="tabName">
									<TabPane
										v-for="(tab, tabIndex) in item.tabs"
										:key="tabIndex"
										:label="tab.title"
										:name="tabIndex + ''"
									>
										<!-- 选项卡普通表单内容 -->
										<Col
											v-if="!tab.type"
											:span="tabItem.span || '24'"
											v-for="(
												tabItem, tabItemIndex
											) in tab.forms"
											:key="tabItemIndex"
										>
											<FormItem
												:prop="tabItem.key"
												:label="tabItem.label + '：'"
												:label-width="
													tabItem.hiddenLabel
														? 0
														: 100
												"
												label-position="left"
											>
												<!-- 自定义标签 -->
												<div slot="label">
													{{
														tabItem.hiddenLabel
															? ''
															: tabItem.label +
															  ':'
													}}
												</div>
												<!-- 输入框 -->
												<Input
													v-if="
														tabItem.type === 'input'
													"
													v-model="
														formData[tabItem.key]
													"
													:placeholder="
														tabItem.placeholder
													"
													:type="tabItem.comType"
													:disabled="tabItem.disabled"
													style="
														width: calc(
															100% - 100px
														);
													"
												/>
												<!-- 日期选择 -->
												<DatePicker
													v-if="
														tabItem.type === 'date'
													"
													v-model="formData[item.key]"
													:transfer="true"
													:disabled="tabItem.disabled"
													:type="tabItem.comType"
													:placeholder="
														tabItem.placeholder
													"
													style="
														width: calc(
															100% - 100px
														);
													"
												>
												</DatePicker>
											</FormItem>
										</Col>
										<!-- 维护记录 -->
										<Col
											span="24"
											v-if="tab.type === 'picList'"
											style="
												position: relative;
												height: 100%;
											"
										>
											<div
												style="
													text-align: right;
													width: 100%;
													margin-bottom: 10px;
												"
											>
												<Button
													type="primary"
													@click="historyShow = true"
													>添加</Button
												>
												<my-history-form
													v-model="historyShow"
													@getData="historyAdd"
												></my-history-form>
											</div>
											<Table
												:columns="piclistColumns"
												:data="
													formData.facKeepRecordList
												"
											></Table>
										</Col>
										<!-- 其他资质 -->
										<Col
											span="24"
											v-if="tab.type === 'quaList'"
											style="
												position: relative;
												height: 100%;
											"
										>
											<Table
												:columns="quaColumns"
												:data="formData.attr"
											></Table>
											<div
												style="
													text-align: center;
													width: 60px;
													margin: 10px auto 0;
												"
											>
												<div class="upload-flie">
													<Upload
														ref="upload-flie"
														:before-upload="
															(flie) =>
																upload(
																	flie,
																	item,
																	'attr'
																)
														"
														:format="[
															'jpg',
															'jpeg',
															'png',
														]"
														accept=".jpg,.png,.jpeg"
														action=""
													>
														<Button type="primary"
															>新增证书</Button
														>
													</Upload>
												</div>
											</div>
										</Col>
										<Modal
											v-model="showImgUrlModal"
											title="查看"
										>
											<div style="text-align: center">
												<img :src="showImgUrl" alt="" />
											</div>
										</Modal>

										<!-- 主营价格 -->
										<Col
											span="24"
											v-if="tab.type === 'material'"
										>
											<material-table
												:id="formData.id"
											></material-table>
										</Col>
										<!-- 采购分析 -->
										<Col
											span="24"
											v-if="tab.type === 'charts'"
										>
											<charts
												:show="modal"
												:id="formData.id"
											></charts>
										</Col>
									</TabPane>
								</Tabs>
							</div>
							<div v-if="item.type === ''" style="cursor: auto">
								<Input
									style="opacity: 0; cursor: auto"
									disabled
								/>
							</div>
						</FormItem>
					</Col>
				</Form>
			</div>
			<Modal
				v-model="imgMddalType"
				title="图片查看"
				>
				<div>
					<img style="max-width:100%" :src="imgMddalUrl" alt="" />
				</div>
			</Modal>
		</Modal>
	</div>
</template>

<script>
import MyHistoryForm from './my-history-form'
import MyModalMaterial from './my-modal-material'
import { UploadBusinessLicense } from '@/api/upload'
import MyTable from '_c/my-table/my-table'
import MaterialTable from './material-table'
import Charts from './charts'
import MyTreeSelect from '_c/my-tree-select/my-tree-select'
import { UploadBase64 } from '@/api/upload'
import axios from 'axios'
export default {
	components: {
		MyTable,
		MyModalMaterial,
		MaterialTable,
		Charts,
		MyHistoryForm,
		MyTreeSelect,
	},
	props: {
		// 标题
		title: {
			type: String,
			default: '',
		},
		// 修改表单时的数据
		data: {
			type: Object,
			default() {
				return {}
			},
		},
		// 表单类型 add新增 edit修改 form查看
		type: {
			type: String,
			default: 'add',
		},
		// 表单校验格式
		ruleValidate: {
			type: Object,
			default() {
				return {}
			},
		},
		// 表单显示格式
		config: {
			type: Array,
			default() {
				return []
			},
		},
		// 是否显示表单
		value: {
			type: Boolean,
			default: false,
			require: true,
		},
		width: {
			type: String,
			default: '500px',
		},
	},
	watch: {
		isMaterial() {
			console.log('isMaterial', this.isMaterial)
		},
		value: {
			handler(n) {
				this.modal = n
				// 表单数组绑定问题
				if (n) {
					this.tabName = '0'
					setTimeout(() => {
						this.isFirst = false
					}, 100)
					if (this.data.categoryCode) {
						if(this.$refs.myTreeSelect && this.$refs.myTreeSelect[0]){
							this.$refs.myTreeSelect[0].init(this.data.categoryCode)
						}
						
					}
				} else {
					this.isFirst = true
					this.tabName = 0
				}
			},
			immediate: true,
		},
		modal(n) {
			this.$emit('input', n)
		},
	},
	data() {
		const v = this
		return {
			imgMddalType:false,
			imgMddalUrl:"",
			selectedList: [],
			tabName: '0',
			isFirst: true,
			codeListShow: true,
			historyShow: false,
			show: false,
			modal: false,
			formData: {
				materialCodeList: [],
				facKeepRecordList: [],
			},
			showImgUrl: null,
			showImgUrlModal: false,
			quaColumns: [
				{
					title: '序号',
					type: 'index',
					width: 60,
					align: 'center',
				},
				{
					title: '资质类型',
					align: 'center',
					key: 'realName',
				},
				{
					title: '操作',
					align: 'center',
					key: 'title',
					render(h, p) {
						return h('div', [
							h(
								'Button',
								{
									props: {
										type: 'primary',
										size: 'small',
									},
									style: {
										marginRight: '5px',
									},
									on: {
										click: () => {
											v.showImgUrl = p.row.path
											v.showImgUrlModal = true
										},
									},
								},
								'查看'
							),
							// h(
							// 	'Upload',
							// 	{
							// 		props: {
							// 			type: 'primary',
							// 			size: 'small',
							// 		},
							// 		style: {
							// 			marginRight: '5px',
							// 		},
							// 		on: {
							// 			click: () => {
							// 				this.show(params.index)
							// 			},
							// 		},
							// 	},
							// 	'修改'
							// ),
							h(
								'Button',
								{
									props: {
										type: 'error',
										size: 'small',
									},
									style: {
										marginRight: '5px',
									},
									on: {
										click: () => {
											v.formData.attr.splice(p.index, 1)
										},
									},
								},
								'删除'
							),
						])
					},
				},
			],
			piclistColumns: [
				{
					title: '序号',
					type: 'index',
					width: 60,
					align: 'center',
				},
				{
					title: '维护记录',
					align: 'center',
					key: 'title',
				},
				{
					title: '日期',
					align: 'center',
					key: 'createdTime',
				},
				{
					title: '附件',
					key: 'picUrl',
					tooltip: true,
					minWidth: 200,
					align: 'center',
					render: (h, params) => {
						let list = params.row.picUrl.split(',')
						let showList = []
						list.forEach((item) => {
							showList.push(
								h(
									'div',
									{
										style: {
											color: 'blue',
											overflow: 'hidden',
											whiteSpace: 'nowrap',
											textOverflow: 'ellipsis',
											lineClamp: '2',
											cursor: 'pointer',
										},
										on: {
											click() {
												let newWindow = window.open()
												newWindow.document.write(
													"<br><div style='padding: 0'><img width='" +
														100 +
														'%' +
														"' src='" +
														item +
														"'/></div>"
												)
												newWindow.document.close()
											},
										},
									},
									item
								)
							)
						})
						return h('div', showList)
					},
				},
			],
		}
	},
	methods: {
		//上传app文件
		uploadApk(file, item, type){
			//const reader = new FileReader()
			const formData = new FormData();
			formData.append("file",file);
			console.log(formData)
			axios.post('/cloudApi/applet/uploadFile',formData,{
                'Content-type' : 'multipart/form-data'
            }).then(res => {
				console.log(res.data.msg)
				this.$set(this.formData, item.key, res.data.msg)
			})
			// reader.readAsDataURL(file)
			// reader.onload = (event) => {
			// 	console.log(file)
			// 	// UploadBase64({
			// 	// 	fileBase64: event.srcElement.result,
			// 	// 	fileName: file.name,
			// 	// 	floder: 'order',
			// 	// }).then((res) => {
			// 	// 	if (res.code === 0) {
			// 	// 		this.$set(this.formData, item.key, res.result)
			// 	// 	}
			// 	// })
			// }
		},
		// 图片上传
		
		upload(file, item, type) {
			const reader = new FileReader()
			reader.readAsDataURL(file)
			reader.onload = (event) => {
				UploadBase64({
					fileBase64: event.srcElement.result,
					fileName: file.name,
					floder: 'order',
				}).then((res) => {
					if (res.code === 0) {
						console.log(this.formData)
						if (type == 'attr') {
							if (!this.formData.attr) {
								this.$set(this.formData, 'attr', [])
							}
							this.formData.attr.push({
								realName: file.name,
								temName: file.name,
								path: res.result,
							})
						}else{
							this.$set(this.formData, item.key, res.result)
						}
					}
				})
			}
			return false
		},
		// 维护记录新增数据
		historyAdd(data) {
			if (!this.formData.facKeepRecordList) {
				this.$set(this.formData, 'facKeepRecordList', [])
			}
			this.formData.facKeepRecordList.push({ ...data })
		},
		// 时间控件选择
		handleDateChange(key) {
			this.formData[key] = this.$dayjs(this.formData[key]).format(
				'YYYY-MM-DD hh:mm:ss'
			)
		},
		// 上传运营执照 自动获取相关信息并回填
		uploadOther(file) {
			const reader = new FileReader()
			reader.readAsDataURL(file)
			reader.onload = (event) => {
				UploadBusinessLicense({
					base64str: event.srcElement.result,
				}).then((res) => {
					if (res.code === 0) {
						this.formData = { ...this.formData }
						this.$set(this.formData, 'name', res.result.name)
						this.$set(
							this.formData,
							'legalPerson',
							res.result.legalPerson
						)
						this.$set(
							this.formData,
							'societyCreditCode',
							res.result.societyCreditCode
						)
						this.$set(
							this.formData,
							'registeredAddress',
							res.result.registeredAddress
						)
						this.$set(
							this.formData,
							'establishDate',
							res.result.establishDate
								.replace('年', '-')
								.replace('月', '-')
								.replace('日', '')
						)
						this.$set(
							this.formData,
							'enterpriseType',
							res.result.enterpriseType
						)
						this.$set(
							this.formData,
							'businessScope',
							res.result.businessScope
						)
						this.$set(
							this.formData,
							'registeredCapital',
							res.result.registeredCapital
						)
						this.$set(
							this.formData,
							'businessTerm',
							res.result.businessTerm
								.replace('年', '-')
								.replace('月', '-')
								.replace('日', '')
						)
					}
				})
			}
			return false
		},
		// 选择物料
		materialHandle(item) {
			this.selectedList = this.formData.materialCodeList.map(
				(item, index) => {
					return {
						code: item,
						name: this.formData.materialNames[index],
					}
				}
			)
			this.show = true
		},
		// 获从面料组件获取取选中面料
		getselectedList(list, multiple) {
			if (multiple) {
				for (const key in list[0]) {
					this.formData[key] = list[0][key]
				}
			} else {
				this.formData.materialCodeList = list.map((item) => item.code)
				this.formData.materialNames = list.map((item) => item.name)
			}
		},
		removeCode(index) {
			console.log(index)
			this.formData.materialCodeList.splice(index, 1)
			this.formData.materialNames.splice(index, 1)
			this.codeListShow = false
			setTimeout(() => {
				this.codeListShow = true
			})
		},
		cancel() {
			this.modal = false
			this.formData = {
				materialCodeList: [],
				facKeepRecordList: [],
			}
			this.$refs.form.resetFields()
		},
		cfm() {
			this.$refs.form.validate((valid) => {
				if (valid) {
					if (this.type === 'edit') {
						this.$emit('confirm', 'edit', { ...this.formData })
						// this.formData = {}
						// this.$refs.form.resetFields()
					} else {
						this.$emit('confirm', 'add', { ...this.formData })
						// this.formData = {}
						// this.$refs.form.resetFields()
					}
				}
			})
		},
	},
	mounted() {
		// 不加第一次进来数据会绑定失败 修改的时候会校验失败
		this.formData = {}
		
	},
	beforeUpdate() {
		
		if (!this.modal) {
			this.cancel()
		}
		// this.$set(this, 'formData', this.data)
		// 防止input type为number时绑定数据 校验失败
		if (this.isFirst) {
			if (this.modal && (this.type === 'edit' || this.type === 'form')) {
				for (const key in this.data) {
					if (
						Number.parseFloat(this.data[key]) === 'NaN' ||
						typeof this.data[key] === 'object'
					) {
						this.formData[key] = this.data[key]
					} else if (key === 'sex') {
						this.$set(this.formData, 'sex', this.data.sexCode)
					} else if (this.data[key] || this.data[key] === 0) {
						this.formData[key] = this.data[key].toString()
					}
				}
			}
		}
	},
}
</script>

<style lang="less" scoped>
.upload-flie {
	height: 70px;
}
/deep/ .upload-flie .ivu-upload {
	height: 50px;
	width: 100px;
}
.content {
	.material-list {
		max-height: 300px;
		overflow: auto;
		.material-item {
			position: relative;
			.icon {
				position: absolute;
				right: 5px;
				top: 50%;
				transform: translateY(-50%);
				cursor: pointer;
			}
		}
	}
	.col {
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		.label {
			width: 100px;
			text-align: right;
		}
	}
}
.upload-input {
	display: flex;
	align-items: center;
	/deep/.ivu-upload {
		display: flex;
		align-items: center;
	}
	/deep/.ivu-input {
		flex: 1;
		border-radius: 4px 0 0 4px;
	}
}
/deep/ .vertical-center-modal {
	display: flex;
	align-items: center;
	justify-content: center;
	.ivu-modal {
		top: 0;
	}
}
///deep/ .ivu-modal-content {
//  height: 80vh;
//  overflow: hidden;
//}
/deep/ .ivu-modal-body {
	max-height: ~'calc(80vh - 68px)';
	overflow: auto;
	background: #f5f7fa;
}
/deep/ .ivu-form-item {
	.ivu-form-item {
		margin-bottom: 24px;
	}
}
/deep/ .ivu-form-item-label {
	display: flex;
	justify-content: flex-end;
}
/deep/ .ivu-tabs {
	background-color: #f2f2f2;
	padding: 10px;
}
/deep/ .ivu-upload-select {
	width: 100%;
}
/deep/ .ivu-tabs-tabpane {
	max-height: 310px;
	overflow-y: auto;
}
</style>
