<template>
	<u-modal width="90%" @confirm="submitIpqc" v-model="visable" :showConfirmButton="showIpqcConfirmButton" :showCancelButton="true" title="请填写检验单" content="操作内容" @cancel="close">
	  <u-form ref="qcForm" label-width="90px" class="addForm">
	    <u-row>
	      <u-col span="4">
	        <u-form-item label="工单编码">
	          <SearchInput v-model="qcForm.workorderCode" :disabled="btnType !== ''" placeholder="请输入工单编码" hassearchbtn="true" @serach="searchTask" />
	        </u-form-item>
	      </u-col>
				<u-col span="4">
					<u-form-item label="编排编码">
						<SearchInput v-model="qcForm.arrangeCode" :disabled="btnType !== ''" placeholder="请输入编排编码" hassearchbtn="true" @serach="searWorkorder" />
					</u-form-item>
				</u-col>
				<u-col span="4">
					<u-form-item label="工序名称">
						<uni-data-select v-model="qcForm.processId" :disabled="btnType !== ''" :localdata="processList" @change="changeprocess"></uni-data-select>
					</u-form-item>
				</u-col>
	      <u-col span="4">
	        <u-form-item label="检验单名称" label-width="90px">
	          <u-input v-model="qcForm.ipqcName" placeholder="请输入检验单名称"></u-input>
	        </u-form-item>
	      </u-col>
				<u-col span="4" v-if="btnType">
				  <u-form-item label="检验单编号" label-width="90px">
				    <u-input v-model="qcForm.ipqcCode" placeholder="请输入检验单编号"></u-input>
				  </u-form-item>
				</u-col>
				<u-col span="4">
				  <u-form-item label="检测结果" prop="checkResult">
				    <u-radio-group v-model="qcForm.checkResult">
				      <u-radio :name="item.value" v-for="item in dict.type.mes_qc_result" :key="item.value">
				        {{ item.label }}
				      </u-radio>
				    </u-radio-group>
				  </u-form-item>
				</u-col>
	    </u-row>
	    <u-row>
	      <u-col span="4">
	        <u-form-item label="检测数量" prop="quantityCheck">
	          <u-number-box disabled v-model="qcForm.quantityCheck"></u-number-box>
	        </u-form-item>
	      </u-col>
	      <u-col span="4">
	        <u-form-item label="合格数量" prop="quantityQualified">
	          <u-number-box :min="0" v-model="qcForm.quantityQualified" @change="handleChangeQuantityCheck"></u-number-box>
	        </u-form-item>
	      </u-col>
	      <u-col span="4">
	        <u-form-item label="不合格数量" prop="quantityUnqualified">
	          <u-number-box :min="0" v-model="qcForm.quantityUnqualified" @change="handleChangeQuantityCheck"></u-number-box>
	        </u-form-item>
	      </u-col>
	    </u-row>
	    <u-row>
	      <u-col span="4">
	        <u-form-item label="检测人员" prop="inspectorNickName">
	          <u-input disabled v-model="qcForm.inspectorNickName"></u-input>
						<u-button @tap="userTempVisible=true" v-if="btnType !== 'firstView'" type="success" size="mini">选择人员</u-button>
	        </u-form-item>
	      </u-col>
	    </u-row>
	  </u-form>
		<view class="btnbox">
		  <u-button type="success" v-if="isEdit" size="medium" @click="handleAddFirstEdit">新增</u-button>
		</view>
	   <view class="line-content-item">
	      <uni-table ref="qcLineTable" class="line-table" border stripe :loading="loading" emptyText="未查询到数据">
	        <uni-tr>
	          <uni-th width="100px" align="center">质检项目</uni-th>
	          <uni-th width="100px" align="center">检验要求</uni-th>
	          <uni-th width="150px" align="center">检验结果</uni-th>
						<!-- <uni-th width="15px" align="center">操作</uni-th> -->
	        </uni-tr>
	        <uni-tr v-for="(line, index) in qcLines" :key="index + 'index'">
	          <uni-td align="center">{{ line.indexName }}</uni-td>
	          <uni-td align="center">{{ line.checkMethod }}</uni-td>
	          <uni-td width="150px" align="center">
	            <uni-data-checkbox v-if="line.inputType == 2" multiple v-model="line.qualityCheckResults" :localdata="line.selectValues"></uni-data-checkbox>
	            <uni-easyinput v-else v-model="line.qualityCheckResults"></uni-easyinput>
	          </uni-td>
						<!-- <uni-td width="15px" align="center">
							<view @click="del('qcAddList', index)" :style="{color: isEdit ? '#e56048' : '#ddd'}">删除</view>
						</uni-td> -->
	        </uni-tr>
	        <uni-tr v-for="(line, index) in qcAddList" :key="index + 'add'">
	          <uni-td align="center">
	            <view style="display:flex;">
	              <u-input disabled v-model="line.indexName" placeholder="选择质检项目"></u-input>
	              <u-button @tap="chooseZJ(index)" type="success" size="mini">选择质检项目</u-button>
	            </view>
	          </uni-td>
	          <uni-td align="center"></uni-td>
	          <uni-td width="150px" align="center">
	            <uni-easyinput v-model="line.qualityCheckResults"></uni-easyinput>
	          </uni-td>
				<!-- 		<uni-td width="15px" align="center">
							<view @click="del('qcAddList', index)" :style="{color: isEdit ? '#e56048' : '#ddd'}">删除</view>
						</uni-td> -->
	        </uni-tr>
	      </uni-table>
	    </view>
			<u-modal
			  title="选择人员"
			  @confirm="userDetermine()"
			  show-cancel-button
			  :title-style="{ 'background-color': '#1E3770', color: '#FFFFFF', 'line-height': '37px', 'padding-top': '0px' }"
			  v-model="userTempVisible"
			  width="1300rpx"
			>
			  <view class="feedback-card">
			    <User ref="userRef" v-if="userTempVisible" />
			  </view>
			</u-modal>
	</u-modal>
