<template>
	<div class="s-page">
		<el-page-header @back="goBack" :content="title"></el-page-header>
		<el-divider></el-divider>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>单据信息</span>
			</div>
			<div class="mymain-container">
				<el-form ref="formData" :rules="rules" :model="formData" label-width="110px" size="small" label-position="left">
					<el-row :gutter="20" justify="start">
						<el-col :span="8" v-if="id">
							<el-form-item label="单据状态">
								<el-input type="text" :value="formData.flag == 'SAVE'?'保存':formData.flag == 'SUBMIT'?'已提交':formData.flag == 'OK'?'确认收货':''" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8" v-if="id">
							<el-form-item label="单据编号">
								<el-input type="text" :value="formData.partsRetId" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="所属商户" :required="true" >
								<el-input type="text" :value="companyName" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="网点名称" prop="websitId" :required="true">
								<el-select v-model="formData.websit" disabled value-key="websitId" @change="changeWebsit" placeholder="请选择" style="width: 100%;">
								    <el-option
								      v-for="item in websitList"
								      :key="item.websitId"
								      :label="item.name"
								      :value="item">
								    </el-option>
								  </el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="购买方" :required="true" style="padding-bottom: 1px;">
								<el-radio-group v-model="formData.buyPeople">
									<el-radio disabled label="WORKER">内部师傅</el-radio>
									<el-radio disabled label="CUSTOMER">客户</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<template v-if="formData.buyPeople == 'CUSTOMER'">
							<el-col :span="8">
								<el-form-item label="客户姓名" prop="workerName" :required="true">
									<el-input type="text" disabled v-model="formData.workerName" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="客户联系电话" prop="workerMobile" :required="true">
									<el-input type="text" disabled v-model="formData.workerMobile" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
						</template>
						<template v-else>
							<el-col :span="8">
								<el-form-item label="师傅姓名" prop="worker" :required="true">
									<el-input type="text" v-model="formData.workerName" disabled placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
							<!-- <el-col :span="8">
								<el-form-item label="师傅身份证" prop="identity" :required="true">
									<el-input type="text" v-model="formData.identity" :disabled="formType == 2" placeholder="请输入"></el-input>
								</el-form-item>
							</el-col> -->
							<el-col :span="8">
								<el-form-item label="师傅联系电话" prop="workerMobile" :required="true">
									<el-input type="text" v-model="formData.workerMobile" disabled placeholder="请输入"></el-input>
								</el-form-item>
							</el-col>
						</template>
						<el-col :span="8">
							<el-form-item label="销售订单号" :required="true">
								<el-input type="text" v-model="formData.salesId" :disabled="formType == 2" @change="getDetail" placeholder="请输入销售订单号"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="销售金额">
								<el-input type="text" :value="formData.totalAmount" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="时间">
								<el-input type="text" :value="formData.payTime" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="id">
							<el-form-item label="制单人">
								<el-input type="text" :value="formData.createBy" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="id">
							<el-form-item label="制单时间">
								<el-input type="text" :value="formData.createTime" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="id">
							<el-form-item label="审核人">
								<el-input type="text" :value="formData.confirmBy" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="6" v-if="id">
							<el-form-item label="审核时间">
								<el-input type="text" :value="formData.confirmTime" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="附件">
								<ImageUpload :fileList="formData.fileUrl" :limit="1" :isEdit="formType !== 2" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注">
								<el-input type="textarea" :rows="4" v-model="formData.remark" :disabled="formType == 2" placeholder="请输入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
		</el-card>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>配件信息</span>
			</div>
			<!-- <el-button size="small" type="primary" @click="add()">添加</el-button> -->
			<label>使用类型: </label>
			<el-radio-group v-model="formData.orderUseType">
			    <el-radio :disabled="formType == 2" label="INSIDE">保内</el-radio>
			    <el-radio :disabled="formType == 2" label="OUT">保外</el-radio>
			  </el-radio-group>
			<div class="table">
				<el-table :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
					<el-table-column label="配件名称" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.goods" @change="changeGoods" value-key="goodsId" :disabled="true" placeholder="请选择" style="width: 100%;">
							    <el-option
							      v-for="item in scope.row.goodsList"
							      :key="item.goodsId"
							      :label="item.goodsName"
							      :value="item">
							    </el-option>
							  </el-select>
						</template>
					</el-table-column>
					<el-table-column prop="goods.goodsSalesUnit" align="center" label="单位" ></el-table-column>
					<el-table-column prop="" align="center" label="数量" >
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.oldRefundQty" :disabled="isEdit != scope.$index || formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="goods.goodsCode" align="center" label="配件编码"></el-table-column>
					<el-table-column prop="goods.brandRelaName" align="center" label="适用品牌"></el-table-column>
					<el-table-column prop="goods.productRelaName" align="center" label="适用产品大类"></el-table-column>
					<el-table-column prop="goods.price" align="center" label="销售价格"></el-table-column>
					<el-table-column prop="goods.saleAmount" align="center" label="销售金额" >
						<template slot-scope="scope" v-if="scope.row.oldRefundQty && scope.row.goods && scope.row.goods.price">
							{{(scope.row.goods.price * 100) * scope.row.oldRefundQty / 100}}
						</template>
					</el-table-column>
					<!-- <el-table-column prop="goods.qty" align="center" label="库存数量"></el-table-column> -->
					<el-table-column prop="" align="center" label="退款金额" v-if="formData.orderUseType == 'INSIDE'">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.refundAmount" :disabled="isEdit != scope.$index || formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="right" width="140">
						<template slot-scope="scope" v-if="formType != 2">
							<el-button size="mini" type="primary" v-if="scope.$index != isEdit" @click="isEdit = scope.$index">编辑</el-button>
							<el-button size="mini" type="danger" @click="dataList.splice(scope.$index,1)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-card>
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span>旧件信息</span>
			</div>
			<el-button v-if="formType != 2" size="small" type="primary" @click="add()">添加</el-button>
			<div class="table">
				<el-table :data="oldList" element-loading-text="Loading" border fit highlight-current-row stripe>
					<el-table-column label="工单号" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.orderId" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="工单品牌" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.orderBrand" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="用户姓名" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.name" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="用户电话" align="center">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.phone" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="配件名称" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.partsName" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="配件编码" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.partsCode" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="单位" align="center">
						<template slot-scope="scope">
							<el-input type="text" v-model="scope.row.unit" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="数量" align="center">
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.qty" :disabled="formType == 2" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="right" width="140">
						<template slot-scope="scope" v-if="formType != 2">
							<el-button size="mini" type="danger" @click="oldList.splice(scope.$index,1)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-card>
		<div class="page-footer">
			<div class="footer">
				<el-button v-if="formType == 0 || (formType == 1 && formData.flag == 'SAVE')" size="small" type="primary" @click="save()">保存</el-button>
				<el-button v-if="formType != 0 && formData.flag == 'SAVE'" size="small" type="primary" @click="submit()">提交</el-button>
				<el-button v-if="formType != 0 && formData.flag == 'SUBMIT'" size="small" type="primary"  @click="confirm()">确认收货</el-button>
				<el-button size="small" type="info" @click="goBack">返回</el-button>
			</div>
		</div>
		<el-dialog title="微信支付" :visible.sync="isPay" width="50%" :close-on-click-modal="false" :modal-append-to-body="false" @close="payCodeUrl = ''">
			<h3>扫二维码支付</h3>
			<el-image :src="payCodeUrl" fit="fit"></el-image>
		</el-dialog>
	</div>
