<template>
	<div class="page">
		<template-page v-if="!formDialog && isShowTab" ref="pageRef" :get-list="getList" :table-attributes="tableAttributes"
			:table-events="tableEvents" :operationColumnWidth="140" :options-evens-group="optionsEvensGroup"
			:moreParameters="moreParameters" :column-parsing="columnParsing" :operation="operation()" :exportList="exportList">
			<div slot="moreSearch">
				<el-radio-group v-model="flag" size="mini" @change="changeType">
					<el-radio-button label="">全部</el-radio-button>
					<el-radio-button label="SAVE">保存</el-radio-button>
					<el-radio-button label="SUBMIT">提交</el-radio-button>
					<el-radio-button label="PAY_NOT_TAKE">已支付未提货</el-radio-button>
					<el-radio-button label="PAY_TAKE">已支付已提货</el-radio-button>
					<el-radio-button label="CANCEL">取消订单</el-radio-button>
				</el-radio-group>
				<br><br>
			</div>
		</template-page>
		<div class="detail" v-if="formDialog">
			<attachmentSalesOrderDetail :id="id" @back="backList" :formType="formDialogType"
				:title="'配件销售订单' + formDialogTitles[formDialogType]"></attachmentSalesOrderDetail>
		</div>
		<print-preview ref="preView" @initPrint="handleInitPrint" @refreshList="handleRefreshList" />

		<el-dialog
			title="导入结果"
			:visible.sync="showImportResult"
			width="600px">
			<div class="importResultList">
				<div class="item" v-for="(item, index) in importResultList" :key="index">{{item}}</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showImportResult = false">关 闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import attachmentSalesOrderDetail from '../components/attachmentSalesOrderDetail.vue'
