<template>
	<el-container class="mainBox mainHeaderNoBorderPadding">
		<el-header class="header">
			<div class="left-panel">
				<el-button type="primary" v-auth="'maintenanceOrderAdd'" :size="size" icon="el-icon-plus" @click="add">新增工单</el-button>
				<scImport ref="scImport" :size="size" type="10" :httpDisabled="httpDisabled" title="批量导入维保工单" @parentParams="importUpload" @importSuccess="importSuccess">
					<template #header>
						<el-button v-auth="'maintenanceOrderImport'" type="primary" :size="size" plain @click="importFile" style="margin-right: 12px;">批量导入</el-button>
					</template>
					<template #download>
						<div v-auth="'maintenanceOrderImport'" @click="importTemplate">下载导入模版</div>
					</template>
				</scImport>
				<el-button type="primary" v-auth="'maintenanceOrderSubmit'" plain :size="size" :disabled="selection.length==0" @click="save_maintenance">提交维保</el-button>
				<el-button type="success" v-auth="'maintenanceOrderApproval'" :size="size" icon="sc-icon-OrderReview" :disabled="selection.length==0" @click="batch_review">批量审核</el-button>
				<el-button type="danger" v-auth="'maintenanceOrderDelete'" plain :size="size" icon="el-icon-Delete" :disabled="selection.length==0" @click="batch_del"></el-button>
			</div>
			<div class="right-panel">
				<scExport :size="size" @exportData="exportData" @updateShow="exportChangeShow" :show="exportShow" type="11">
					<el-button :size="size" v-auth="'maintenanceOrderExport'" icon="sc-icon-Download" :disabled="exportShow" @click="exportData">导出</el-button>
				</scExport>
			</div>
		</el-header>
		<el-main class="nopadding">
			<div class="flowPath">
				<flow :list="flowList"/>
			</div>
			<div class="fieldsSwitchBox searchConditionItem" v-if="!fieldsShow">
				<div class="leftBox"></div>
				<div class="rightBox" @click="searchClick">
					<el-icon class="icon"><sc-icon-SwitchQuery /></el-icon>
					<span class="name">切换查询方式</span>
				</div>
			</div>
			<div class="searchMain searchMainNoTop" v-if="!fieldsShow">
				<scTableSearch ref="scSearch" :searchList="list.column" :paramsData="params" :searchShow="searchShow" @fetchSelectData="getSelectData" @changeHeaderData="getHeaderData"></scTableSearch>

				<div class="searchItem searchBtn" v-if="searchHeaderShow">
					<el-button :size="size" :icon="searchShow?'el-icon-ArrowUpBold':'el-icon-ArrowDownBold'" @click="searchShowClick">{{searchShow?'收起':'更多'}}</el-button>
					<el-button :size="size" type="primary" icon="el-icon-search" @click="upSearch">查询</el-button>
					<el-button :size="size" type="info" icon="el-icon-RefreshRight" @click="reset">重置</el-button>
				</div>
			</div>
			<div class="searchMain searchMainMarginNone searchMainNoTop" v-if="fieldsShow">
				<herderMultipleSearch @fieldsSwitch="fieldsSwitch" @fieldsSearch="fieldsSearch" :fieldsShow="fieldsShow" :searchList="list.fields"></herderMultipleSearch>
			</div>
			<scTable ref="table" :apiObj="list.apiObj" :column="list.column" row-key="id" stripe :size="size" border highlightCurrentRow :hideTotal="false" @selection-change="selectionChange" @columnBack="columnBack">
				<el-table-column type="selection" align="center" width="40"></el-table-column>
				<template #business_status="scope">
					<span v-for="(item,ind) in setMap.statusList" :key="ind">
						<span :style="{color:item.value==1?`var(--el-order-color-1)`:item.value==2?`var(--el-order-color-2)`:item.value==3?`var(--el-order-color-3)`:item.value==4?`var(--el-order-color-4)`:`var(--el-order-color-100)`}"
							  v-if="item.value == scope.row.business_status">{{item.label}}</span>
					</span>
				</template>
				<el-table-column label="操作" fixed="right" align="center" width="150">
					<template #default="scope">
						<el-dropdown>
							<el-button class="noBorderBtn" icon="el-icon-more" :size="size"></el-button>
							<template #dropdown>
								<el-dropdown-menu>
									<div v-auth="'maintenanceOrderAdd'">
										<el-dropdown-item @click="table_edit(scope.row)" icon="sc-icon-Edit">编辑工单</el-dropdown-item>
									</div>
									<div v-auth="'maintenanceOrderSubmit'">
										<el-dropdown-item  icon="sc-icon-SaveMaintenance" @click="table_submit(scope.row)">提交维保</el-dropdown-item>
									</div>
									<div v-auth="'maintenanceOrderDelete'">
										<el-dropdown-item @click="table_del(scope.row)" icon="sc-icon-Delete">删除工单</el-dropdown-item>
									</div>
									<div v-auth="'maintenanceOrderApproval'">
										<el-dropdown-item @click="table_review(scope.row)" icon="sc-icon-OrderReview" divided>审核工单</el-dropdown-item>
									</div>
									<div v-auth="'maintenanceOrderDetail'">
										<el-dropdown-item @click="table_show(scope.row)" icon="sc-icon-See">工单详情</el-dropdown-item>
									</div>
									<div v-auth="'orderLogsList'">
										<el-dropdown-item  icon="sc-icon-OrderLog" @click="table_logs(scope.row)" divided>工单日志</el-dropdown-item>
									</div>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</template>
				</el-table-column>

				<template #total>
					<div class="countView">
						<div class="countItem" v-for="(item,index) in countParams" :key="index">
							<span class="name">{{item.title}}:</span>
							<span class="num">{{item.value}}</span>
						</div>
					</div>
				</template>
			</scTable>
		</el-main>
	</el-container>

	<manufacturer-dialog v-if="dialog.companyWf" ref="companyWfDialog" @success="handleWfSuccess" @closed="dialog.companyWf=false"></manufacturer-dialog>
