<template>
	<div class="app-container">
		<!-- @queryBtnClick="handleQueryClick"  -->
		<page-search 
			:searchFormConfig="searchFormConfig" 
			@resetBtnClick="handleNewResetClick"
			@queryDataInfo="handleQueryData"
			:initParams="initParams" >
			<!-- <template #otherchildslot>
				<el-select
					v-model="createuser"
					clearable
					filterable
					remote
					reserve-keyword
					placeholder="请输入创建人"
					:remote-method="remoteMethod"
					:loading="loading"
					style="width: 100%;"
				>
					<el-option
					v-for="item in options"
					:key="item.value"
					:label="item.title"
					:value="item.value"
					/>
				</el-select>
			</template> -->
			<!-- <template #otherchildslot2>
				<el-select
					v-model="dealuser"
					
					filterable
					remote
					clearable
					reserve-keyword
					placeholder="请输入受理人"
					:remote-method="remoteMethod"
					:loading="loading"
					style="width: 100%;"
				>
					<el-option
					v-for="item in options"
					:key="item.value"
					:label="item.title"
					:value="item.value"
					/>
				</el-select>
			</template> -->
		</page-search>
		<page-content ref="pageContentRef" :initParams="initParams" :contentTableConfig="listType == 11 ? warnContentTableConfig : listType == 12 ? VisitedBackContentTableConfig : contentTableConfig"
			pageName="/order/workorder" :isExport="isExport" @newBtnClick="handleNewData" @editBtnClick="handleEditData">
			<template #workordercode="scope">
				<a :style="{color: scope.row.showColor ? scope.row.showColor : 'blue'}" @click="openWorkHandle(scope.row)">{{ scope.row['workordercode'] }}</a>
			</template>
			<template #source="scope">
				<div>
					{{ `${scope.row['source']}（${scope.row['projectname']}）` }}
				</div>
			</template>
			<template #workorderstatename="scope">
				<el-tag v-if="scope.row.workorderstatename" effect="plain"
					:type="tagTypeFn(scope.row.workorderstatename)">{{ scope.row.workorderstatename }}</el-tag>
			</template>

			<template #warnInfosSlot="scope">
				<span v-for="(item,index) in scope.row.warnInfos" :key="index">
					{{`${ item.surveyName || '' }(${item.totalScore})`}}
				</span>
			</template>

			<template #handlerOther="scope">
				<el-button v-for="(item ,index) in orderBtnFilter(scope.row,initParams.listType)" :key="index" type="text"
					@click="btnClickEvents(item,scope.row)">
					{{ item.text }}
				</el-button>
			</template>
		</page-content>
		<page-modal :defaultInfo="defaultInfo" :otherInfo="otherInfo" ref="pageModalRef" :pageName="pageNameUrl"
			:modalConfig="resultConfigData" @dataChange="getConsultData" @submit="submit"></page-modal>
		

		<!-- 添加 -->
		<el-dialog
			v-model="dialogAddWorkorder"
			:title="modalTitle"
			center
			width="70%"
			:modal="true"
			:show-close="true"
		>
			<page-order :getDefaultInfo="postDefaultInfo" @refreshOrder="submitRefresh()"></page-order>
		</el-dialog>

	</div>
</template>

