<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" 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!=1" @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" @click="exportData">下载</el-button>
				</scExport>
			</div>
		</el-header>
		<el-main class="nopadding">
			<div class="flowPath">
				<flow :list="flowList"/>
			</div>
			<div class="searchMain searchMainNoTop">
				<scSearch ref="scSearch" :searchList="searchList" @fetchSelectData="getSelectData"></scSearch>

				<div class="searchItem searchBtn">
					<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>
			<scTable ref="table" :apiObj="list.apiObj" :column="list.column" row-key="id" stripe :size="size" highlightCurrentRow :hideTotal="false" @selection-change="selectionChange">
				<el-table-column type="selection" align="center" width="40"></el-table-column>
				<sc-table-column label="序号" align="center" type="index"></sc-table-column>
				<template #business_status="scope">
					<span v-for="(item,ind) in 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>

</template>

<script>

import {eventBus} from "@/utils/eventBus";
import flow from "./components/flow"
export default {
	name:"orderList",
	components: {
		flow
	},
	data() {
		return {
			size:'small',
			flowList:[
				{name:'新建/导入/同步邮件',left:false,right:true},
				{name:'提交维保',left:true,right:true},
				{name:'审核',left:true,right:false},
			],
			dialog: {
				save: false,
				show: false,
			},
			list: {
				apiObj: this.$API.orders.order.maintenance.list,
				column: [],
			},
			selection: [],
			exportShow:false,
			searchShow:false,
			searchList:[
				{name:'PE确认时间',type:'date',code:'pe_confirmation_time',show:true},
				{name:'保修到期',type:'date',code:'warranty_end_date',show:true},
				{name:'SLA到期时间',type:'date',code:'sla_expiration',show:true},
				{name:'客户',type:'select',code:['customer_name'],placeholder:"请选择客户",isOpen:true,show:false},
				{name:'维修单号',type:'text',code:['repair_order_no'],placeholder:"请输入维修单号",isOpen:true,show:false},
				{name:'维修等级',type:'select',code:'maintenance_level', data:[], placeholder:"请选择维修等级",show:false},
				{name:'园区名称',type:'select',code:['park_name'],data:[],placeholder:"请输入园区名称",isOpen:true,show:false},
				{name:'整机型号',type:'text',code:['device_model'],placeholder:"请输入整机型号",isOpen:true,show:false},
				{name:'故障类型',type:'multiple',code:'fault_type', data:[], placeholder:"请选择公司名称",show:false},
				{name:'部件型号',type:'text',code:['component_model'],placeholder:"请输入部件型号",isOpen:true,show:false},
				{name:'部件序列号',type:'text',code:['component_serial_no'],placeholder:"请输入部件序列号",isOpen:true,show:false},
				{name:'整机厂商',type:'text',code:['device_manufacturer'],placeholder:"请输入整机厂商",isOpen:true,show:false},
				{name:'是否需要关机',type:'select',code:['requires_shutdown'],placeholder:"请选择是否关机",isOpen:true,show:false},
				{name:'机房城市',type:'select',code:['city'],data:[],placeholder:"请输入机房城市",isOpen:true,show:false},
				{name:'机房/IDC名称',type:'select',code:['data_center_name'],data:[],placeholder:"请输入机房/IDC名称",isOpen:true,show:false},
				{name:'机架位置',type:'text',code:['rack_position'],placeholder:"请输入机架位置",isOpen:true,show:false},
				{name:'整机SN',type:'select',code:['device_sn'],data:[],placeholder:"请输入整机SN",isOpen:true,show:false},
				{name:'部件厂商',type:'text',code:['component_manufacturer'],placeholder:"请输入部件厂商",isOpen:true,show:false},
				{name:'部件零件PN号',type:'text',code:['component_pn'],placeholder:"请输入部件零件PN号",isOpen:true,show:false},
				{name:'剩余BD数',type:'text',code:['bd_backup_count'],placeholder:"请输入剩余BD数",isOpen:true,show:false},
				{name:'维保等级',type:'select',code:['maintenance_plan'],data:[],placeholder:"请输入维保等级",isOpen:true,show:false},
				{name:'业务状态',type:'select',code:['business_status'],data:[],placeholder:"请选择业务状态",isOpen:true,show:false},
				{name:'关键字',type:'text',code:['fault_description'],keyword:true,show:true},
			],
			params: {},
			statusList:[],

			countParams:this.$store.state.msg.main_order_count
		}
	},
	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;
			}
		},
		searchShowClick(){
			this.searchShow = !this.searchShow;
			this.searchList.forEach(item=>{
				if(item.isOpen){
					item.show = this.searchShow
				}
			})
		},
		async getSelectData(item) {
			let {data, params} = item;
			this.params = params;
			let searchParams = this.$TOOL.objCopy(params);
			searchParams.field = ""
			if (typeof data.code === 'string') {
				searchParams.field = data.code;
			} else {
				searchParams.field = data.code[0];
			}
			if (data.type == 'select') {
				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 => {
							item.label = item[data.code];
						})
					}
					this.searchList.forEach(item => {
						if (item.code == data.code) {
							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) {
			const res = await this.$API.orders.order.maintenance.import.post(params);
			if(res.code == 200){
				this.$message.success('上传成功，开始导入数据');
			}
		},
		importSuccess(){
			this.$refs.table.refresh()
		},

		//编辑
		table_edit(row){
			eventBus.$emit('tagClose','/order/create-order',{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,
				}
				const res = await this.$API.orders.order.maintenance.review.post(params);
				if (res.code == 200) {
					this.$refs.table.refresh();
				}
			})
		},
		async save_maintenance() {
			eventBus.$emit('tagClose','/order/submit-order',{id:this.selection.map(em => em.id)[0]});
		},
		// 工单设置
		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.$message.success('开始导出');
			}
		},
		upSearch(){
			this.$refs.table.upData(this.params);
		},
		reset(){
			this.params = {};
			this.$refs.scSearch.reload();
			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.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>
