<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="报工"
      @clickLeft="back"
    >
    </uni-nav-bar>
	<uni-section title="设备信息">
		<view class="device">
			<view class="divice-top">
				<view class="top-name">设备</view>
				<view class="content">{{currentDivice.name}}</view>
				<view class="choose" @click="chooseAsset">选择</view>
			</view>
			<view class="divice-number">
				<view>生产数量<span>{{countInfo.standardTotalNum}} PCS</span></view>
				<view>生产重量<span>{{countInfo.standardTotalWeight}} KG</span></view>
				<view>已投料<span>{{countInfo.feedMaterielWeight}} KG</span></view>
			</view>
			<view class="divice-btm">
				<view class="btm-mold">
					<view class="mold-name">模具编码</view>
					<view class="content">{{currentMold.name}}</view>
					<view class="choose" @click="chooseMold">选择</view>
				</view>
				<view class="btm-mold">
					<view class="mold-name">冲压次数</view>
					<uni-easyinput class="modle-input" placeholder="请输入"  trim="all" v-model="punchingNum"></uni-easyinput>
					<view>次</view>
				</view>
			</view>
		</view>
	</uni-section>
	<uni-section title="工单信息">
		<view class="device order-msg">	
			  <uni-table border stripe>
				<uni-tr>
				  <uni-td align="center" class="label">工单号:</uni-td>
				  <uni-td>{{orderInfo.code}}</uni-td>
				  <uni-td align="center" class="label">产品编码:</uni-td>
				  <uni-td>  {{orderInfo.productCode}} </br> {{orderInfo.productName}} </uni-td>
				</uni-tr>
				<uni-tr>
					<uni-td align="center" class="label">牌号/型号:</uni-td>
				  <uni-td>  {{orderInfo.brandNo}} / {{orderInfo.model}} </uni-td>
				  <uni-td align="center" class="label">生产数量:</uni-td>
				  <uni-td> {{orderInfo.formingNum}} PCS</br> {{orderInfo.formingWeight}} KG </uni-td>
				</uni-tr>
			  </uni-table>
		</view>
    </uni-section>
	<uni-section title="物料信息">
		<view class="device">
			<view class="device-line">
				<view class="line-title">物料名称</view>
				<view class="line-content">
					<view class="content">{{currentMaterial.categoryName}}</view>
					<view class="choose" @click="chooseMaterial">选择</view>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">物料编码</view>
				<view class="line-content">{{currentMaterial.categoryCode}}</view>
			</view>
			<view class="device-line">
				<view class="line-title">库存地点</view>
				<view class="line-content">
					<view class="content">{{currentLoaction.warehouse}}</view>
					<view class="choose" @click="chooseLocation">选择</view>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">批次号</view>
				<view class="line-content">
					<uni-data-select 
					@change="batchChange"
						:localdata="batchList"
						v-model="currentMaterial.batchNo"></uni-data-select>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">库存</view>
				<view class="line-content">
					{{investmentNum}}KG
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">实际投入</view>
				<view class="line-content">
					<!-- <view class="content-input"> -->
						<uni-easyinput trim="all" placeholder="请输入"  v-model="currentMaterial.totalWeight"></uni-easyinput>
						<view>KG</view>
					<!-- </view> -->
					<!-- <div class="line-right">
						<u-button class="right-minus" @click="reduceNum" :disabled="investmentNum<2">-</u-button>
						<u-button class="right-add"  @click="addNum">+</u-button>
					</div> -->
				</view>
			</view>
		</view>
	</uni-section>
	<uni-section title="周转车信息">
      <view class="device">
		   <view class="car-row" v-for="(item, index) in carList">
			  <view class="car-col">
				<text>周转车编码:</text>{{ item.code }}
				<view class="del" @click="handleDelete(index)">删除</view>
			  </view>
			  <!-- <view class="car-col">
				<text>产品数量:</text><uni-easyinput v-model="item.standardNum" placeholder="请输入" ></uni-easyinput>
			  </view> -->
			  <view class="car-col">
				<text>合格品数量(PCS):</text><uni-easyinput trim="all" type="number" placeholder="请输入"  v-model="item.standardNum"></uni-easyinput>
			  </view>
			  <view class="car-col">
				<text>合格品重量(KG):</text><uni-easyinput disableColor="#ffffff" trim="all" :disabled="true"  :value="(item.standardWeight =
                  item.standardNum === ''
                    ? ''
                    : multiply(
                        item.standardNum,
                        orderInfo.productUnitWeight || 1
                      ))"></uni-easyinput>
			  </view>
		   </view>
          <!-- <uni-table border stripe>
            <uni-tr>
              <uni-th align="center">周转车编码</uni-th>
              <uni-th align="center">产品数量</uni-th>
              <uni-th align="center">操作</uni-th>
            </uni-tr>
            <uni-tr v-for="(item, index) in carList">
              <uni-td>{{ item.code }}</uni-td>
              <uni-td>
                <uni-easyinput v-model="item.standardNum" placeholder="请输入" ></uni-easyinput>
              </uni-td>
              <uni-td>
                <view class="del" @click="handleDelete(index)">删除</view>
              </uni-td>
            </uni-tr>
          </uni-table> -->
        <view class="addcar" @click="chooseCar">+</view>
      </view>
    </uni-section>
	<uni-section title="处置信息">
		<view class="device handlebox">
			<!-- <view class="device-line">
				<view class="line-title">合格数量(PCS)</view>
				<view class="line-content">
					<uni-easyinput trim="all" type="number" placeholder="请输入"  v-model="workReport.productInfo.standardNum"></uni-easyinput>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">合格重量(KG)</view>
				<view class="line-content">
					<uni-easyinput trim="all" type="number" :disabled="true"  :value="(workReport.productInfo.standardWeight =
                  workReport.productInfo.standardNum === ''
                    ? ''
                    : multiply(
                        workReport.productInfo.standardNum,
                        orderInfo.productUnitWeight || 1
                      ))"></uni-easyinput>
				</view>
			</view> -->
			<view class="device-line">
				<view class="line-title">不合格数量(PCS)</view>
				<view class="line-content">
					<uni-easyinput trim="all" placeholder="请输入" type="number" v-model="workReport.productInfo.noStandardNum"></uni-easyinput>
					<view class="handle" @click="handle(1)">处置</view>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">不合格品重量(KG)</view>
				<view class="line-content">
					<uni-easyinput trim="all" type="number" disableColor="#ffffff" :disabled="true"  :value="(workReport.productInfo.noStandardWeight =
                workReport.productInfo.noStandardNum === ''
                  ? ''
                  : multiply(
                      workReport.productInfo.noStandardNum,
                      orderInfo.productUnitWeight || 1
                    ))"></uni-easyinput>
				</view>
			</view>
			<view class="device-line">
				<view class="line-title">副产品（KG）</view>
				<view class="line-content">
					<uni-easyinput trim="all" type="number" placeholder="请输入"   v-model="workReport.productInfo.byProductWeight"></uni-easyinput>
					<view class="handle" @click="handle(2)">处置</view>
				</view>
			</view>
		</view>
	</uni-section>
    <view class="bottom" @click="report">完成报工</view>
	
	<locationPopu ref="locationRef" @checkLocation="comfirmLocation"></locationPopu>
	<assetPopu ref="assetRef" :taskId="taskId" @comfirmChoose="comfirmAsset"></assetPopu>
	<moldPopu ref="moldRef" @chooseMold="comfirmMold"></moldPopu>
	<materialPopu ref="materialRef" 
	   :taskId="taskId" 
	   :versionId="orderInfo.produceVersionId"
	   @chooseMaterial="comfirmMaterial"
	></materialPopu>
	<carPopu ref="carRef" @confirm="carConfirm"></carPopu>
    <HandlePop ref="handlePopRef" @confirm="handleConfirm" />
  </view>