<script>
	import { defineComponent, onMounted,onActivated,inject  } from 'vue'
	import moment from 'moment';

	import PageSearch from '@/components/page-search'
	import PageContent from '@/components/page-content'
	import PageModal from '@/components/page-modal'
	import PageOrder from '@/components/page-order';

	import { searchFormConfig } from './config/search.config'
	import { contentTableConfig } from './config/content.config'
	import { warnContentTableConfig } from './config/warn-content.config'
	import { VisitedBackContentTableConfig } from './config/visited-back-content.config'

	import { usePageSearch } from '@/hooks/use-page-search'
	import { usePageModal } from '@/hooks/use-page-modal'


	import { getToken } from '@/utils/auth'
	import { orderBtnFilter, getModalData } from '@/utils/operationBtn'
	import { useRoute,  useRouter} from 'vue-router'
	import useSelectStore from '@/store/commonSelect/common'

	import {
		getPageListData,
		deletePageData,
		createPageData,
		editPageData
	} from '@/api/main/system/system'
	
	export default defineComponent({
		name: 'OrderList',
		components: {
			PageSearch,
			PageContent,
			PageModal,
			PageOrder
		},
		setup() {
			let [pageContentRef, handleResetClick, handleQueryClick] = usePageSearch()
			const { proxy } = getCurrentInstance();
			
			const templateForm = ref({})
			const pageNameUrl = ref('')
			const workordercode = ref('')
			const route = useRoute();
			const router = useRouter();
			const listType = ref(route.query.listType || 0);
			const isExport = ref((listType.value == 0 || listType.value == 6)?true:false)  
			const postDefaultInfo = ref({})
			const otherInfo = ref({})
			const initParams = ref({
				listType: listType.value,
			})
			const dialogAddWorkorder = ref(false)
			const modalTitle = ref('添加工单')
			function submitRefresh() {
				dialogAddWorkorder.value = false
				init()
			}
			const dealDeptId = ref()
			const resultConfigData = ref({})

			// const list = ref([])
			const options = ref([])
			// const createuser = ref([])
			// const dealuser = ref([])
			const loading = ref(false)
			const remoteMethod = (query) => {
				if (query) {
					console.log(query)
					// console.log(list.value)
					loading.value = true
					// setTimeout(() => {
					// 	loading.value = false
					// 	options.value = list.value.filter((item) => {
					// 		return item.title.toLowerCase().includes(query.toLowerCase())
					// 	})
					// }, 200)
				} else {
					options.value = []
				}
			}

			onMounted(() => {
				init()
			})  
			onActivated(() => {
				init()
			})
			const init = () => {
				// list.value = useSelectStore().workorderUserList

				const params = {
					listType: listType.value,
					// workordercode:route.query.workordercode
				}
				// if (route.query.workordercode ) {
				// 	params.workordercode = route.query.workordercode
				// }
				// console.log(route.query.listType)
				// if () {
				// 	debugger
				// 	isExport.value = true
				// } else {
				// 	isExport.value = false
				// }
				pageContentRef.value.getPageData(params)
			}
			
			function handleQueryData(params) {
				console.log(params,'handleQueryData')
				
				
				// if (createuser.value) {
				// 	params.createuser = createuser.value
				// }else {
				// 	delete params.createuser
				// }

				// if (dealuser.value) {
				// 	params.dealuser = dealuser.value
				// }else {
				// 	delete params.dealuser
				// }

				console.log(params)
				pageContentRef.value.getPageData(params)
			}
			function submit() {
				init()
			}
			function getConsultData(item) {
				if (selectCascade(item.dealdept, dealDeptId.value)) {
					useSelectStore().getSelectCascade(item.dealdept).then((res) => {
						const evaluateUserItem = resultConfigData.value.formItems.find(
							(item) => item.field === 'dealuser'
						)
						evaluateUserItem.options = res
						
					})
				}
				dealDeptId.value = item.dealdept
			}
			// 处理弹出框
			function openWorkHandle(rowData) { 
				let type
				if (listType.value*1 === 1) {
					type = 'wddcl'
				} else if ((listType.value*1 === 4 || listType.value*1 === 11) && rowData.workorderstate + '' == '5000') {
					type = 'ybdhf'
				} else if (listType.value*1 === 0) {
					type = 'djb'
				}
				let query = {
					workordercode : rowData.workordercode,
					type,
					listType: listType.value*1
				}
				sessionStorage.setItem('workQuery', JSON.stringify(query))
				router.push({ path : '/workHandle' }) 
			}
			function btnClickEvents(item, data) {
				console.log(item, data, 'btnClickEvents');
				workordercode.value = data.workordercode
				if (item.eventName === 'editCommonBtn') {
					modalTitle.value = item.text
					postDefaultInfo.value = data
					dialogAddWorkorder.value =true
				} 
				
				if (item.popoutType === 'newTab') {
					openWorkHandle(data)
				} else if (item.popoutType === 'model') {
					modalTitle.value = item.text
					resultConfigData.value = getModalData(item).config
					defaultInfo.value = data
					defaultInfo.value.code = data.workordercode
					otherInfo.value = {
						code: data.workordercode
					}
					console.log(defaultInfo.value.code, 'defaultInfo.value.code')
					pageModalRef.value.dialogVisible = true
					pageNameUrl.value = getModalData(item).pageNameUrl
				} else if (item.popoutType === 'confirm') {
					confirmHandle(item, workordercode.value, getModalData(item).pageNameUrl,data)
				} else if (item.popoutType === 'prompt') {
					promptHandle(item, workordercode.value, getModalData(item).pageNameUrl,data)
				}
			}
			function promptHandle(item, code, apiUrl,data) {
				proxy.$modal.prompt('确定' + item.text + '吗?').then((e) => {
					const params = {
						code:code,
						reason: e.value
					}
					if (item.eventName === 'refuseCommonBtn') {
						params.agree = 0
						editPageData(apiUrl, params).then((data) => {
							proxy.$modal.msgSuccess('操作成功');
							init()
						});
					} else {
						editPageData(apiUrl, params).then((data) => {
							proxy.$modal.msgSuccess('操作成功');
							init()
						});
					}
					
				});
			}
			function confirmHandle(item, code, apiUrl,data) {
				const params = { code }
				if (item.eventName ===  'withdrawCommonBtn') {
					params.agree = 1
				}
				proxy.$modal.confirm('确定' + item.text + '吗?').then((e) => {
					editPageData(apiUrl, params).then((data) => {
						proxy.$modal.msgSuccess('操作成功');
						init()
					});
				});
			}
			const selectCascade = (value, oldValue) => {
				let returnState = false
				if (value) {
					if (!(oldValue && (value.toString() === oldValue.toString()))) {
						oldValue = value
						returnState = true
					}
				}
				return returnState
			}

			// 1.处理逻辑
			const handleNewResetClick = ()=>{
				// createuser.value = ''
				// dealuser.value = ''
				init()
			}
			const newCallback = () => {}
			const handleNewData = () => {
				postDefaultInfo.value = {}
				dialogAddWorkorder.value =true
			}
			const editCallback = () => {
				console.log(defaultInfo.value)
			}

			// 3.调用hook获取公共变量和函数
			const [pageModalRef, defaultInfo, handleEditData] =
				usePageModal(newCallback, editCallback)
			return {
				VisitedBackContentTableConfig,
				listType,
				remoteMethod,
				// list,
				options,
				// createuser,
				// dealuser,
				loading,
				isExport,
				handleQueryData,
				handleNewResetClick,
				postDefaultInfo,
				pageNameUrl,
				openWorkHandle,
				dialogAddWorkorder,
				modalTitle,
				submitRefresh,
				confirmHandle,
				resultConfigData,
				submit,
				workordercode,
				selectCascade,
				dealDeptId,
				getConsultData,
				btnClickEvents,
				orderBtnFilter,
				initParams,
				proxy,
				searchFormConfig,
				warnContentTableConfig,
				contentTableConfig,
				pageContentRef,
				handleResetClick,
				handleQueryClick,
				pageModalRef,
				defaultInfo,
				otherInfo,
				handleNewData,
				handleEditData
			}
		}
	})
</script>