<template>
	<view class="zd_container">
		<!-- <nav-bar title="呼叫套轴"></nav-bar> -->
		<nav-bar :title="title"></nav-bar>
		<view class="add_content">
			<view class="filter-card">
				<view class="zd-row filter-head">
					<view class="zd-row filter-title"><text></text>作业条件</view>
					<view class="iconfont icon_down" :class="{'icon_up': !collapse}" @tap="toCollapse">&#xe65d;</view>
				</view>
				<view v-if="!collapse">
					<view class="filter-grid">
						<view class="filter_field">
							<view class="filt_label">区域</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="index1" :localdata="options1" @change="selectChange1"></uni-data-select>
							</view>
						</view>
						<view class="filter_field">
							<view class="filt_label">位置</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="index2" :localdata="options2" @change="selectChange2"></uni-data-select>
							</view>
						</view>
						<view class="filter_field filter-field-full">
							<view class="filt_label">左管</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="upL" :searchInput="true" :localdata="newaxis1" @handleChange="handleChange1" @showSelector="showSelector1"></uni-data-select>
							</view>
						</view>
						<view class="filter_field filter-field-full">
							<view class="filt_label">右管</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="upR" :searchInput="true" :localdata="newaxis2" @handleChange="handleChange2" @showSelector="showSelector2"></uni-data-select>
							</view>
						</view>
						<view class="filter_field">
							<view class="filt_label">尺寸</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="index3" :localdata="options3" @change="selectChange3"></uni-data-select>
							</view>
						</view>
						<view class="filter_field">
							<view class="filt_label">代数</view>
							<view class="filter_input_wraper filt_input_wraper">
								<uni-data-select v-model="index4" :localdata="options4" @change="selectChange4"></uni-data-select>
							</view>
						</view>
						<view class="filter_field filter-field-full">
							<view class="filt_label">数量</view>
							<view class="filter_input_wraper filt_input_wraper">
								<NumberInput
								v-model="qty"
								input-class="filter_input"
								mode="integer"
								/>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="plan-panel">
				<view class="panel-head">
					<view class="zd-row filter-head">
						<view class="zd-row filter-title">呼叫计划</view>
						<view class="zd-row">
							<view class="zd-row icon-shuaxin-wrap" @tap="handleRefresh">
								<view class="iconfont icon_shuaxin" :class="{'spin-icon': refreshing}">&#xe650;</view>
								<text>&nbsp;刷新</text>
							</view>
						</view>
					</view>
					<view class="stats">
						<view class="stat">
							<view class="stat_num">{{planSize}}</view>
							<text>呼叫总数</text>
						</view>
						<view class="stat">
							<view class="stat_num">{{canUsePointCount}}</view>
							<text>可用点位数</text>
						</view>
						<view class="stat">
							<view class="stat_num">{{remainingCount}}</view>
							<text>可用空闲位数</text>
						</view>
					</view>
				</view>
				<view class="zd-row list-toolbar">
					<text class="resultText">{{resultText}}</text>
					<view class="zd-row seg">
						<button class="seg_all" :class="{'on': state === 'all'}" @tap="state='all'">全部</button>
						<button class="seg_on" :class="{'on': state === '02'}" @tap="state='02'">已套轴</button>
						<button class="seg_waiting" :class="{'on': state === '01'}" @tap="state='01'">待套轴</button>
					</view>
				</view>
				<view class="plan-list">
					<block v-for="(item, index) in filteredPlanList" :key="index">
						<view class="plan-item" :class="{'open': item._expand}">
							<view class="plan-main">
								<view class="plan-left">
									<view class="plan-code">{{ item.paper_tube_or_FRP === '1' ? item.paper_tube_description : item.frp_description }}</view>
									<view class="plan-sub">
										<text>管芯尺寸 · {{ item.qzz_size }}</text>
										<text>管芯代数 · {{ item.qzz_generation }}</text>
									</view>
								</view>
								<view class="plan-right">
									<text class="status" :class="item.status==='01' ? 'waiting' : 'fitted'">
										{{ item.status === '01' ? '待套轴' : '已套轴'}}
									</text>
									<view class="expand-btn" @tap="toggleExpand(item)">
										<text>{{ item._expand ? '收起明细' : '查看明细' }}</text>
										<view class="iconfont" :class="{'icon‑rotate': item._expand}">&#xe65e;</view>
									</view>
								</view>
							</view>
							<view class="plan-details">
								<text>呼叫时间：{{ item.call_time }}</text>
								<text>管芯重量：{{ item.paper_weight }}</text>
								<text>是否套轴完成：{{ item.is_child_tz_ok === 1 ? '是' : '否' }}</text>
								<text>呼叫人：{{item.material_type}}</text>
							</view>
						</view>
					</block>
					<view v-if="!filteredPlanList.length" class="list_empty">
						<view class="iconfont icon_local">&#xe61f;<br /><text>请先选择位置<br />系统将加载该位置的呼叫计划</text></view>
					</view>
				</view>
			</view>
		</view>
		<view class="zd-row submitbar">
			<button class="zd-col-6 btn-submit btn-default" @tap="clearUp">清空</button>
			<button class="zd-col-15 btn-submit btn-success" :class="{'btn-info': !index1 || !index2 || (!upL && !upR) || !index3 || !index4 || !qty}" :disabled="disabled" @tap="openConfirmModal">呼叫套轴</button>
		</view>
		<view v-if="confirmModalShow" class="zd-row jccenter confirm-modal-mask" @tap="closeConfirmModal">
			<view class="flex-column confirm-modal" @tap.stop>
				<view class="iconfont icon_right">&#xe66b;</view>
				<view class="modal-title">确认呼叫套轴</view>
				<view class="modal-desc">请核对本次呼叫信息，确认后将提交</view>
				<view class="info-block">
					<view class="info-row">
						<text class="info-label">位置</text>
						<text class="info-val">{{ index2Label || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">管芯规格</text>
						<text class="info-val">{{ getAxisLabel() || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">尺寸</text>
						<text class="info-val">{{ index3Label || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">数量</text>
						<text class="info-val info-val-q">{{ qty || 0 }}</text>
					</view>
				</view>
				<view class="modal-buttons">
					<button class="btn-cancel" @tap="closeConfirmModal">取消</button>
					<button class="btn-confirm" @tap="handleConfirmCall">确认呼叫</button>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	import NavBar from '@/components/NavBar.vue'
	import SearchBox from '@/components/SearchBox.vue'
	import NumberInput from '@/components/NumberInput.vue'
	import {queryProductArea, queryDeviceByarea} from '@/utils/getData2.js'
	import {slitXnplan, slitXnarea, paperQueryPaperMaterial, getBindXnPlan} from '@/utils/getData3.js'
	export default {
		components: {
			NavBar,
			SearchBox,
			NumberInput
		},
		data() {
			return {
				title: '',
				collapse: false,
				state: 'all',
				refreshing: false,
				options1: [],
				index1: '',
				options2: [],
				index2: '',
				options3: [{text: '3寸', value: '3'}, {text: '6寸', value: '6'}],
				index3: '',
				options4: [{text: '4代', value: '4'}, {text: '5代', value: '5'}],
				index4: '',
				axis: [],
				newaxis1: [],
				newaxis2: [],
				upL: '',
				upR: '',
				qty: null,
				disabled: false,
				disabled1: false,
				planList: [],
				planSize: 0,
				remainingCount: 0,
				canUsePointCount: 0,
				confirmModalShow: false,
				index2Label: '',
				index3Label: '',
			};
		},
		computed: {
			resultText() {
				if (!this.index2) {
					return '选择位置后加载'
				}
				const posItem = this.options2.find(o => o.value === this.index2)
				const posLabel = posItem ? posItem.text : this.index2
		
				const list = this.planList
				return `${posLabel} · 共 ${list.length} 个`
			},
			filteredPlanList() {
				if (this.state === 'all') {
					return this.planList
				} else if (this.state === '01') {
					return this.planList.filter(p => p.status === '01')
				} else if (this.state === '02') {
					return this.planList.filter(p => p.status !== '01')
				}
				return []
			},
			statTotal() {
				return this.planList.length
			},
			statWaiting() {
				return this.planList.filter(p => p.status === '01').length
			},
			statFitted() {
				return this.statTotal - this.statWaiting
			}
		},
		onLoad (options) {
			this.title = options.title
			this._queryProductArea()
			this._paperQueryPaperMaterial()
		},
		methods: {
			toCollapse () {
				this.collapse = !this.collapse
			},
			/** 生产区域下拉框查询 */
			async _queryProductArea () {
				let res = await queryProductArea()
				this.options1 = [...res.data]
			},
			async _slitXnarea (e) {
				try {
					let res = await slitXnarea(e)
					if (res) {
						const list = res.map(el => {
							return {
								text: el.label,
								value: el.value
							}
						})
						this.options2 = list
					}
				} catch (e) {
					this.options2 = []
				}
			},
			async _getBindXnPlan (e) {
				try {
					let res = await getBindXnPlan(e)
					if (res && res.status === 200) {
						this.planSize = res.planSize || 0
						this.canUsePointCount = res.canUsePointCount || 0
						this.remainingCount = res.remainingCount || 0
						this.planList = res.plans.map(p=>{
							return { ...p, _expand:false }
						})
					} else {
						this.planSize = 0
						this.canUsePointCount = 0
						this.remainingCount = 0
						this.planList = []
					}
				} catch (e) {
					this.planSize = 0
					this.canUsePointCount = 0
					this.remainingCount = 0
					this.planList = []
				}
			},
			selectChange1(e) {
				this.index1 = e
				if (e) {
					this._slitXnarea(e)
				} else {
					this.options2 = []
				}
			},
			selectChange2(e) {
				this.index2 = e
				if (e) {
					this._getBindXnPlan(e)
				} else {
					this.planSize = 0
					this.canUsePointCount = 0
					this.remainingCount = 0
					this.planList = []
				}
			},
			selectChange3(e) {
				this.index3 = e
			},
			selectChange4(e) {
				this.index4 = e
			},
			async _paperQueryPaperMaterial () {
				let res = await paperQueryPaperMaterial()
				this.axis = [...res.rows]
			},
			clearUp () {
				this.index1 = ''
				this.index2 = ''
				this.upL = ''
				this.upR = ''
				this.index3 = ''
				this.index4 = ''
				this.qty = null
				this.disabled = false
				this.disabled1 = false
				this.state = 'all',
				this.refreshing = false
				this.planSize = 0
				this.canUsePointCount = 0
				this.remainingCount = 0
				this.planList = []
			},
			openConfirmModal () {
				this.disabled = true
				if (!this.index1 || !this.index2 || (!this.upL && !this.upR) || !this.index3 || !this.index4 || !this.qty) {
					this.disabled = false
					return
				}
				const opt2 = this.options2.find(o=>o.value === this.index2)
				this.index2Label = opt2 ? opt2.text : ''
				const opt3 = this.options3.find(o=>o.value === this.index3)
				this.index3Label = opt3 ? opt3.text : ''
				this.confirmModalShow = true
			},
			closeConfirmModal(){
				this.confirmModalShow = false
				this.disabled = false
			},
			getAxisLabel(){
				let arr = []
				if(this.upL) {
					const l = this.newaxis1.find(x=>x.value === this.upL)
					l && arr.push(l.text + '（左）')
				}
				if(this.upR) {
					const r = this.newaxis2.find(x=>x.value === this.upR)
					r && arr.push(r.text + '（右）')
				}
				return arr.join(' / ')
			},
			handleConfirmCall(){
				this.confirmModalShow = false
				this._slitXnplan()
			},
			async _slitXnplan () {
				let upLT = ''
				let upRT = ''
				this.axis.map(el => {
					if (el.value === this.upL) {
						upLT = el.text
					}
					if (el.value === this.upR) {
						upRT = el.text
					}
				})
				try {
					let res = await slitXnplan(this.index1, this.index2, upLT, this.upL, upRT, this.upR, this.index3, this.index4, this.qty)
					this.disabled = false
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					if(this.index2){
						this._getBindXnPlan(this.index2)
					}
				} catch (e) {
					this.disabled = false
				}
			},
			/** 模糊匹配 */
			selectMatchItem (lists, keyWord) {
				let resArr = []
				lists.filter((item) => {
					if (item.text.indexOf(keyWord) > -1) {
						resArr.push(item)
					}
				})
				return resArr
			},
			handleChange1 (e) {
				if (e){
					this.upL = ''
					this.newaxis1 = this.selectMatchItem(this.axis, e)
				} else {
					this.newaxis1 = this.axis
				}
			},
			showSelector1 () {
				this.newaxis1 = this.axis
			},
			handleChange2 (e) {
				if (e){
					this.upR = ''
					this.newaxis2 = this.selectMatchItem(this.axis, e)
				} else {
					this.newaxis2 = this.axis
				}
			},
			showSelector2 () {
				this.newaxis2 = this.axis
			},
			handleRefresh() {
				if (!this.index2) {
					uni.showToast({ title:'请先选择位置', icon:'none' })
					return
				}
				if(this.refreshing) return
				
				this.refreshing = true
				this._getBindXnPlan(this.index2).finally(()=>{
					this.refreshing = false
				})
			},
			toggleExpand(item) {
				this.$set(item, '_expand', !item._expand)
			}
		}
	}
</script>