</template>

<script>
import locationPopu from '../components/locationPopu.vue'
import assetPopu from '../components/assetPopu.vue'
import moldPopu from '../components/moldPopu.vue'
import materialPopu from '../components/materialPopu.vue'
import carPopu from '../components/carPopu.vue'
import HandlePop from "../components/HandlePop.vue";
import dayjs from 'dayjs'
import { getOrderById , getCount , getTaskListById , getBatchNumber } from '@/api/production/extrusion.js'
import { workReport } from '@/api/production/execute'
  import { multiply } from '@/utils/math';
export default {
  components: {
    HandlePop,
    locationPopu,
	assetPopu,
	moldPopu,
	materialPopu,
	carPopu
  },
  data () {
    return {
        // categoryMsg: {
        //   batchNo: '',
        //   number: '',
        //   position: '',
        //   totalWeight: '',
        //   brandNum: '',
        //   sourceCategoryId: '',
        //   rootCategoryLevelId: '1',
        //   name: '',
        //   code: ''
        // },
		multiply,
        workReport: {
          qualityItem: '',
          workOrderId: '',
          qualityStandard: '',
          executorId: '',
          taskSort: '1',
			taskCode: "",
			taskName: "",
          executorJobNum: '',
          executeTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          remark: '',
          productInfo: {
            standardNum: '',
            byProductWeight: '',
            standardWeight: '',
            noStandardNum: '',
            noStandardWeight: ''
          }
        },
		punchingNum:'',
		diviceName:'',
		investmentNum:'',
		orderInfo:{},
		batchList: [],
      	carList: [],
		id:'',
		countInfo:{},
		taskId:'',
		currentDivice:{},
		currentMold:{},
		currentLoaction:{},
		disposeOrderList:{},
		currentMaterial:{},
		batchNum:''
    }
  },
  onLoad ({ id , taskCode }) {
	  if(id){
		  this.id = id
		  this.workReport.workOrderId = id
	  }
	  if(taskCode){
		  this.workReport.taskCode = taskCode
	  }
  	this.getOrderInfo(id)
	this.getCountNumber()

	const userInfo =  uni.getStorageSync('userInfo')
      this.workReport.executorId = userInfo?.userId;
      this.workReport.executorJobNum = userInfo?.jobNumber;
  },

  methods: {
    async carConfirm(list) {
      const obj = this.carList.map((i) => i.id);

        for (const p of list) {
          console.log(list, p);
          if (!obj.includes(p.id)) {
            obj.push(p.id);
            this.carList.push(p);
          }
        }
    },
	
    handleDelete(index) {
      const _this = this;
      uni.showModal({
        title: `确定删除当前周转车`,
        content: "",
        confirmText: "确认",
        success: function (res) {
          if (res.confirm) {
            _this.carList.splice(index, 1);
          }
        },
      });
    },
	  chooseMaterial(){
		 this.$refs.materialRef.open() 
	  },
	  chooseAsset(){
		 this.$refs.assetRef.open(this.currentDivice) 
	  },
	  chooseMold(){
		 this.$refs.moldRef.open() 
	  },
	  chooseLocation(){
		  this.$refs.locationRef.open()
	  },
	  chooseCar(){
		  this.$refs.carRef.open()
	  },
    handle(disposeType) {
      this.$refs.handlePopRef.open(disposeType);
    },
	
    handleConfirm(data) {

		data.workOrderCode = this.orderInfo.code
		data.workOrderId = this.id

	  this.disposeOrderList = data
    },
	async report(){

		this.currentMaterial.position = this.currentLoaction.warehouseId
		this.currentMaterial.rootCategoryLevelId = '1',
		this.currentMaterial.sourceCategoryId = this.currentMaterial.id
		// this.currentMaterial.totalWeight = this.investmentNum

		const _this = this;
		uni.showModal({
			title: `是否提交报工？`,
			content: "",
			confirmText: "确认",
			success: async function (res) {
			if (res.confirm) {
				try {
					let standardNum = 0
					let standardWeight = 0
					_this.carList.map(item => {
							standardNum+=item.standardNum
							standardWeight+=item.standardWeight
					})
					
					_this.workReport.productInfo.standardNum = standardNum
					_this.workReport.productInfo.standardWeight = standardWeight
				await workReport({
					checkState: 1,
					isSapReportState: 1,
					workReport: _this.workReport,
					workReportCategoryList: [_this.currentMaterial],
					disposeOrderList: _this.disposeOrderList.workOrderId ? [_this.disposeOrderList] : [],
					workReportDeviceList: _this.carList.map(item => ({
						...item,
						rootCategoryLevelId: 7,
						sourceInstanceId: item.id,
					}))
				})
				uni.showToast({
					title: "报工成功！",
				});
				setTimeout(() => {
					uni.navigateBack({
						delta: 1,
					});
				}, 1500);
				} catch (error) {
				uni.showToast({
					title: error,
					icon: "none",
				});
				}
			}
			},
		});
	},
	  async getOrderInfo(id){
		 const data = await getOrderById(id)
		  this.orderInfo = data
		  if(data.produceVersionId){
			 const res = await getTaskListById(data.produceVersionId) 
			 if(res.length){
				 this.taskId = res[0].id
			 }
		  }
	  },
	  async getCountNumber(){
		  const params = {
			  taskCode:this.workReport.taskCode,
			  workOrderId:this.id
		  }
		  const data = await getCount(params)
		 this.countInfo = data
	  },
	  comfirmAsset(currentData){
		  this.currentDivice = currentData
	  },
	  comfirmMold(currentData){
		  this.currentMold = currentData
	  },
	  comfirmLocation(currentData){
		  this.currentLoaction = currentData
		  this.getBatch()
	  },
	  comfirmMaterial(currentData){
		  this.currentMaterial = currentData
		  this.currentMaterial.code = currentData.categoryCode
		  this.currentMaterial.name = currentData.categoryName
		//   this.currentMaterial.id = currentData.categoryId
		  this.getBatch()
	  },
	  getBatch(){
		  if(this.currentLoaction.warehouseId&&this.currentMaterial.categoryCode){
			  const params = {
				  position:this.currentLoaction.warehouseId,
				  categoryCode:this.currentMaterial.categoryCode,
				  factoryCode:this.orderInfo.werks
			  }
			  getBatchNumber(params).then(res=>{
				 this.batchList = res.map(item => ({
					...item,
					value: item.batchNum,
					text: item.batchNum
				 }))
			  })
		  }		  
	  },
	  batchChange(e){
		console.log(e);
		const obj = this.batchList.find(i => i.value === e)

		if(obj){
			this.investmentNum = obj.storageNum
		}
	  },
	  addNum(){
		  this.investmentNum = Number(this.investmentNum)+1
	  },
	  reduceNum(){
		  this.investmentNum = Number(this.investmentNum)-1
	  }
	  
  }
}
</script>

