<template>
	<view class="mainBox">
		<uni-nav-bar background-color="#157A2C" color="#fff" fixed="true" statusBar="true" left-icon="back" title="售后需求"
			@clickLeft="back">
		</uni-nav-bar>
		<view class="top-wrapper">
			<uni-section>
				<uni-easyinput @clear="clearSearch" prefixIcon="search" style="width: 460rpx" v-model="searchVal"
					placeholder="关键字">
				</uni-easyinput>
			</uni-section>
			<button class="search_btn" @click="doSearch">搜索</button>
			<image class="menu_icon" @click="showSearch" src="~@/static/pda/menu.svg"></image>
		</view>
		<view class="wrapper">
			<u-list @scrolltolower="scrolltolower" class="listContent">
				<view v-for="(item, index) in tableList" :key="index" style="position: relative;">
					<myCard @del="del(item)" @handleAudit="handleAudit(item)" @handleRevoke="handleRevoke(item)"
						@edit="add('edit',item.id)" @details="add('view',item.id)" :item="item" :index="index+1"
						:columns="columns" :btnList="btnList">
					</myCard>
				</view>
			</u-list>
		</view>
		<view style='margin-top: 20vh;' v-if="tableList.length==0">
			<u-empty iconSize='150' textSize='32' text='暂无数据'>
			</u-empty>
		</view>
		<view class="add" @click="add('add','')">
			<u-icon name="plus" color="#fff"></u-icon>
		</view>


		<ba-tree-picker ref="treePicker" :multiple="false" @select-change="confirm" :localdata="listData" valueKey="id"
			textKey="name" childrenKey="children" />
		<u-toast ref="uToast"></u-toast>

		<u-modal @confirm="handleSubmit" ref="popup" type="center" :show="modalShow" @cancel="modalShow=false"
			:showCancelButton="true" :closeOnClickOverlay="true">
			<view class="popup-content">

				<form>
					<view class="form-item">
						<label class="form-label">*部门</label>
						<u--input placeholder="部门" @click.native="showPicker"
							v-model="addForm.planExecuteGroupName"></u--input>
					</view>
					<view class="form-item">
						<label class="form-label">*计划执行人</label>

						<uni-data-picker v-model="addForm.planExecuteUserId" placeholder="请选择" :localdata="userList"
							@change="industryOnchange">
						</uni-data-picker>
					</view>

				</form>
			</view>
		</u-modal>

		<u-toast ref="uToast"></u-toast>

		<MySearch :show.sync="searchShow" :formItems="formItems" @search="confirmSearch" ref="mySearchRef">
		</MySearch>

	</view>
</template>