</template>

<script>
	import { getWebsit } from "@/api/customerManagement";
	import ImageUpload from '@/components/file-upload'
	import { getWorker, getCategory, getGoods, getDetail } from "@/api/auxiliaryFittings/auxiliarySalesOrder";
	import { add, edit, getNewDetail } from "@/api/auxiliaryFittings/attachmentNewReturn";
	export default {
		components: { ImageUpload },
		props: ['id','title','formType'],
		data() {
			return {
				dataList: [],
				oldList: [],
				websitList: [],
				workerList: [],
				mainList: [],
				isPay: false,
				payCodeUrl: '',
				salesDetail: {},
				formData: {
					websit: {},
					websitId: '',
					websitName: '',
					fileUrl: [],
					salesId: '',
					partsRetId: '',
					flag: '',
					createBy: '',
					createTime: '',
					confirmBy: '',
					confirmTime: '',
					worker: {},
					workerName: '',
					workerId: '',
					identity: '',
					workerMobile: '',
					remark: '',
					totalAmount: '',
					orderUseType: 'INSIDE'
				},
				isEdit: 0,
				companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
				rules: {
					websitId: [
						{ required: true, message: '请选择网点', trigger: 'change' }
					],
					worker: [
						{ required: true, message: '请选择师傅', trigger: 'change' }
					],
					identity: [
						{ required: true, message: '请输入师傅身份证', trigger: 'blur' },
						{ pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
					],
					workerMobile: [
						{ required: true, message: '请输入师傅联系电话', trigger: 'blur' },
						{ pattern:/^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/, message: '电话号码格式不正确', trigger: 'blur' }
					],
				}
			};
		},
		computed: {},
		created() {
			if(this.id){
				this.getNewDetail()
			}
			this.getWebsit()
		},
		methods: {
			// 返回
			goBack() {
				this.$emit('back');
			},
			async getDetail(salesId){
				const that = this
				getDetail({salesId}).then(async res => {
					Object.assign(this.formData, res.data, {
						websit: {websitId: res.data.websitId,name: res.data.websitName},
						worker: {nickName: res.data.workerName,userId: res.data.workerId},
						fileUrl: res.data?.fileUrl ? res.data?.fileUrl?.split(",").map(item=>({url:item})) : []
					})
					this.getWorker()
					for(var item of res.data.items){
						var ress = await that.getGoods(item.goodsName, 1)
						item.goods = {...ress.data,oldPrice:ress.data.price}
						item.goodsList = ress.data ? [{...ress.data,oldPrice:ress.data.price}] : []
						item.oldRefundQty = 1
						item.refundAmount = 0
					}
					this.dataList = res.data.items
				})
			},
			async getNewDetail(){
				const that = this
				getNewDetail({id: this.id}).then(async res => {
					Object.assign(this.formData, res.data, {
						websit: {websitId: res.data.websitId,name: res.data.websitName},
						worker: {nickName: res.data.workerName,userId: res.data.workerId},
						fileUrl: res.data?.fileUrl ? res.data?.fileUrl?.split(",").map(item=>({url:item})) : []
					})
					this.getWorker()
					for(var item of res.data.websitPartsRetItemList){
						var ress = await that.getGoods(item.goodsName, 1)
						item.goods = {...ress.data,oldPrice:ress.data.price}
						item.goodsList = ress.data ? [{...ress.data,oldPrice:ress.data.price}] : []
					}
					this.dataList = res.data.websitPartsRetItemList
					this.oldList = res.data.websitPartsRetOldRecordList
				})
			},
			getWebsit(){
				getWebsit({type: 'C'}).then(res => {
					this.websitList = res.data
				})
			},
			changeWebsit(e){
				this.formData.websitId = e.websitId
				this.formData.websitName = e.name
				this.getWorker()
				this.getCategory(e.websitId)
			},
			async getGoods(goodsName,type){
				const that = this
				if(type == 1){
					return new Promise((resolve, reject) => {
						getGoods({websitId: this.formData.websitId,type: 'P',goodsName: goodsName}).then(res => {
							resolve({
								data: res.data[0]
							})
						})
					})
				}else{
					getGoods({websitId: this.formData.websitId,type: 'P'}).then(res => {
						that.dataList[that.isEdit].goodsList = res.data
						console.log(this.dataList)
					})
				}
			},
			getWorker(){
				getWorker({pageNum: 1,pageSize: -1,params: [{param: 'b.websit_id',compare: '=',value: this.formData.websitId}]}).then(res => {
					this.workerList = res.data.records
				})
			},
			changeWorker(e){
				this.formData.identity = e.idCard
				this.formData.workerMobile = e.mobile
				this.formData.workerId = e.userId
				this.formData.workerName = e.nickName
			},
			workerBlur(e){
				this.formData.worker = e.target.value
				this.$forceUpdate()
			},
			changeGoods(e){
				console.log(e)
				this.dataList[this.isEdit].goodsId = e.goodsId
				this.dataList[this.isEdit].goodsName = e.goodsName
				this.dataList[this.isEdit].goodsSalesUnit = e.goodsSalesUnit
				this.dataList[this.isEdit].brandRelaName = e.brandRelaName
				this.dataList[this.isEdit].productRelaName = e.productRelaName
				this.dataList[this.isEdit].price = e.price
				this.dataList[this.isEdit].goodsCode = e. goodsCode
				this.dataList[this.isEdit].qty = e.qty
			},
			add(){
				this.oldList.push({
					orderId: '',
					orderBrand: '',
					name: '',
					phone: '',
					partsName: '',
					unit: '',
					qty: '',
					partsCode: ''
				})
			},
			async checkForm(){
				let is_save = true
				this.dataList.forEach(item=>{
					if(!item.oldRefundQty || item.oldRefundQty < 1){
						this.$message.warning('请输入配件数量并且数量大于0！')
						is_save = false
					}else if((!item.refundAmount || item.refundAmount <= 0) && this.formData.orderUseType == 'INSIDE'){
						this.$message.warning('请输入配件退货金额并且大于0！')
						is_save = false
					}
				})
				return is_save
				
			},
			confirm(){
				this.$confirm(`请确定是否确认提货, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					edit({
						flag: 'OK',
						partsRetId: this.formData.partsRetId,
					}).then(res => {
						if(res.code == 200){
							this.$message.success('确认提货成功！')
							this.goBack()
						}
					})
				});
			},
			async submit(){
				let is_save = await this.checkForm()
				if(!is_save){return false}
				this.$confirm(`请确定是否提交, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					edit({
						flag: 'SUBMIT',
						salesId: this.formData.salesId,
						partsRetId: this.formData.partsRetId,
						goodsType: 'P',
						type: 'OLD',
						remark: this.formData.remark,
						websitId: this.formData.websitId,
						websitName: this.formData.websitName,
						workerName: this.formData.workerName,
						workerId: this.formData.workerId,
						identity: this.formData.identity,
						workerMobile: this.formData.workerMobile,
						websitPartsRetItems: this.dataList,
						websitPartsRetOldRecordList: this.oldList,
						orderUseType: this.formData.orderUseType,
						fileUrl: this.formData.fileUrl.map(item=>item.url).join(","),
					}).then(res => {
						if(res.code == 200){
							this.$message.success('提交成功！')
							this.goBack()
						}
					})
				});
			},
			async save(){
				let is_save = await this.checkForm()
				console.log(is_save)
				if(!is_save){return false}
				this.$refs.formData.validate((valid, invalidFields, errLabels) => {
					if (valid) {
						if(this.formType == 0){
							add({
								salesId: this.formData.salesId,
								goodsType: 'P',
								type: 'OLD',
								remark: this.formData.remark,
								websitId: this.formData.websitId,
								websitName: this.formData.websitName,
								workerName: this.formData.workerName,
								workerId: this.formData.workerId,
								identity: this.formData.identity,
								workerMobile: this.formData.workerMobile,
								websitPartsRetItems: this.dataList,
								websitPartsRetOldRecordList: this.oldList,
								orderUseType: this.formData.orderUseType,
								fileUrl: this.formData.fileUrl.map(item=>item.url).join(","),
							}).then(res => {
								if(res.code == 200){
									this.$message.success('提交成功！')
									this.goBack()
								}
							})
						}else if(this.formType == 1){
							edit({
								salesId: this.formData.salesId,
								partsRetId: this.formData.partsRetId,
								goodsType: 'P',
								type: 'OLD',
								remark: this.formData.remark,
								websitId: this.formData.websitId,
								websitName: this.formData.websitName,
								workerName: this.formData.workerName,
								workerId: this.formData.workerId,
								identity: this.formData.identity,
								workerMobile: this.formData.workerMobile,
								websitPartsRetItems: this.dataList,
								websitPartsRetOldRecordList: this.oldList,
								orderUseType: this.formData.orderUseType,
								fileUrl: this.formData.fileUrl.map(item=>item.url).join(","),
							}).then(res => {
								if(res.code == 200){
									this.dataList = []
									this.$message.success('提交成功！')
									this.goBack()
								}
							})
						}
					}
				})
			}
		}
	};
</script>

<style scoped="scoped" lang="scss">
	.s-page {
		padding: 20px;
		background-color: #ffffff;
	}
	.page-footer {
		height: 70px;
	}
	
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 1;
		width: 100%;
		background: #fff;
		padding: 15px 40px;
		box-sizing: border-box;
		transition: all 0.28s;
		text-align: right;
		box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);
	
		&.hideSidebar {
			margin-left: 54px;
			width: calc(100vw - 54px);
		}
	
		&.openSidebar {
			margin-left: 210px;
			width: calc(100vw - 210px);
		}
	
		.tips {
			font-size: 12px;
			color: red;
			margin-top: 10px;
		}
	}
</style>