</template>
<script>

import {eventBus} from "@/utils/eventBus";
import flow from "./components/flow"
import manufacturerDialog from "@/views/order/orderList/components/manufacturer"
export default {
	name:"orderList",
	components: {
		flow,
		manufacturerDialog
	},
	data() {
		return {
			fieldsShow:false,
			size:'small',
			httpDisabled:false,
			flowList:[
				{name:'新建/导入/同步邮件',left:false,right:true},
				{name:'提交维保',left:true,right:true},
				{name:'审核',left:true,right:false},
			],
			dialog: {
				save: false,
				show: false,
				companyWf:false
			},
			setMap:{
				statusList:[],
			},
			list: {
				apiObj: this.$API.orders.order.maintenance.list,
				column: [],
				fields:{}
			},
			selection: [],
			exportShow:false,
			searchShow:false,
			searchHeaderShow:false,
			filterMap:{
				data:{}
			},
			params: {},

			countParams:this.$store.state.msg.main_order_count
		}
	},
	provide(){
		return{
			filterUploadClick:this.filterClick,
			filterUploadParams:this.filterParams,
			filterTagClose:this.tagClose,
			filterModelParams:this.filterModelParams,
		}
	},
	watch:{
		'list.column':{
			handler(val){
				this.searchHeaderShow = val.length>0 && val.some(em=>em.is_search);
			},
			immediate:false,
			deep:true
		}
	},
	computed:{
		filterModelParams(){
			return this.filterMap
		},
	},
	mounted() {
		// 获取新消息
		eventBus.$on('sockBack', this.getWsResult);
		this.getStatusList();
	},
	unmounted() {
		eventBus.$off('sockBack', this.getWsResult);
	},
	methods: {
		getWsResult(res){
			if(res.data && res.data.type == 21){
				this.$store.commit('set_list_count_info',res.data.list_count_info.main_order_count);
				this.countParams = res.data.list_count_info.main_order_count;
			}
		},
		/**
		 * 表格检索开始
		 * */
		searchClick(){
			this.fieldsShow = true;
		},
		fieldsSwitch(val){
			this.fieldsShow = val;
		},
		fieldsSearch(params){
			this.params = params;
			this.upSearch();
		},

		columnBack(val,fieldsData){
			val.forEach(item=>{
				if(item.prop === "business_status"){
					item.data = this.setMap.statusList;
				}
			})
			this.list.column = val;
			this.list.fields = fieldsData;
		},
		async filterClick(item) {
			let {data, params} = item;
			let filterParams = Object.assign(this.params,params);
			this.filterMap.data = filterParams;
			let searchParams = this.$TOOL.objCopy(this.params);
			searchParams.field = ""
			if (typeof data.prop === 'string') {
				searchParams.field = data.prop;
			} else {
				searchParams.field = data.prop[0];
			}
			if (data.search_type == 'select' || data.search_type == 'checkbox') {
				await this.getField(data,searchParams);
			}
		},
		filterParams(params){
			let filterParams = Object.assign(this.params,params);
			this.filterMap.data = filterParams;
			this.upSearch();
		},
		tagClose(params){
			let filterParams = Object.assign(this.params,params);
			this.filterMap.data = filterParams;
		},
		searchShowClick(){
			this.searchShow = !this.searchShow;
			eventBus.$emit('close-all-popovers');
		},
		getHeaderData(params){
			this.params = params;
			this.filterMap.data = params;
		},
		async getSelectData(item) {
			let {data, params} = item;
			this.params = params;          // 列表需要的参数
			this.filterMap.data = params;  // 表头组件需要转 才能传的参数
			let searchParams = this.$TOOL.objCopy(params);
			searchParams.field = ""
			if (typeof data.prop === 'string') {
				searchParams.field = data.prop;
			} else {
				searchParams.field = data.prop[0];
			}
			if (data.search_type == 'select' || data.search_type == 'checkbox') {
				await this.getField(data,searchParams)
			}
		},
		async getField(data,searchParams) {
			const res = await this.$API.orders.order.maintenance.field.post(searchParams);
			if (res.code == 200) {
				if (res.data && res.data.length > 0) {
					res.data.forEach(item => {
						if (data.prop === 'business_status') {
							this.setMap.statusList.forEach(em => {
								if (em.value === item[data.prop]) {
									item.label = em.label;
									item.value = em.value;
								}
							})
						} else {
							item.label = item[data.prop];
							item.value = item[data.prop];
						}
					})
				}
				this.list.column.forEach(item => {
					if (item.prop == data.prop) {
						item.data = res.data;
					}
				})
			}
		},
		/** 表格检索结束 */

		//添加
		add(){
			eventBus.$emit('tagClose','/order/create-order');
		},
		// 批量导入
		importFile(){
			this.$nextTick(()=>{
				this.$refs.scImport.importFile();
			})
		},
		async importTemplate() {
			const res = await this.$API.orders.order.maintenance.template.post();
			const blob = new Blob([res]);
			const text = new Date().getTime();
			const eLink = document.createElement('a');
			eLink.download = "维保导入模版_"+text+'.xlsx';
			eLink.style.display = 'none';
			eLink.href = URL.createObjectURL(blob);
			document.body.appendChild(eLink);
			eLink.click();
			URL.revokeObjectURL(eLink.href);
			document.body.removeChild(eLink);
		},
		async importUpload(params) {
			this.httpDisabled = true;
			const res = await this.$API.orders.order.maintenance.import.post(params);
			if(res.code == 200){
				this.$refs.scImport.setAnalysisShow(true);
				this.$message.success('上传成功，开始导入数据');
			}
		},
		importSuccess(refresh){
			this.httpDisabled = false;
			if(!refresh){
				this.$refs.table.refresh()
			}
		},

		//编辑
		table_edit(row){
			eventBus.$emit('tagClose','/order/order-edit',{id:row.id});
		},
		//查看
		table_show(row){
			eventBus.$emit('tagClose','/order/order-info',{id:row.id});
		},
		// 审核
		table_review(row){
			eventBus.$emit('tagClose','/order/preview-order',{id:row.id});
		},
		//删除
		async table_del(row){
			this.$confirm(`确定删除 ${row.repair_order_no} 吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				const reqData = {order_ids: [row.id]};
				const res = await this.$API.orders.order.maintenance.delete.post(reqData);
				if(res.code == 200){
					this.$refs.table.refresh();
				}
			}).catch(()=>{})
		},
		async batch_del(){
			this.$confirm(`确定删除 ${this.selection.length}项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				let ids = this.selection.map(em=>em.id);
				const reqData = {order_ids: ids};
				const res = await this.$API.orders.order.maintenance.delete.post(reqData);
				if(res.code == 200){
					this.$refs.table.refresh();
				}
			}).catch(()=>{})
		},
		async batch_review(){
			this.$messageBox.prompt('如果拒绝，请输入审核不通过的理由。', '审核', {
				confirmButtonText: '拒绝',
				cancelButtonText: '通过',
				cancelButtonClass:'cancelBtn el-button--primary',
				confirmButtonClass:'saveBtn el-button--danger',
			}).then(async ({value}) => {
				let params = {
					order_ids:this.selection.map(em=>em.id),
					status:false,
					opinion:value
				}
				const res = await this.$API.orders.order.maintenance.review.post(params);
				if(res.code == 200){
					this.$refs.table.refresh();
				}
			}).catch(async () => {
				let params = {
					order_ids: this.selection.map(em => em.id),
					status: true,
					is_verify_erp_inventory: false,
				}
				const res = await this.$API.orders.order.maintenance.review.post(params);
				if (res.code == 200) {
					this.$message.success('审核成功');
					this.$refs.table.refresh();
				}
			})
		},

		save_maintenance() {
			// eventBus.$emit('tagClose','/order/submit-order',{id:this.selection.map(em => em.id)[0]});
			this.dialog.companyWf = true;
			this.$nextTick(() => {
				this.$refs.companyWfDialog.open('show');
			})
		},
		async handleWfSuccess(data, mode) {
			if (mode === 'show') {
				const params = {
					order_ids: this.selection.map(em => em.id),
					maintenance_vendor: data.company_id,
					is_verify_erp_inventory: false,
					// component_info: []
				};
				const res = await this.$API.orders.order.maintenance.submit.post(params);
				if (res.code == 200) {
					this.$refs.companyWfDialog.hideVisible();
					this.$refs.table.refresh();
				}
			}
		},
		// 工单设置
		async table_submit(row){
			eventBus.$emit('tagClose','/order/submit-order',{id:row.id});
		},
		// 工单日志
		table_logs(row){
			eventBus.$emit('tagClose','/order/order-logs',{id:row.id,type:1});
		},
		//表格选择后回调事件
		selectionChange(selection){
			this.selection = selection;
		},
		// 状态
		changeSwitch(val, row) {
			row.$switch_yx = true;
			setTimeout(async () => {
				let params = {
					id: row.id,
					status: row.active_status,
				};
				const res = await this.$API.system.company.status.post(params);
				if(res.code !=200){
					row.active_status = !row.active_status;
				}
				delete row.$switch_status;
				delete row.$switch_yx;
			}, 500);
		},
		// 下载导出
		exportChangeShow(params){
			if(params.type == 11){
				this.exportShow = params.status==0?true:false
			}
		},
		async exportData() {
			if(this.exportShow) return
			const res = await this.$API.orders.order.maintenance.export.post(this.params);
			if(res.code == 200){
				this.exportShow = true;
				this.$message.success('开始导出');
			}
		},
		upSearch(){
			this.$refs.table.upData(this.params);
		},
		reset(){
			this.params = {};
			this.filterMap.data = {};
			this.$refs.scSearch.reload();
			eventBus.$emit('reset-popovers');
			this.$refs.table.reload();
		},
		handleSaveSuccess(){
			this.$refs.table.refresh();
		},
		async getStatusList() {
			const res = await this.$API.orders.order.maintenance.status.post();
			if (res.code == 200) {
				this.setMap.statusList = res.data;
			}
		},
	}
}
</script>

<style lang="scss" scoped>
.mainBox{
	padding: 0;
	.header{
		padding: 0 10px;
	}
	.searchMain{
		margin-left: 10px;
		margin-right: 10px;
	}
	.scTable{
		padding: 0 10px;
	}
}
.logoCell{
	display: flex;
	align-items: center;
	height: 20px;
	margin: 0 auto;
}
.el-message-box{
	::v-deep .cancelBtn{

	}
	::v-deep .saveBtn{

	}
}
</style>
