<template>
	<div class="my-container">
		<div class="bill-main" v-show="isShow==='ckb'" key="item">
			<module-view :propConfig="config" ref="moduleView" @pagination="getDataList" @search="getDataList"
				@resert="getDataList" @detail="openEdit" @onRefresh="onRefresh">
			</module-view>
			<!-- 注册/编辑弹窗 -->
			<el-dialog :title="popTitle+'仓库'" :visible.sync="dialogFormVisible" width="960px" height="450px">
				<!-- <by-form :propConfig="addConfig" ref="addFormId"></by-form> -->
				<ruleForm ref='addFormId' @toCargoOwner="toCargoOwner"></ruleForm>
				<div slot="footer" class="dialog-footer">
					<el-button @click="close">取 消</el-button>
					<el-button type="primary" @click="confirm">确 定</el-button>
				</div>
			</el-dialog>
		</div>
		<div class="bill-main" v-show="isShow==='cwb'" key="item2">
			<module-view :propConfig="config2" ref="moduleView2" @clickHandle="clickHandle2" @detail="openEdit2"
				@pagination="getDataList2" @search="getDataList2" @resert="getDataList2" @onRefresh="onRefresh2">
			</module-view>
			<!-- 注册/编辑弹窗 -->
			<el-dialog :title="popTitle+'仓位'" :visible.sync="dialogFormVisible2" :show-close="false" width="30%">
				<by-form :propConfig="addConfig2" ref="addFormId2">
					<template v-slot:organizationName="{value}">
						<el-input placeholder="请选择所属机构名称" size="small" v-model="value.organizationName"
							class="input-organizationName" :readonly="true">
							<el-button slot="append" icon="el-icon-more" @click="handleSupplier"></el-button>
						</el-input>
					</template>
				</by-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeStoringLocation">取 消</el-button>
					<el-button type="primary" @click="confirm2">确 定</el-button>
				</div>
			</el-dialog>
		</div>
		<supplier-modal ref="supplierModal" @confirm="confirmSupplier" :zIndex="9999" />
	</div>