import import_mixin from '@/components/template/import_mixin.js'
import ImageUpload from '@/components/file-upload'
import { downloadFiles } from '@/utils/util'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import { listPageV2, pageExport, getDetail, add, edit, submit, listImportP, queryImportResult } from "@/api/auxiliaryFittings/auxiliarySalesOrder";
import { getWebsit } from "@/api/customerManagement";
import printPreview from '../components/preview.vue'
import { disAutoConnect, hiprint } from 'vue-plugin-hiprint'
import operation_mixin from '@/components/template/operation_mixin.js'
import { commonTemplateDownload } from '@/api/common.js'
disAutoConnect()
export default {
	components: { TemplatePage, ImageUpload, attachmentSalesOrderDetail, printPreview },
	mixins: [import_mixin,operation_mixin],
	data() {
		return {
			// 表格属性
			tableAttributes: {
				// 启用勾选列
				selectColumn: true
			},
			// 表格事件
			tableEvents: {
				'selection-change': this.selectionChange
			},
			// 勾选选中行
			recordSelected: [],
			/** 表单变量 */
			formDialogType: 0,
			formDialogTitles: ["新增", "编辑", "详情"],
			formDialog: false,
			id: '',
			flag: this?.$route?.params?.pageCode || '',
			websitList: [],
			isShowTab: true,
			orderEnginBaseId: '',
			payQrcode: JSON.parse(localStorage.getItem('greemall_user')).payQrcode,
			billTitle: JSON.parse(localStorage.getItem('greemall_user')).billTitle,//打印名称
			showImportResult: false,
			importResultList: [],
		}
	},
	computed: {
		// 事件组合
		optionsEvensGroup() {
			return [
				[
					[
						this.optionsEvensAuth("add", {
							click: this.addData
						}),
					]
				],
				[
					[
						this.optionsEvensAuth("imp", {
							render: () => {
							  return this.importButton(listImportP, '导入', null, null, (res) => {
									this.$nextTick(() => {
										this.checkImportResult(res.data);
									})
								})
							}
						})
					],
					[
						this.optionsEvensAuth("template", {
							click: () => {
								this.handleDownload()
							}
						})
					]
				]
			]
		},
		// 更多参数
		moreParameters() {
			return []
		},
		formItems() { },
		filterArr() {
			return function (arr, size) {
				//判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组
				if (!arr.length || !size || size < 1) return []
				let [start, end, result] = [null, null, []]
				for (let i = 0; i < Math.ceil(arr.length / size); i++) {
					start = i * size
					end = start + size
					result.push(arr.slice(start, end))
				}
				return result
			}
		}
	},
	created(){
		if(this.$route.query.id){
			this.id = this.$route.query.id
			this.formDialogType = 2
			this.openForm()
		}
		if(this.pageCode){
			this.orderEnginBaseId = this.pageCode
		}
	},
	watch: {
		flag(){
			this.isShowTab = false
			this.$nextTick(()=>{
				this.isShowTab = true
			})
		}
	},
	methods: {
		// 切换状态
		changeType(val) {
			this.$refs.pageRef.refreshList()
		},
		backList() {
			this.id = ''
			this.formDialog = false;
			this.$refs.pageRef.refreshList()
		},
		// 列表请求函数
		getList(p, cb) {
			try {
				var pam = JSON.parse(JSON.stringify(p))
				pam.params.push({ "param": "a.goods_type", "compare": "=", "value": 'P' }, { 'param': 'a.flag', "compare": "=", "value": this.flag }, { 'param': 'a.order_engin_base_id', "compare": "=", "value": this.orderEnginBaseId })
				cb && cb(pam)
				return listPageV2(pam)
			} catch (error) {
				console.log(error)
			}
		},
		// 列表导出函数
		exportList: pageExport,
		// 表格列解析渲染数据更改
		columnParsing(item, defaultData) {
			if (item.jname === 'idCardImg') {
				defaultData.render = (h, { row, index, column }) => {
					return (
						<div style="padding:0 6px;cursor: pointer;">
							{row.idCardImg ? row.idCardImg.split(",").map(url => <el-image src={url} preview-src-list={[url]} fit="fit" style="width:80px;height:80px;" />) : null}
						</div>
					)
				}
			}
			return defaultData
		},
		// 监听勾选变化
		selectionChange(data) {
			this.recordSelected = data
		},
		
		operation() {
			return this.operationBtn({
				edit: {
					conditions: ({ row, index, column }) => {
						return row.flag == 'SAVE'
					},
					click: ({ row, index, column }) => {
						this.id = row.salesId
						this.formDialogType = 1
						this.openForm()
					}
				},
				detail: {
					conditions: ({ row, index, column }) => {
						return row.flag != 'SAVE'
					},
					click: ({ row, index, column }) => {
						this.id = row.salesId
						this.formDialogType = 2
						this.openForm()
					}
				},
				verify: {
					conditions: ({ row, index, column }) => {
						return row.flag == 'PAY_NOT_TAKE'
					},
					click: ({ row, index, column }) => {
						this.id = row.salesId
						this.formDialogType = row.flag == 'SAVE' ? 1 : 2
						this.openForm()
					}
				},
				print: {
					click: ({ row, index, column }) => {
						this.toPrint(row, 2)
					}
				},
			})
		},


		addData() {
			this.formDialogType = 0
			this.openForm()
		},
		openForm() {
			this.formDialog = true;
		},
		getWebsit() {
			getWebsit({ type: 'C' }).then(res => {
				this.websitList = res.data
			})
		},
		// 点击打印
		async toPrint(row, type) {
			this.getWebsit()
			let pagingData = []
			const { data } = await getDetail({
				salesId: row.salesId
			})
			pagingData = this.filterArr(data.items, 4)
			// 初始化模板，否则生成的模板叠加
			hiprint.init()
			this.hiprintTemplate = new hiprint.PrintTemplate()
			// 兼容批量打印
			// let params = !type ? this.filterArr() : [row.salesId]
			let len = pagingData.length
			let loadingLen = len
			// 使用 i-- 提升for效率
			this.$startLoading()
			for (let i = 0; i < len; i++) {
				try {
					let websitHtml = ''
					let html = ''
					let num = 0
					let totalAmount = 0
					pagingData[i].forEach(item => {
						totalAmount = (Number(item.saleAmount) * 100 + totalAmount * 100) / 100
						num += Number(item.salesQty)
						html += `
					<tr align="center">
					<td>${item.goodsName || ''}</td>
					<td>${item.goodsSpecification || ''}</td>
					<td>${item.goodsSalesUnit || ''}</td>
					<td>${item.salesQty || ''}</td>
					<td>${item.price || ''}</td>
					<td>${item.saleAmount || ''}</td>
					<td>${data.storageName}</td>
					<td></td>
					</tr>
				`
					})
					this.websitList.slice(0, 5).forEach(item => {
						websitHtml += `
					<div style="display: flex;font-size: 14px;margin-bottom: 6px;">
						<div style="margin-right: 10px;">${item.name}</div>
						<div style="margin-right: 10px;">${item.websitPhone}</div>
						<div>地址: ${item.address}</div>
					</div>
				`
					})
					// 模板基础配置
					this.panel = this.hiprintTemplate.addPrintPanel({
						height: 140,
						width: 241,
						fontFamily: '黑体',
						fontSize: 13,
						paperFooter: 340,
						paperHeader: 10,
						paperNumberDisabled: true
					})

					// 获取收款单模板和基础配置
					this.panel.addPrintHtml({
						options: {
							width: 633,
							top: 30,
							left: 20,
							fontFamily: '黑体',
							fontSize: 13,
							content: this.setTableDom(data, html, websitHtml, totalAmount, num, len, i)
						}
					})

					loadingLen--
				} catch (error) {
					console.log(999, error)
					this.$endLoading()
					return
				}
			}
			if (loadingLen === 0) {
				this.$endLoading()
			}
			console.log(333)
			// 预览打印内容
			this.$refs.preView.show(this.hiprintTemplate, this.panel)
		},
		// 打印模板
		setTableDom(data, html, websitHtml, totalAmount, num, length, page) {
			return `
	   <div style="font-family:'黑体';font-size: 16px;">
			<div style="display: flex;justify-content: space-between;align-items: center;">
				<div style="width: 28%;"></div>
				<h1 style="text-align:center;margin: 10px 0;">${this.billTitle?this.billTitle:data.websitName}销售单</h1>
				<div>共 ${length}页 第 ${page + 1} 页</div>
			</div>
		  <div style="display: flex;justify-content: space-between;">
			<div style="width: 28%;"></div>
			<div>单据日期: ${data.createTime}</div>
			<div>单据编号: ${data.salesId}</div>
		  </div>
		  <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
		  	<div>客户: ${data.workerName}</div>
		  	<div>摘要: ${data.payType == 'CASH' ? '现金' : data.payType == 'WECHAT' ? '微信': '工程支付'}</div>
		  </div>
		  <div style="display: flex;justify-content: space-between;font-size: 16px;margin-bottom: 10px;">
		  	<div>联系电话: ${data.workerMobile}</div>
		  	<div>收货地址: ${data.province?(data.province + data.city + data.area + data.street + data.address):''}</div>
			<div style="width: 28%;"></div>
		  </div>
	      <div >
	        <table border=".5" cellspacing="0" width="856"
	         style="border-color: rgb(0,0,0);
	          border-collapse: collapse;
	          border-style: none;
	          border: 1px solid rgb(0,0,0);
	          font-weight: normal;
	          
	          text-decoration: none;
	          vertical-align: middle;
	          box-sizing: border-box;
	          word-wrap: break-word;
	          word-break: break-all;">
				<tr align="center">
					<td>商品名称</td>
					<td>规格</td>
					<td>单位</td>
					<td>数量</td>
					<td>单价</td>
					<td>金额</td>
					<td>仓库</td>
					<td>备注</td>
				</tr>
	            ${html}
				<tr align="center" align="center">
				  <td>小计: </td>
				  <td colspan="2"></td>
				  <td>${num}</td>
				  <td></td>
				  <td>${totalAmount}</td>
				  <td colspan="2">金额总计: ${totalAmount}</td>
				</tr>
	        </table>
	      </div>
		  <div style="display: flex;justify-content: space-between;font-size: 16px;margin: 10px 0;">
		  	<div>制单人: ${data.createBy || ''}</div>
		  	<div>审核人: ${data.confirmBy || ''}</div>
			<div>业务员: </div>
			<div>签收人: </div>
		  </div>
		  <div style="display: flex;justify-content: space-between;">
		  	<div>
		  		${websitHtml}
		  	</div>
		  	${(data.payType == 'CASH' && this.payQrcode)?`<div style="">
		  		<img style="width: 80px;height: 80px;" src="${this.payQrcode}"/>
		  	</div>`:''}
		  </div>
	      <div style="margin:100px 0 0 0">
	        <div></div>
	      </div>
	   </div>
	  `
		},
		handleRefreshList() {
			this.recordSelected = []
			this.$refs.pageRef.refreshList()
		},
		handleInitPrint() {
			this.$nextTick(() => {
				this.initPrint()
			})
		},
		// 下载导入模版
		handleDownload() {
			commonTemplateDownload({ name: '配件销售订单导入模板.xlsx' }, `${this.$route.meta.title}`).then(res => {
			    this.$message({
			        message: '下载成功',
			        type: 'success'
			    })
			}).catch(err => {
			    this.$message.error('下载失败')
			})
		},

		// 查询导入结果
		checkImportResult(importBatchId) {
			const loading = this.$loading({
				lock: true,
				text: '正在查询导入结果',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			queryImportResult({
				importBatchId
			}).then(result => {
				if(result.data.waitCount == 0){
					clearInterval(this.timer)
					loading.close();
					// result.data.errList = ['测试测试1', '测试测试1']
					if(result.data?.errList?.length > 0) {
						this.importResultList = result.data.errList;
						this.showImportResult = true;
					}else {
						
					}
				}else {
					this.timer = setTimeout(()=>{
						this.checkImportResult(importBatchId);
					}, 2000)
				}
			}).catch(err => {
				loading.close();
				clearInterval(this.timer)
			})
		},
	}
}
</script>

<style lang="scss" scoped>
.page {
	height: 100%;
}

.tab {
	padding: 20px 20px 0 20px;
}

.importResultList {
	.item {
		font-size: 16px;
		margin-bottom: 10px;
	}
}
</style>