</template>

<script>
	import UniEasyinput from '../../../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
	import UButton from '../../../../uview-ui/components/u-button/u-button.vue';
	import SearchInput from '@/components/ScanInput/index.vue';
	import User from '@/components/User/User.vue';
	export default {
		props: ["zjVisible", "qcAddIndex", "visible", "showIpqcConfirmButton", "btnType", "curQcType", "currentItem"],
		components: {
			SearchInput,
			User,
			UniEasyinput,
			UButton
		},
		dicts: ['mes_qc_result'],
		data() {
			return {
				qcForm: {
					workorderCode: '',
					arrangeCode: '',
					processId: '',
					ipqcName: '',
					checkResult: 'REJECT',
					quantityCheck: 1,
					quantityQualified: 1,
					quantityUnqualified: 0,
					inspectorNickName: '',
					inspector: ''
				},
				Condition: {},
				userTempVisible: false,
				loading: false,
				visable: true,
				qcAddList: [],
				qcLines: [],
				processList: []
			}
		},
		created() {
			this.visable = true
		},
		computed: {
			isEdit () {
				return this.btnType === 'firstEdit' || !this.btnType || this.btnType === 'sjqrFinish'
			}
		},
		watch: {
			visable(){
				this.$emit('update:visible', this.visable)
			},

			currentItem: {
				handler(){
					if(this.btnType && this.currentItem) {
						this.qcForm = Object.assign({}, this.currentItem);
						this.qcLines = []
						this.getTemplateLineList()
						if(this.currentItem.workorderCode) this.searchTask(this.currentItem.workorderCode)
						if(this.currentItem.arrangeCode) this.searWorkorder(this.currentItem.arrangeCode)
					}
				},
				immediate: true
			},
			btnType () {
				if(this.btnType === 'firstEdit') {
					this.qcForm.checkResult = this.qcForm.checkResult ? this.qcForm.checkResult : 'REJECT';
					this.qcForm.quantityCheck = this.qcForm.quantityCheck ? this.qcForm.quantityCheck : 1;
					this.qcForm.quantityQualified = this.qcForm.quantityQualified ? this.qcForm.quantityQualified : 1;
					this.qcForm.quantityUnqualified = this.qcForm.quantityUnqualified ? this.qcForm.quantityUnqualified : 0;
				}
			}
		},
		methods: {
			del(list, index){
				if(this.isEdit) {
					uni.showModal({
						title: '提示',
						content: '您确定要删除此项吗？',
						style: 'z-index: 99999',
						success: async (res) => {
							if (res.confirm) {
								this[list].splice(index, 1)
							}
						}
					})
				}
			},
			getTemplateLineList() {
			  this.$u.api
			    .getIpqcLineList({
			      ipqcId: this.qcForm.ipqcId
			    })
			    .then((res) => {
			      if (res.code === 200) {
			        this.qcLines = res.rows.map((item) => {
			          let selectValues = item.selectValues;
			          let qualityCheckResults = item.qualityCheckResults;
			          if (item.inputType == 2) {
			            // selectValues = selectValues? JSON.parse(item.selectValues) : []
			            if (selectValues) {
			              const data = JSON.parse(item.selectValues);
			              selectValues = data.map((item) => {
			                return {
			                  text: item.name,
			                  value: item.name
			                };
			              });
			            } else {
			              selectValues = [];
			            }
			            qualityCheckResults = qualityCheckResults ? JSON.parse(item.qualityCheckResults) : [];
			          }
			          return {
			            ...item,
			            selectValues,
			            qualityCheckResults
			          };
			        });
			      }
			    });
			},
			handleSubmitZj(params){
				Object.keys(params).forEach(item => {
					this.$set(this.qcAddList[this.qcAddIndex], item, params[item])
				})
			},
			chooseZJ(index) {
				this.$emit('update:zjVisible', true)
				this.$emit('update:qcAddIndex', index)
			},
			userDetermine() {
			  this.qcForm.inspectorNickName = this.$refs.userRef.tableSelectData[0]?.nickName;
			  this.qcForm.inspector = this.$refs.userRef.tableSelectData[0]?.userName;
			},
			async changeprocess() {
				const res = await this.$u.api.generateItems({"workorderCode":this.qcForm.workorderCode,"arrangeCode":this.qcForm.arrangeCode,"qcTypes":"PATROL","processId":this.qcForm.processId})
				// const res = await this.$u.api.generateItems({"workorderCode":"","arrangeCode":"BP24531002","qcTypes":"PATROL","processId":389})
				if (res.code === 200) {
					console.log(res.data)
					this.qcLines = res.data.map((item) => {
					  let selectValues = item.selectValues;
					  let qualityCheckResults = item.qualityCheckResults;
					  if (item.inputType == 2) {
					    // selectValues = selectValues? JSON.parse(item.selectValues) : []
					    if (selectValues) {
					      const data = JSON.parse(item.selectValues);
					      selectValues = data.map((item) => {
					        return {
					          text: item.name,
					          value: item.name
					        };
					      });
					    } else {
					      selectValues = [];
					    }
					    qualityCheckResults = qualityCheckResults ? JSON.parse(item.qualityCheckResults) : [];
					  }
					  return {
					    ...item,
					    selectValues,
					    qualityCheckResults
					  };
					});
				}
			},
			handleChangeQuantityCheck(e) {
				console.log('sadasdas', e)
			  const sum = this.qcForm.quantityQualified + this.qcForm.quantityUnqualified;
			  this.$set(this.qcForm, 'quantityCheck', sum);
			},
			handleAddFirstEdit() {
			  this.qcAddList.push({
			    indexName: '',
			    qualityCheckResults: ''
			  })
			},
			async searchTask(val) {
				const res = await this.$u.api.getQcCondition({
				  workorderCode: val,
					arrangeCode: this.qcForm.arrangeCode
				});
				if (res.code === 200) {
				  if (!res.data) {
				    this.$u.toast('暂未查询到工序信息！');
				  }
					this.Condition = res.data
					this.qcForm.workorderCode = res.data.workorderCode
					this.qcForm.arrangeCode = res.data.arrangeCode
					if(res.data.processList && res.data.processList.length > 0){
						this.processList = res.data.processList.map(v=>({text: v.processName, value: v.processId, code: v.processCode, workstationCode: v.workstationCode, workstationId: v.workstationId, workstationName: v.workstationName, workorderProcessId: v.workorderProcessId}))
					}
				}
			},
			async searWorkorder(val) {
			  const res = await this.$u.api.getQcCondition({
			    workorderCode: this.qcForm.workorderCode,
					arrangeCode: val
			  });
			  if (res.code === 200) {
			    if (!res.data) {
			      this.$u.toast('暂未查询到工序信息！');
			    }
					this.Condition = res.data
					this.qcForm.workorderCode = res.data.workorderCode
					this.qcForm.arrangeCode = res.data.arrangeCode
					if(res.data.processList && res.data.processList.length > 0){
						this.processList = res.data.processList.map(v=>({text: v.processName, value: v.processId, code: v.processCode, workstationCode: v.workstationCode, workstationId: v.workstationId, workstationName: v.workstationName, workorderProcessId: v.workorderProcessId}))
					}
			  }
			},
			submitIpqc() {
				if(!this.qcForm.processId) {
					this.$u.toast('请输入工单编码或编排编码并选择工序！');
					return;
				}
				const item = this.processList.find(v=>v.value === this.qcForm.processId)
				console.log('item', item)
				this.$emit('confirm', {
					...this.Condition,
					...this.qcForm,
					processCode: item.code,
					processName: item.text,
					workstationCode: item.workstationCode,
					workorderProcessId: item.workorderProcessId,
					workstationId: item.workstationId, 
					workstationName: item.workstationName,
					qcLines: this.qcLines,
					qcAddList: this.qcAddList
				})
			},
			close(){
				this.$emit('close')
			}
		}
	}
</script>

<style>
	.line-content-item {
	  width: 100%;
		padding: 0 10px;
	  height: 300px;
	  display: flex;
	  flex-wrap: nowrap;
	}
	.line-table {
	  display: inline-block;
	}
	.addForm {
		padding: 0 40rpx;
	}
	.btnbox {
	  // display:flex;
	  margin-bottom: 10rpx;
	  margin-top: 10rpx;
	  padding-left: 40rpx;
	  .u-btn {
	    width: 150rpx;
	  }
	}
	.del-modal{
		z-index: 99999;
	}
</style>