</template>
<script lang="ts">
	import { Component, Prop, Vue, Watch } from "vue-property-decorator";
	import api from "@/api/currency";
	import ruleForm from "./components/ruleForm.vue";
	import Assembly from "@/components/Assembly/yesno.vue";
	@Component({ components: { ruleForm } })
	export default class Depots extends Vue {
		isShow : any = 'ckb'
		timeNum = 0;
		timer : any = null
		timeNum2 = 0;
		timer2 : any = null
		popTitle : any = ''
		tableData : any = {}
		dialogFormVisible : boolean = false
		dialogFormVisible2 : boolean = false
		isAdd : any = false
		config : any = {
			attr: {
				calculateH: true
			},
			search: {
				attr: {
					size: 'mini'
				},
				columns: [
					[{
						span: 6,
						label: '仓库名称',
						prop: 'name',
						component: 'by-input',
						labelWidth: '70px',
						compConfig: {
							attr: {
								placeholder: '请输入名称',
								clearable: true
							},
						},
					}, {
						span: 6,
						label: '地址',
						prop: 'address',
						component: 'by-input',
						labelWidth: '70px',
						compConfig: {
							attr: {
								placeholder: '请输入地址',
								clearable: true
							}
						}
					},
					]
				]
			},
			tool: {
				tools: {
					search: true,
					refresh: true
				},
				customTools: [
					{
						name: '注册', icon: 'el-icon-plus', audit: [''], event: {
							click: () => {
								(this as any).onAdd();
							}
						}
					}
				]
			},
			table: {
				attr: {
					size: 'mini',
					align: 'left',
					triggerRowCheck: 'row'
				},
				columns: [{
					width: 200,
					title: '名称',
					field: 'name',
					isDetail: true,
				},
				{
					width: 120,
					title: '金蝶仓库名称',
					field: 'financeStorehouseName',
				},
				{
					width: 120,
					title: '金蝶仓库编号',
					field: 'financeStorehouseNo',
				},
				// {
				// 	width: 120,
				// 	title: '金蝶财务系统名称',
				// 	field: 'financeType',
				// },
				{
					width: 120,
					title: '绑定第三方系统',
					field: 'isThird',
					component: Assembly,
				},
				{
					width: 120,
					title: '第三方系统',
					field: 'thirdSysName',
				},
				{
					width: 120,
					title: '第三方货主',
					field: 'thirdPartnerName',
				},
				{
					width: 120,
					title: '第三方货仓库',
					field: 'thirdStorehouseName',
				},			
				{
					width: 120,
					title: '省',
					field: 'province',
				},
				{
					width: 120,
					title: '市',
					field: 'city',
				},
				{
					width: 150,
					title: '县/区',
					field: 'region',
				},
				{
					width: 150,
					title: '街道',
					field: 'street',
				},
				{
					width: 200,
					title: '地址',
					field: 'address',
				},
				{
					width: 70,
					title: '仓位',
					action: true,
					plugins: [{
						icon: 'el-icon-edit',
						name: '查看',
						audit: '',
						event: {
							click: (item : any) => {
								(this as any).changeTab(item)
							}
						}
					}]
				}, {
					width: 104,
					title: '操作',
					action: true,
					plugins: [{
						icon: 'el-icon-edit',
						name: '编辑',
						audit: '',
						event: {
							click: (item : any) => {
								(this as any).openEdit(item)
							}
						}
					}, {
						name: '删除',
						event: {
							click: (item : any) => (this as any).doDelete2(item, 'maindataStorehouse')
						}
					}]
				}]
			},
		}
		config2 : any = {
			attr: {
				calculateH: true
			},
			search: {
				attr: {
					size: 'mini'
				},
				columns: [
					[
						{
							span: 6,
							label: '名称',
							prop: 'name',
							component: 'by-input',
							compConfig: {
								attr: {
									placeholder: '请输入名称',
									clearable: true
								},
							},
						},
						{
							span: 6,
							label: '所属机构名称',
							prop: 'organizationName',
							component: 'by-input',
							compConfig: {
								attr: {
									placeholder: '请输入所属机构名称',
									clearable: true
								}
							}
						},
					],
				]
			},
			tool: {
				tools: {
					return: true,
					search: true,
					refresh: true
				},
				customTools: [
					{
						name: '注册', icon: 'el-icon-plus', audit: [''], event: {
							click: () => {
								(this as any).onAdd2();
							}
						}
					},
					{
						name: '删除', icon: 'el-icon-delete', audit: [''], event: {
							click: () => {
								(this as any).onDelete('moduleView2', 'maindataStoringLocation')
							}
						}
					},
				]
			},
			table: {
				attr: {
					size: 'mini',
					seq: true,
					align: 'left',
					checkbox: true,
					triggerRowCheck: 'row'
				},
				columns: [{
					width: 300,
					title: '仓位名称',
					field: 'name',
					isDetail: true,
				},
				{
					width: 250,
					title: '仓库名称',
					field: 'ckName',
				},
				{
					width: 200,
					title: '所属机构名称',
					field: 'organizationName',
				},
				{
					width: 150,
					title: '库存体积',
					field: 'stockVolume'
				},
				{
					width: 150,
					title: '库存数量上限',
					field: 'maxStockNumber'
				},
				{
					width: 150,
					title: '库存体积上限',
					field: 'maxStockVolume'
				}, {
					width: 120,
					title: '操作',
					action: true,
					plugins: [{
						icon: 'el-icon-edit',
						name: '编辑',
						audit: '',
						event: {
							click: (item : any) => {
								(this as any).openEdit2(item)
							}
						}
					}, {
						name: '删除',
						event: {
							click: (item : any) => (this as any).doDelete3(item, 'maindataStoringLocation')
						}
					}]
				}]
			},
		}
		addConfig = {
			attr: {
				size: 'small',
				rules: {
					name: [{
						required: true, message: '请输入名称', trigger: 'blur'
					}],
					address: [{
						required: true, message: '请输入详细地址', trigger: 'blur'
					}],
					province: [{
						required: true, message: '请选择仓库地址', trigger: 'change'
					}],
				}
			},
			columns: [
				[
					{
						span: 24,
						labelWidth: '110px',
						label: '名称',
						prop: 'name',
						component: 'by-input',
					},
					{
						span: 24,
						labelWidth: '110px',
						label: '第三方仓库名称',
						prop: 'financeStorehouseName',
						component: 'by-input',
					},
					{
						span: 24,
						labelWidth: '110px',
						label: '第三方系统名称',
						prop: 'financeType',
						component: 'by-input',
					},
					{
						span: 24,
						labelWidth: '110px',
						label: '第三方仓库编码',
						prop: 'financeStorehouseNo',
						component: 'by-input',
					},
				],
				[{
					labelWidth: '110px',
					label: '仓库地址',
					prop: 'province',
					component: 'by-area',
					compConfig: {
						attr: {
							province: 'province', //省
							provinceCode: 'provinceCode', //省编码
							city: 'city',   //市
							cityCode: 'cityCode',  //市编码
							county: 'region',  //县/区
							countyCode: 'regionCode',   //县/区编码
							town: 'street', //街道
							townCode: 'streetCode', //街道编码
						}
					}
				},
				],
				[
					{
						span: 24,
						labelWidth: '110px',
						label: '详细地址',
						prop: 'address',
						component: 'by-input',
					},
				]
			]
		}
		addConfig2 = {
			attr: {
				size: 'small',
				rules: {
					name: [{
						required: true, message: '请输入名称', trigger: 'change'
					}],
					organizationName: [{
						required: true, message: '请输入所属机构名称', trigger: 'change'
					}],
					stockVolume: [{
						required: true, message: '请输入库存体积', trigger: 'change'
					}],
					maxStockNumber: [{
						required: true, message: '请输入库存数量上限', trigger: 'change'
					}],
					maxStockVolume: [{
						required: true, message: '请输入库存体积上限', trigger: 'change'
					}]

				}
			},
			columns: [
				[
					{
						labelWidth: '110px',
						span: 23,
						label: '名称',
						prop: 'name',
						component: 'by-input',
					},
					{
						labelWidth: '110px',
						span: 23,
						label: '所属机构名称',
						prop: 'organizationName',
						slot: true,
					},
					{
						labelWidth: '110px',
						span: 23,
						label: '库存体积',
						prop: 'stockVolume',
						component: 'by-input',
						compConfig: {
							attr: {
								type: "number",
							},
						}
					},
					{
						labelWidth: '110px',
						span: 23,
						label: '库存数量上限',
						prop: 'maxStockNumber',
						component: 'by-input',
						compConfig: {
							attr: {
								type: "number",
							},
						}
					},
					{
						labelWidth: '110px',
						span: 23,
						label: '库存体积上限',
						prop: 'maxStockVolume',
						component: 'by-input',
						compConfig: {
							attr: {
								type: "number",
							},
						}
					},
				]
			]
		}
		created() {
			this.timer = setInterval(() => {
				this.getDataList()
			}, 500)
		}
		close(){
			(this as any).$refs.addFormId.clearValue();
			setTimeout(()=>{
				this.dialogFormVisible = false;
			},0)
		}
		// 跳转货主管理
		toCargoOwner(){
			this.dialogFormVisible = false;
			(this as any).$router.push('/oms/cargoOwner')
		}
		// 仓库确认注册/编辑
		confirm() {
			if(this.$refs.addFormId){
				(this.$refs.addFormId as any).validate().then(()=>{
					let query = (this as any).$refs.addFormId.getValue();
					// console.log(query.isThird)
					if(query.isThird == 0 || query.isThird == null){
						query.thirdSysName = '';
						query.thirdPartnerId = '';
						query.thirdPartnerName = '';
						query.thirdStorehouseName = '';
					}
					// console.log(query);
					if (this.popTitle === '注册') {
						let loading = this.$loading({ target: '.main-container' });
						api.saveList(query, 'maindataStorehouse').then((res : any) => {
							loading.close();
							if (res.code === 200) {
								this.dialogFormVisible = false;
								this.$message.success(this.popTitle + '成功');
								this.getDataList();
								this.$confirm('是否注册仓位', '提示', {
									confirmButtonText: '确定',
									cancelButtonText: '取消',
								}).then(() => {
									api.single({ id: res.data }, 'maindataStorehouse').then((data : any) => {
										this.changeTab(data.data);
										this.onAdd2();
									})
								}).catch(() => {
									let data = {
										storehouseId: res.data,
										idDelete: 0,
										maxStockNumber: "100000",
										maxStockVolume: "100000",
										name: "默认仓位",
										organizationId: 1,
										organizationName: "供应商A",
										stockVolume: "100000",
									};
									api.saveList(data, 'maindataStoringLocation').then((res : any) => {
										if (res.code === 200) {
											this.$alert('此仓库将新增一个默认仓位');
										} else this.$message.error(res.msg)
									})
								});
							} else this.$message.error(res.msg)
						}).catch(() => loading.close());
					} else if (this.popTitle === '编辑') {
						let loading = this.$loading({ target: '.main-container' });
						api.updateList(query, 'maindataStorehouse').then((res : any) => {
							loading.close();
							if (res.code === 200) {
								this.dialogFormVisible = false;
								this.$message.success(this.popTitle + '成功');
								this.getDataList();
							} else this.$message.error(res.msg)
						}).catch(() => loading.close());
					}
				})
			}
		}
		// 仓位确认注册/编辑
		confirm2() {
			(this as any).$refs.addFormId2.validate().then(() => {
				let query = (this as any).$refs.addFormId2.getValue();
				query.storehouseId = this.tableData.id;
				query.idDelete = 0;
				if (this.popTitle === '注册') {
					let loading = this.$loading({ target: '.main-container' });
					api.saveList(query, 'maindataStoringLocation').then((res : any) => {
						loading.close();
						if (res.code === 200) {
							this.dialogFormVisible2 = false;
							this.$message.success(this.popTitle + '成功');
							this.getOneself(query.storehouseId);
						} else this.$message.error(res.msg)
					}).catch(() => loading.close());
				} else if (this.popTitle === '编辑') {
					let loading = this.$loading({ target: '.main-container' });
					api.updateList(query, 'maindataStoringLocation').then((res : any) => {
						loading.close();
						if (res.code === 200) {
							this.dialogFormVisible2 = false;
							this.$message.success(this.popTitle + '成功');
							this.getOneself(query.storehouseId);
						} else this.$message.error(res.msg)
					}).catch(() => loading.close());
				}
			})
		}
		// 取消仓位注册
		closeStoringLocation() {
			this.dialogFormVisible2 = false;
			if (this.tableData.subList.length <= 0) {
				let data = {
					storehouseId: this.tableData.id,
					idDelete: 0,
					maxStockNumber: "100000",
					maxStockVolume: "100000",
					name: "默认仓位",
					organizationId: 1,
					organizationName: "供应商A",
					stockVolume: "100000",
				};
				api.saveList(data, 'maindataStoringLocation').then((res : any) => {
					if (res.code === 200) {
						this.getOneself(this.tableData.id);
						this.$alert('此仓库将新增一个默认仓位');
					} else this.$message.error(res.msg)
				});
			}
		}
		// 通过id拿到当条数据
		getOneself(e : any) {
			api.single({ id: e }, 'maindataStorehouse').then((res : any) => {
				if (res.code === 200) {
					this.tableData = res.data;
					this.tableData.subList.map((v : any) => {
						v.ckName = this.tableData.name;
					});
					(this.$refs.moduleView2 as any).setTableValue(this.tableData.subList);
				}
			})
		}
		// 获取仓库列表数据
		getDataList() {
			if (!this.$refs.moduleView) {
				if (this.timeNum > 5) {
					clearInterval(this.timer)
				}
				this.timeNum++;
				return
			}
			clearInterval(this.timer)
			let query = (this.$refs.moduleView as any).getQuery();
			api.pageList(query, 'maindataStorehouse').then((res : any) => {
				if (res.code === 200) {
					(this.$refs.moduleView as any).setTableValue(res.data.records);
					let page = {
						pageNo: res.data.current, //当前页
						pageSize: res.data.size, //每页条数
						total: res.data.total //总条数
					};
					(this.$refs.moduleView as any).setPage(page)
				} else this.$message.error(res.msg)
			})
		}
		// 获取仓位列表数据
		getDataList2() {
			if (!this.$refs.moduleView2) {
				if (this.timeNum2 > 5) {
					clearInterval(this.timer2)
				}
				this.timeNum2++;
				return
			}
			clearInterval(this.timer2)
			let query = (this.$refs.moduleView2 as any).getQuery();
			console.log(query);
			query.storehouseId = this.tableData.id;
			let loading = this.$loading({ target: '.main-container' });
			api.pageList(query, 'maindataStoringLocation').then((res : any) => {
				loading.close();
				if (res.code === 200) {
					res.data.records.map((v : any) => {
						v.ckName = this.tableData.name;
					});
					(this.$refs.moduleView2 as any).setTableValue(res.data.records);
					let page = {
						pageNo: res.data.current, //当前页
						pageSize: res.data.size, //每页条数
						total: res.data.total //总条数
					};
					(this.$refs.moduleView2 as any).setPage(page)
				} else this.$message.error(res.msg)
			}).catch(() => loading.close());
		}
		// 工具栏方法
		clickHandle2(e : any) {
			if (e === 'onAdd') this.onAdd2();
			if (e === 'onReturn') {
				this.isShow = 'ckb';
				this.getDataList();
			};
		}
		// 打开注册
		onAdd() {
			this.popTitle = '注册'
			this.dialogFormVisible = true;
			setTimeout(() => {
				if ((this as any).$refs.addFormId) (this as any).$refs.addFormId.setValue({});
			}, 0)
		}
		// 打开编辑
		openEdit(e : any) {
			console.log(e);
			this.popTitle = '编辑'
			this.dialogFormVisible = true;
			setTimeout(() => {
				if ((this as any).$refs.addFormId) (this as any).$refs.addFormId.setValue(e);
			}, 0)
		}
		// 打开注册
		onAdd2() {
			this.popTitle = '注册'
			this.dialogFormVisible2 = true;
			this.isAdd = true;
			setTimeout(() => {
				if ((this as any).$refs.addFormId2) (this as any).$refs.addFormId2.setValue({});
			}, 0)
		}
		// 打开编辑
		openEdit2(e : any) {
			this.popTitle = '编辑'
			this.dialogFormVisible2 = true;
			this.isAdd = false;
			setTimeout(() => {
				if ((this as any).$refs.addFormId2) (this as any).$refs.addFormId2.setValue(e);
			}, 0)
		}
		// 打开机构选择
		handleSupplier() {
			(this.$refs.supplierModal as any).setShow(true);
		}
		// 确定机构选择
		confirmSupplier(e : any) {
			if (e.length == 0) return this.$message.warning('请选择机构名称');
			let value : any = (this.$refs.addFormId2 as any).getValue();
			value.organizationName = e[0].name;
			value.organizationId = e[0].id;
			(this.$refs.addFormId2 as any).setValue(value);
		}
		// 查看仓位
		changeTab(item : any) {
			let loading = this.$loading({ target: '.main-container' });
			api.single({ id: item.id }, 'maindataStorehouse').then((res : any) => {
				if (res.code === 200) {
					this.isShow = 'cwb';
					this.tableData = res.data;
					res.data.subList.map((v : any) => {
						v.ckName = res.data.name;
					})
					console.log('仓库表数据 ==> ', res.data);
					(this.$refs.moduleView2 as any).setTableValue(res.data.subList);
					loading.close();
				} else loading.close();
			}).catch(() => loading.close());
		}
		// 刷新仓库
		onRefresh() {
			(this as any).$refs.moduleView.clearSearch();
			this.getDataList();
		}
		// 刷新仓位
		onRefresh2() {
			(this as any).$refs.moduleView2.clearSearch();
			this.getDataList2();
		}
		// 仓库操作删除
		doDelete2(item : any, url : any) {
			this.$confirm('确定删除吗,此操作不能撤销！', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				let loading = this.$loading({ target: '.main-container' });
				api.single({ id: item.id }, 'maindataStorehouse').then((res : any) => {
					if (res.data.subList.length > 0) {
						loading.close();
						this.$message.warning('此仓库下有仓位，不可删除！');
					} else {
						api.deleteList({ ids: item.id }, url).then((res : any) => {
							loading.close();
							if (res.code === 200) {
								this.getDataList();
								this.$message.success('删除成功');
							} else this.$message.error(res.msg)
						}).catch(() => loading.close());
					}
				}).catch(() => loading.close());
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 仓位工具栏删除
		onDelete(moduleView : any, url : any) {
			let selectData = (this.$refs[moduleView] as any).getSelectData()
			let ids = '';
			if (selectData.length > 0) {
				selectData.map((v : any) => {
					ids += v.id + ','
				})
			} else return this.$message.warning('请选择删除数据');
			ids = ids.slice(0, ids.length - 1);
			this.$confirm('确定删除吗,此操作不能撤销！', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				let loading = this.$loading({ target: '.main-container' });
				api.deleteList({ ids: ids }, url).then((res : any) => {
					loading.close();
					if (res.code === 200) {
						this.getDataList2();
						this.$message.success('删除成功');
					} else this.$message.error(res.msg)
				}).catch(() => loading.close());
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 仓位操作删除
		doDelete3(item : any, url : any) {
			console.log('仓位操作删除:', item, url);
			this.$confirm('确定删除吗,此操作不能撤销！', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				let loading = this.$loading({ target: '.main-container' });
				api.deleteList({ ids: item.id }, url).then((res : any) => {
					loading.close();
					if (res.code === 200) {
						this.getDataList2();
						this.$message.success('删除成功');
					} else this.$message.error(res.msg)
				}).catch(() => loading.close());
			}).catch(() => this.$message.info('已取消删除'));
		}
	}
</script>
<style lang="scss" scoped>
	.my-container {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		height: 100%;

		.bill-main {
			width: 100%;
			box-sizing: border-box;
			height: 100%;
		}
	}
</style>