<template>
  <basic-container>
    <avue-crud 
			ref="crud"
			:option="option"
			:table-loading="loading"
			:data="listData"
			@on-load="onLoad"
			@refresh-change="onLoad"
			@search-change="searchChange"
			@search-reset="searchReset"
			@selection-change="selectionChange"
			v-model:page="page"
			@current-change="currentChange"
			@size-change="sizeChange">
			<template #menu-left>
				<el-button
				  type="primary"
				  icon="el-icon-plus"
					v-if="permission.order_add"
				  @click="handleAdd">新 增</el-button>
				<el-button
				  type="primary"
				  icon="el-icon-edit"
				  plain
					v-if="permission.order_edit"
				  @click="handleEdit" :disabled="selectionList.length != 1">编 辑</el-button>
				<template v-if="orderStatus == '' || orderStatus == '1'">
					<el-button
					  type="primary"
					  icon="el-icon-user-filled"
						v-if="permission.order_dispatch && (deptId == '3' || deptId == '5')"
					  plain
					  @click="handleDispatch" :disabled="selectionList.length < 1">派 工</el-button>
					<el-button
					  type="primary"
					  icon="el-icon-user-filled"
						v-if="permission.order_dispatch && (deptId != '3' && deptId != '5')"
					  plain
					  @click="handleDispatch" :disabled="selectionList.length != 1">派 工</el-button>
				</template>
				<el-button
				  type="success"
				  icon="el-icon-document"
					v-if="permission.order_receive && orderStatus == ''"
				  plain
				  @click="handleReceive" :disabled="selectionList.length < 1">接 单</el-button>
				<el-button
				  type="success"
				  icon="el-icon-document"
					v-if="permission.order_feedback && (orderStatus == '4' || orderStatus == '5')"
				  plain
				  @click="handleFeedback" :disabled="selectionList.length != 1">回 访</el-button>
				<el-button
				  type="warning"
				  icon="el-icon-coin"
					v-if="permission.order_settlement && (orderStatus == '4')"
				  plain
				  @click="handleSettlement" :disabled="selectionList.length != 1">结 算</el-button>
				<el-button
					type="info"
				  icon="el-icon-circle-close"
					v-if="permission.order_close"
				  plain
				  @click="handleDelete('无效')" :disabled="selectionList.length != 1">无 效</el-button>
			  <el-button
			    type="danger"
			    icon="el-icon-delete"
					v-if="permission.order_delete"
			    plain
			    @click="handleDelete('删除')" :disabled="selectionList.length != 1">删 除</el-button>
				<el-button
				  type="warning"
				  icon="el-icon-download"
					v-if="permission.order_export"
				  plain
				  @click="handleExport">导 出</el-button>
			</template>
			<template #customerAddress="{row}">
				{{ row.province }}{{ row.city }}{{ row.area }}{{ row.customerAddress }}
			</template>
			<template #number="{row}">
				<el-link type="primary" :underline="false" @click="handleView(row)">{{ row.number }}</el-link>
			</template>
    </avue-crud>
  </basic-container>
	
	<!-- 新增、编辑、详情 avue-dialog avue-crud__dialog-->
	<el-dialog
		class="avue-dialog avue-crud__dialog"
	  :title="title"
	  v-model="open"
		v-if="open"
	  width="1100px"
		:close-on-click-modal="false"
		:align-center="true"
	  append-to-body>
		<el-tabs v-model="tabActive" @tab-click="handleTab" v-if="title == '详情'">
			<el-tab-pane label="详 情" name="first"></el-tab-pane>
			<el-tab-pane label="过程信息" name="second">
				<el-timeline>
					<el-timeline-item
						v-for="(activity, index) in formData.guochengList"
						:key="index"
						type='primary'
						placement="top"
						:timestamp="activity.d"
					>
						{{ activity.c }}
					</el-timeline-item>
				</el-timeline>
			</el-tab-pane>
		</el-tabs>
		<avue-form
			ref="formData"
			:option="formOption"
			v-model="formData"
			:hidden="tabActive == 'second'">
			<template #feedback>
				<el-row style="border: 0;">
					<el-col :span="22" style="border: 0;">
						<el-input
						    v-model="formData.feedbackEntity.feedback"
						    style="width: 100%;"
								class="el-textarea el-input--default is-disabled avue-input"
						    :rows="4"
								disabled
						    type="textarea"
						  />
					</el-col>
					<el-col :span="2" style="border: 0; text-align: right;">
						<el-button size="small" plain type="primary" @click="feedbackPOpen = true; getFeedbackList(formData.id)">查看全部</el-button>
					</el-col>
				</el-row>
			</template>
			<template #serviceProcess>
				<ul class="serviceProcess">
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.createTime ? 'order' : 'order-grey'}.png);`"></div>
						<div class="txt">创建工单</div>
						<div class="time">{{formData.createTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.dispatchTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.dispatchTime ? 'service' : 'service-grey'}.png);`"></div>
						<div class="txt">派工服务商</div>
						<div class="time">{{formData.dispatchTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.processTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.processTime ? 'service' : 'service-grey'}.png);`"></div>
						<div class="txt">服务商接单</div>
						<div class="time">{{formData.processTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.siteDispatchTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.siteDispatchTime ? 'service' : 'service-grey'}.png);`"></div>
						<div class="txt">服务商派工</div>
						<div class="time">{{formData.siteDispatchTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.siteProcessTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.siteProcessTime ? 'engineer' : 'engineer-grey'}.png);`"></div>
						<div class="txt">工程师接单</div>
						<div class="time">{{formData.siteProcessTime}}</div>
					</li>
					<!-- <li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.dropInTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.dropInTime ? 'engineer' : 'engineer-grey'}.png);`"></div>
						<div class="txt">工程师上门</div>
						<div class="time">{{formData.dropInTime}}</div>
					</li> -->
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.endTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.endTime ? 'order' : 'order-grey'}.png);`"></div>
						<div class="txt">工单完成</div>
						<div class="time">{{formData.endTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.settleTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.settleTime ? 'order' : 'order-grey'}.png);`"></div>
						<div class="txt">工单结算</div>
						<div class="time">{{formData.settleTime}}</div>
					</li>
					<li class="arrow">
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.settleTime ? 'arrow' : 'arrow-grey'}.png);`"></div>
					</li>
					<li>
						<div class="pic" :style="`background-image: url(${baseUrl}images/${formData.settleTime ? 'finish' : 'finish-grey'}.png);`"></div>
						<div class="txt">已完成</div>
						<div class="time">{{formData.settleTime}}</div>
					</li>
				</ul>
			</template>
			<template #feedImgs>
				<div v-for="(itm,index) in formData.feedImgs" :key="index" v-if="formData.feedImgs.length">
					<avue-upload v-model="formData.feedImgs[index]" list-type='picture-card' disabled v-if="itm.length"></avue-upload>
				</div>
			</template>
		</avue-form>
		<template #footer v-if="title == '详情' ? false : true">
		  <span class="avue-dialog__footer">
				<el-button icon="el-icon-circle-plus" type="primary" @click="submitForm">保 存</el-button>
		    <el-button icon="el-icon-circle-close" @click="open = false">取 消</el-button>
		  </span>
		</template>
	</el-dialog>
	
	<!-- 派工 -->
	<el-dialog
	  :title="`派工`"
	  v-model="dispatchOpen"
		v-if="dispatchOpen"
	  width="500px"
		:close-on-click-modal="false"
	  append-to-body>
		<Dispatch :selectionList="selectionList" @childSubmit="childSubmit"></Dispatch>
	</el-dialog>
	
	<!-- 过程反馈 -->
	<el-dialog
	  :title="`过程反馈`"
	  v-model="feedbackPOpen"
		v-if="feedbackPOpen"
	  width="800px"
		:close-on-click-modal="false"
		:align-center="true"
	  append-to-body>
		<el-timeline>
			<el-timeline-item
				v-for="(activity, index) in feedbackList"
				:key="index"
				type='primary'
				placement="top"
				:timestamp="activity.feedbackTime"
			>
				反馈内容：{{ activity.feedback }}
			</el-timeline-item>
		</el-timeline>
	</el-dialog>

	<!-- 回访 -->
	<el-dialog
	  :title="`回访`"
	  v-model="feedbackOpen"
		v-if="feedbackOpen"
	  width="500px"
		:close-on-click-modal="false"
		:align-center="true"
	  append-to-body>
		<Feedback :obj="childObj" @childSubmit="childSubmit"></Feedback>
	</el-dialog>
	
	<!-- 结算 -->
	<el-dialog
	  :title="`结算`"
	  v-model="settlementOpen"
		v-if="settlementOpen"
	  width="500px"
		:close-on-click-modal="false"
		:align-center="true"
	  append-to-body>
		<Settlement :obj="childObj" @childSubmit="childSubmit"></Settlement>
	</el-dialog>
</template>

<script> 
	import NProgress from 'nprogress';
	import 'nprogress/nprogress.css';
	import func from '@/utils/func';
	import { exportBlob } from '@/api/common';
	import { getToken } from '@/utils/auth';
	import { downloadXls } from '@/utils/util';
	import {dateNow} from "@/utils/date";
  import {getList, getDetail, add, update, remove, receiveOrder, listFeedback} from "@/api/order/order";
  import {sendThis} from "@/option/order/order";
  import {mapGetters} from "vuex";
	import Dispatch from "./componets/dispatch.vue"
	import Feedback from "./componets/feedback.vue"
	import Settlement from "./componets/settlement.vue"
  export default {
		meta:'allOrder',
		props:{
			orderStatus:{
				type:String,
				default:'',//1.待派工 2.服务中 3.待回访 4.待结算 5.已完成 6.无效工单 7.取消工单
			},
			orderSiteStatus:{
				type:String,
				default:'',//0尚未指派给服务商 1待服务商接单 2服务商已拒单 3待服务商派工 4待工程师接单 5待上门 6服务中 7已完工 8派工取消 9无效工单
			}
		},
    data() {
      return {
				baseUrl:import.meta.env.VITE_APP_BASE,
				query: {},
				loading: false,
				page: {
				  pageSize: 10,
				  currentPage: 1,
				  total: 0
				},
				option: {},
				listData: [{}],
				selectionList: [],
        formData: {},
				formOption:{},
				
				title:'',
				open:false,
				tabActive:'first',
				dispatchOpen:false,
				feedbackPOpen:false,
				feedbackList:[],
				feedbackOpen:false,
				settlementOpen:false,
				childObj:{},
      };
    },
		components:{Dispatch, Feedback, Settlement},
    computed: {
      ...mapGetters(["permission","userInfo"]),
			deptId(){
				return this.userInfo.dept_id;//3.服务商 4.平台员工 5.服务商人员
			},
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    created(){
			sendThis(this);
    },
		activated() {
			this.onLoad();
		},
    methods: {
			/** 平台端查看所有服务反馈 **/
			getFeedbackList(orderId){
				listFeedback({orderId:orderId}).then(res=>{
					this.feedbackList = res.data.data;
				});
			},
			handleTab(e){
				this.tabActive = e.props.name;
				sendThis(this);
			},
			currentChange(currentPage){
			  this.page.currentPage = currentPage;
			},
			sizeChange(pageSize){
			  this.page.pageSize = pageSize;
			},
			onLoad() {
			  this.loading = true;
				if(this.orderSiteStatus && (this.deptId == '3' || this.deptId == '5')){
					this.query.siteStatus = this.orderSiteStatus;
				}else{
					if(this.orderStatus){
						this.query.status = this.orderStatus;
					}
				}
			  getList(this.page, this.query).then(res => {
			    const data = res.data.data;
			    this.page.total = data.total;
			    this.listData = data.records;
			    this.loading = false;
			    this.selectionClear();
			  });
			},
			searchReset() {
			  this.query = {};
			  this.onLoad();
			},
			searchChange(params, done) {
				if(params.createTime){
					params.createTimeSta = params.createTime[0]
					params.createTimeEnd = params.createTime[1]
				}
				if(params.dispatchTime){
					params.dispatchTimeSta = params.dispatchTime[0]
					params.dispatchTimeEnd = params.dispatchTime[1]
				}
				if(params.siteDispatchTime){
					params.siteDispatchTimeSta = params.siteDispatchTime[0]
					params.siteDispatchTimeEnd = params.siteDispatchTime[1]
				}
				if(params.endTime){
					params.endTimeSta = params.endTime[0]
					params.endTimeEnd = params.endTime[1]
				}
			  this.query = params;
			  this.page.currentPage = 1;
			  this.onLoad();
			  done();
			},
			selectionChange(list) {
			  this.selectionList = list;
			},
			selectionClear() {
			  this.selectionList = [];
			  this.$refs.crud.toggleSelection();
			},
			handleAdd(){
				this.open = true;
				this.title = '新增';
				sendThis(this);
				this.formData={}
			},
			handleView(row){
				let id = row.id;
				getDetail(id).then(res=>{
					this.open = true;
					this.title = '详情';
					res.data.data.bdImgs = res.data.data.bdImgs ? res.data.data.bdImgs.split(",").map(itm=> this.imgUrl + itm) : ''; 
					// res.data.data.feedbackEntity.feedbackImg = res.data.data.feedbackEntity.feedbackImg ? res.data.data.feedbackEntity.feedbackImg.split(",").map(itm=> this.imgUrl + itm) : ''; 
					//反馈图片
					res.data.data.feedImgs = res.data.data.feedImgs.length ? res.data.data.feedImgs.map(itm=> itm ? itm.split(",").map(it=> this.imgUrl + it) : []) : []; 
					console.log("res.data.data.feedImgs",res.data.data.feedImgs);
					this.formData=res.data.data
					sendThis(this);
				})
			},
			handleEdit(){
				let row = this.selectionList[0];
				let id = row.id;
				if((this.deptId == '3' || this.deptId == '5')){
					// if(row.siteStatus == '7' || row.siteStatus == '9'){
					// 	this.$message.warning("当前状态不可编辑");
					// 	return
					// }
				}else{
					if(row.status != '1' && row.status != '2'){
						this.$message.warning("当前状态不可编辑");
						return
					}
				}
				getDetail(id).then(res=>{
					this.open = true;
					this.title = '编辑';
					res.data.data.bdImgs = res.data.data.bdImgs ? res.data.data.bdImgs.split(",").map(itm=> this.imgUrl + itm) : '';
					this.formData=res.data.data
					sendThis(this);
				})
			},
			submitForm(){
				// console.log(this.formData);
				// return
				this.$refs['formData'].validate((valid,done) => {
					if (valid) {
						let formData = JSON.parse(JSON.stringify(this.formData));
						formData.bdImgs = formData.bdImgs ? formData.bdImgs.split(",").map(itm=> itm.replace(this.imgUrl,'')).join(",") : '';
						if(this.title == '新增'){
							add(formData).then(res => {
								this.open = false
								this.onLoad();
								this.$message({
									type: 'success',
									message: '操作成功!',
								});
							}, error => {
								window.console.log(error);
							});
						}else{
							update(formData).then(res => {
								this.open = false
								this.onLoad();
								this.$message({
									type: 'success',
									message: '操作成功!',
								});
							}, error => {
								window.console.log(error);
							});
						}
						done();
					} else {
						console.log('error submit!!');
						return false;
					}
				})
			},
			handleDelete(type) {
				let row = this.selectionList[0];
				if(type == '无效'){
					if((this.deptId == '3' || this.deptId == '5')){
						if(row.siteStatus == '7' || row.siteStatus == '9'){
							this.$message.warning("当前状态不可操作无效");
							return
						}
					}else{
						if(row.status == '5' || row.status == '6'){
							this.$message.warning("当前状态不可操作无效");
							return
						}
					}
					this.$prompt('请输入无效原因：', {
					  confirmButtonText: "确定",
					  cancelButtonText: "取消",
						inputPattern:/^.+$/,
						inputErrorMessage:'请输入无效原因',
					}).then(({value}) => {
						return remove({
							id:this.ids,
							status:'6',
							disableResource:value
						});
					}).then(() => {
						this.onLoad();
						this.$message({
							type: "success",
							message: "操作成功!"
						});
						this.$refs.crud.toggleSelection();
					}).catch(()=>{});
				}else{
					if((this.deptId == '3' || this.deptId == '5')){
						if(row.siteStatus != '9'){
							this.$message.warning("当前状态不可删除");
							return
						}
					}else{
						if(row.status != '6'){
							this.$message.warning("当前状态不可删除");
							return
						}
					}
					this.$confirm('是否确认删除该工单？', {
					  confirmButtonText: "确定",
					  cancelButtonText: "取消",
					  type: "warning"
					}).then(() => {
						return remove({
							id:this.ids,
							status:'7',
						});
					}).then(() => {
						this.onLoad();
						this.$message({
							type: "success",
							message: "操作成功!"
						});
						this.$refs.crud.toggleSelection();
					}).catch(()=>{});
				}
			  
			},
			handleExport() {
			  this.$confirm('是否导出所有数据?', {
			    confirmButtonText: '确定',
			    cancelButtonText: '取消',
			    type: 'warning',
			  }).then(() => {
			    NProgress.start();
			    exportBlob(
			      `/sf/operationOrder/export-operationOrder?${this.website.tokenHeader}=${getToken()}`,
						this.query
			    ).then(res => {
			      downloadXls(res.data, `订单${dateNow()}.xlsx`);
			      NProgress.done();
			    });
			  }).catch(()=>{});
			},
			handleDispatch(){
				if((this.deptId == '3' || this.deptId == '5')){
					if(this.selectionList.find(itm=>itm.siteStatus != '3')){
						this.$message.warning("请选择【待服务商派工】状态派工");
						return
					}
				}else{
					let row = this.selectionList[0];
					if(row.status != '1'){
						this.$message.warning("当前状态不可派工");
						return
					}
				}
				this.dispatchOpen = true;
			},
			childSubmit(e){
				this.dispatchOpen = false;
				this.feedbackOpen = false;
				this.settlementOpen = false;
				if(e == 'cancel'){
					return
				}
				this.onLoad();
				this.$refs.crud.toggleSelection();
			},
			handleReceive(){
				if(this.selectionList.find(itm=>itm.siteStatus != '1')){
					this.$message.warning("请选择【待服务商接单】状态接单");
					return
				}
				this.$confirm('是否确认接单？', {
				  confirmButtonText: "确定",
				  cancelButtonText: "取消",
				  type: "warning"
				}).then(() => {
					return receiveOrder({
						orderIds:this.ids
					});
				}).then(() => {
					this.onLoad();
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					this.$refs.crud.toggleSelection();
				}).catch(()=>{});
			},   
			handleFeedback(){
				let row = this.selectionList[0];
				this.childObj = row;
				this.feedbackOpen = true;
			},
			handleSettlement(){
				let row = this.selectionList[0];
				this.childObj = row;
				this.settlementOpen = true;
			},
		}
  };
</script>

<style>
</style>