<script>
	import {
		getByCode
	} from '@/api/pda/common.js'

	import {
		initDict
	} from '@/utils/utils.js'

	import {
		listOrganizations,
		getUserPage
	} from '@/api/myTicket/index.js'
	import {
		getTableList,
		revokeSalesDemand,
		deleteSalesDemand,
		demanDispatch,
		auditSalesDemand
	} from '@/api/salesServiceManagement/demandList/index.js'
	import myCard from '@/pages/saleManage/components/myCard.vue'
	import {
		processInstanceCreateAPI,
		processInstancePage
	} from '@/api/wt/index.js'

	export default {
		components: {
			myCard,
		},
		watch: {
			fault_level_arr: {
				handler(val) {
					console.log(val);
					this.formItems.find(item => item.prop === 'faultLevel').props.localdata = val
				},
				deep: true
			}
		},
		data() {
			return {
				addForm: {
					planExecuteUserId: '',
					planExecuteUserName: '',
					planExecuteGroupId: '',
					planExecuteGroupName: '',
					id: ''
				},
				modalShow: false,
				userList: [],
				listData: [],
				searchForm: {},
				emptyShow: false,
				searchShow: false,
				fault_level_obj: {},
				fault_level_arr: [],
				formItems: [{
						label: '客户名称：',
						prop: 'contactName',
						component: 'MyInput',
						props: {
							placeholder: '请输入内容',
						}
					},
					{
						label: '编码：',
						prop: 'code',
						component: 'MyInput',
						props: {
							placeholder: '请输入内容',
						}
					},
					{
						label: '客户编码：',
						prop: 'contactCode',
						component: 'MyInput',
						props: {
							placeholder: '请输入内容',
						}
					},
					{
						label: '创建人：',
						prop: 'createUserName',
						component: 'MyInput',
						props: {
							placeholder: '请输入内容',
						}
					},

					{
						label: '故障等级：',
						prop: 'faultLevel',
						component: 'MySelect',
						props: {
							localdata: [],
							dataKey: 'label',
							dataValue: 'value'
						}
					},

					{
						label: '状态：',
						prop: 'demandStatus',
						component: 'MySelect',
						props: {
							localdata: [{
								label: '待提交',
								value: 0
							}, {
								label: '已提交',
								value: 1
							}, {
								label: '已关闭',
								value: 3
							}, {
								label: '已撤回',
								value: 4
							}],
							dataKey: 'label',
							dataValue: 'value',
						}
					},
				],

				tableList: [],
				searchVal: '',
				page: 1,
				size: 10,
				isEnd: false,
				current: {},
				examForm: {
					auditOpinion: '',
					auditResult: '',
					id: ''
				},

				btnList: [{
						name: '详情',
						apiName: 'details',
						btnType: 'primary',
						type: '2',
						pageUrl: '',
					}, {
						name: '修改',
						apiName: 'edit',
						btnType: 'primary',
						type: '2',
						pageUrl: '',
						judge: [{
							authorities: '',
						}, {
							key: 'demandStatus',
							fn: (row) => {
								if (row?.afterSalesType == 3) {
									return (
										(row?.approvalResult == 0 || row?.approvalResult == 3) &&
										row?.demandStatus != 2
									);
								} else {
									return row?.demandStatus == 0;
								}
							},

						}],
					},
					{
						name: '删除',
						apiName: 'del',
						btnType: 'error ',
						type: '2',
						pageUrl: '',
						judge: [{
							authorities: '',
						}, {
							fn: (row) => {
								if (row?.afterSalesType == 3) {
									return (
										(row?.approvalResult == 0 || row?.approvalResult == 3) &&
										row?.demandStatus != 2
									);
								} else {
									return row?.demandStatus == 0;
								}
							},
						}],
					}, {
						name: '提交',
						apiName: 'handleAudit',
						btnType: 'primary',
						type: '2',
						pageUrl: '',
						judge: [{
							authorities: '',
						}, {
							fn: (row) => {
								if (row?.afterSalesType == 3) {
									return (
										(row?.approvalResult == 0 || row?.approvalResult == 3) &&
										row?.demandStatus != 2
									);
								} else {
									return row?.demandStatus == 0;
								}
							},
						}],
					},

				],
				columns: [
					[{
						label: '名称：',
						prop: 'name',
						type: 'title',
						className: 'perce100',
					}],
					[{
						label: '编码：',
						prop: 'code'
					}, {
						label: '客户编码：',
						prop: 'contactCode'
					}],
					[{
						label: '客户名称：',
						prop: 'contactName'
					}, {
						label: '故障等级：',
						prop: 'faultLevel',
						formatter: (row) => {
							return this.fault_level_obj && this.fault_level_obj[row.faultLevel] || ''
						}
					}],
					[{
						label: '创建人：',
						prop: 'createUserName'
					}, {
						label: '创建时间：',
						prop: 'createTime',
					}],
					[{
						label: '状态：',
						prop: 'demandStatus',
						formatter: (row) => {
							const reviewStatus = {
								0: '未提交',
								1: '审核中',
								2: '已审核',
								3: '审核不通过'
							}
							let cellValue = row.demandStatus;
							if (row.afterSalesType == 3) {
								return cellValue == 2 ? '已关闭' : reviewStatus[row.approvalResult];
							} else {
								return cellValue == 0 ?
									'待提交' :
									cellValue == 1 ?
									'已提交' :
									cellValue == 2 ?
									'已关闭' :
									cellValue == 3 ?
									'已完成' :
									'';
							}
						}
					}],
					[{
						label: '操作：',
						prop: 'action',
						type: 'action',
						className: 'perce100',
					}],

				]
			}
		},

		onReachBottom() {
			console.log('123');
			this.getList()
		},
		onLoad() {
			this.getDict()
			this.getDept()
		},
		onShow() {
			this.doSearch();
		},


		methods: {
			handleAudit(row) {
				this.current = row
				if(row.afterSalesType==3){
					this.listSubmit()
				}else{
					this.modalShow = true
				}
				
				console.log(this.modalShow, 'dsds')
			},

			
			// 显示选择器
			showPicker() {
				this.$refs.treePicker._show();
			},
			// btnShow(row) {

			// },
			confirm(data, name) {

				this.addForm.planExecuteGroupName = name
				this.addForm.planExecuteGroupId = data[0]
				this.addForm.planExecuteUserName = ''
				this.addForm.planExecuteUserId = ''
				this.getUser(data[0])
			},
			industryOnchange(obj) {
				this.addForm.planExecuteUserName = obj.detail.value[0].text

			},
			getDept() {
				listOrganizations(1).then(data => {
					this.listData = data
				})
			},
			getUser(deptCode) {
				getUserPage({
					pageNum: 1,
					size: -1,
					groupId: deptCode
				}).then(data => {
					this.userList = data.list.map(item => {
						item.text = item.name
						item.value = item.id
						return item
					})
				})

			},
			handleSubmit() {
				auditSalesDemand({
						...this.addForm,
						submitSource: 3,
						id: this.current.id
					})
					.then((res) => {
						if (res) {
							this.modalShow = false
							this.$refs.uToast.show({
								type: "success",
								message: "操作成功",
							})
							this.doSearch();
						}
					})
					.catch((err) => {
						this.modalShow = false
					});
			},
			async getDict() {
				let res = await getByCode('fault_level')
				let [arr, obj] = initDict(res)
				this.fault_level_obj = obj
				this.fault_level_arr = arr
				console.log(this.fault_level_obj);
				// console.log(arr, obj);
			},

			doSearch() {
				this.isEnd = false
				this.page = 1
				this.getList()
			},
			//获取列表信息
			getList() {
				if (this.isEnd) {
					this.$refs.uToast.show({
						message: "暂无更多数据",
						duration: 1000
					})
					return
				}
				uni.showLoading({
					title: '加载中'
				})
				let data = {
					pageNum: this.page,
					size: this.size,
					keyWord: this.searchVal,
					...this.searchForm
				}
				getTableList(data).then(res => {
					if (this.page === 1) {
						this.tableList = res.list
						if (this.tableList.length === 0) {
							this.emptyShow = true
						}
					} else {
						this.tableList.push(...res.list)
					}
					this.page += 1
					this.isEnd = this.tableList.length >= res.count
					uni.hideLoading();
				}).catch((e) => {
					uni.hideLoading()
				})
			},

			hidePopup() {
				this.$refs.popup.close();
				this.examForm = {
					auditOpinion: '',
					auditResult: '',
					id: ''
				};
			},

			async listSubmit() {
				try {
					//后台不提供接口
					let list = await processInstancePage({
						pageNo: 1,
						pageSize: 1,
						reset: true,
						key: 'after_sale_quality_issues_feedback'
					})
					let params = {
						businessId: this.current.id,
						businessKey: 'after_sale_quality_issues_feedback',
						formCreateUserId: this.current.createUserId,
						processDefinitionId: list?.list[0]?.processDefinition.id,
						variables: {
							businessCode: this.current.code,
							businessName: this.current.name,
							businessType: '质量问题反馈',
						},
					}

					await processInstanceCreateAPI(params)
					uni.showModal({
						title: `提交成功`,
						content: '',
						confirmText: '确认',
						showCancel: false, // 是否显示取消按钮，默认为 true
						success: () => {
							this.doSearch()
						}

					})


				} catch {

				}

			},
			// 撤回
			async handleRevoke(row) {
				const res = await uni.showModal({
					title: '确认撤回',
					content: '确定要撤回该条数据吗?',
					confirmText: '撤回',
					confirmColor: '#FF4D4F',
				});
				if (res[1].confirm) {
					const data = await revokeSalesDemand({
						id: row.id
					});
					if (!data) return
					this.$refs.uToast.show({
						type: "success",
						message: "操作成功",
					})
					this.doSearch();
				} else if (res.cancel) {
					console.log('用户取消');
				}

			},
			add(type, id) {
				uni.navigateTo({
					url: `/pages/salesServiceManagement/demandList/add?type=${type}&id=${id}`
				})
			},
			scrolltolower() {
				if (this.isEnd) {
					return
				}
				this.getList();
			},
			async del(row) {
				const res = await uni.showModal({
					title: '确认删除',
					content: '确定要删除该条数据吗?',
					confirmText: '删除',
					confirmColor: '#FF4D4F',
				});
				if (res[1].confirm) {
					const data = await deleteSalesDemand([row.id])
					if (!data) return
					this.$refs.uToast.show({
						type: "success",
						message: "操作成功",
					})
					this.doSearch();
				} else if (res.cancel) {
					console.log('用户取消');
				}
				// deleteInformation([item.id]).then(res => {
				// 	this.isEnd = false
				// 	this.page = 1
				// 	this.$refs.uToast.show({
				// 		type: "success",
				// 		message: "操作成功",
				// 	})
				// 	this.getList(this.where)
				// })
			},


			clearSearch() {
				this.searchVal = ''
				this.doSearch()
			},
			showSearch() {
				this.searchShow = true
			},
			confirmSearch(e) {
				console.log(e);
				let data = JSON.parse(JSON.stringify(e))
				this.searchForm = data
				this.doSearch()
			},



		}
	}
</script>

<style lang="scss" scoped>
	.add {
		width: 96rpx;
		height: 96rpx;
		border-radius: 48rpx;
		background: #3c9cff;
		position: fixed;
		bottom: 100rpx;
		right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.wrapper {}

	.top-wrapper {
		background-color: #fff;
		display: flex;
		width: 750rpx;
		height: 88rpx;
		padding: 16rpx 32rpx;
		align-items: center;
		gap: 16rpx;

		/deep/.uni-section {
			margin-top: 0px;
		}

		/deep/.uni-section-header {
			padding: 0px;

		}

		.search_btn {
			width: 120rpx;
			height: 70rpx;
			line-height: 70rpx;
			padding: 0 24rpx;
			background: $theme-color;
			font-size: 32rpx;
			color: #fff;
			margin: 0;
			margin-left: 26rpx;
		}

		.menu_icon {
			width: 44rpx;
			height: 44rpx;
			margin-left: 14rpx;
		}
	}
</style>