<style lang="scss" scoped>
.device{
	width: 100%;
	.car-row{
	   border-bottom: 1rpx solid #ccc;
	   margin-bottom: 30rpx;
	   .car-col{
		 display: flex;
		 justify-content: space-between;
		 align-items: center;
		padding:10rpx 20rpx;
		 text{
			margin-right: 20rpx;
		 }
	   }
	}
	&.order-msg{
		.uni-table-td{
		font-size: 28rpx !important;
			padding: 8rpx 0rpx;

			&.label{
				font-weight: bold;
			}
		}
	}
	.divice-top{
		width: 96%;
		height: 60rpx;
		margin: 10rpx auto;
		display: flex;
		align-items: center;
		justify-content: flex-start;		
	}
	.divice-number{
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin: 20rpx 0;
		span{
			margin-left: 10rpx;
		}
		view:last-child span{
			color: rgba(112, 182, 3, 1);
		}
	}
	.divice-btm{
		width: 96%;
		margin: 0 auto;
		.btm-mold{
			display: flex;
			align-items: center;
			justify-content: flex-start;
			width: 60%;
			margin-bottom: 20rpx;
			.uni-easyinput,
			.content{
				width: 35%;
				margin: 0 20rpx;
			}
		}
		.btm-mold.btm-last{
			width: 40%;
			.modle-input{
				margin: 0 10rpx;
			}
		}
	}
	.device-line{
		display: flex;
		align-items: center;
		width: 100%;
		border-bottom: 1rpx solid #ccc;
		// margin-bottom: 20rpx;
		height: 80rpx;
		.line-title{
			width: 40%;
			text-indent: 30rpx;
		}
		.line-content{
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 70%;
			margin-right: 20rpx;
			.content{
				width: 70%;
				margin: 0 20rpx 0 0;
			}
			.content-input{
				display: flex;
				align-items: center;
				justify-content: flex-start;
				width: 40%;
				view{
					margin-left: 10rpx;
				}
			}
			.line-right{
				  display: flex;
				  align-items: center;
				  justify-content: flex-end;
				  .right-minus{
					  width: 80rpx;
					  height: 51rpx;
					  text-align: center;
					  line-height: 51rpx;
					  color: #fff;
					  background: #F59A23;
				  }
				  .right-add{
					  width: 80rpx;
					  height: 51rpx;
					  text-align: center;
					  line-height: 51rpx;
					  color: #fff;
					  background: #70B603;
					  margin-left: 10rpx;
				  }
				  .right-choose.u-button--info{
					  border-color:#70B603;
					  color: #70B603;
				  }
			}
		}
	}
	.addcar{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 120rpx;
		color: #ccc;
		font-weight: bold;
		line-height: 80rpx;
	}
	.content{
		width: 40%;
		border: 1rpx solid #ccc;
		border-radius: 8rpx;
		line-height: 60rpx;
		height: 60rpx;
		margin: 0 20rpx;
		text-indent: 12rpx;
	}
	.choose{
		background: rgba(112, 182, 3, 1);
		color: #fff;
		padding: 10rpx 20rpx;
		border-radius: 8rpx;
	}
	.del{
		background: rgba(236, 128, 141, 1);
		color: #fff;
		padding: 10rpx 20rpx;
		border-radius: 8rpx;
	}
	.handle{
		background: rgba(112, 182, 3, 1);
		color: #fff;
		padding: 10rpx 20rpx;
		border-radius: 8rpx;
		margin-left: 60rpx;
	}
}
.handlebox{
  padding-bottom: 130rpx;
}
.bottom{
	width: 100%;
	height: 90rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: fixed;
	bottom: 0;
	left: 0;
	font-size: 36rpx;
	color: #fff;
	background: #4B7902;
}
</style>