<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="12" v-if="id">
							<el-form-item label="单据状态">
								<el-input type="text" :value="formData.flag == 'SAVE'?'已保存':formData.flag == 'SUBMIT'?'已提交':formData.flag == 'OK'?'审核通过':formData.flag == 'FAIL'?'审核失败':''" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="id">
							<el-form-item label="单据编号">
								<el-input type="text" :value="formData.sheetId" 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="12">
							<el-form-item label="所属商户" :required="true" >
								<el-input type="text" :value="companyName" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="网点名称" prop="websitId" :required="true">
								<el-select v-model="formData.websit" :disabled="formData.flag == 'OK'" 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="24">
							<el-form-item label="附件">
								<ImageUpload :fileList="formData.file_url" :limit="1" :isEdit="formType !== 2" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注">
								<el-input type="textarea" :rows="4" :disabled="formData.flag == 'OK'" v-model="formData.remark" 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" v-if="formData.flag == 'SAVE' || formType==0" type="primary" @click="add()">添加</el-button>
			<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.productCategory" value-key="categoryId" @change="changeMain" :disabled="isEdit != scope.$index || formData.flag == 'OK'" placeholder="请选择" style="width: 100%;">
							    <el-option
							      v-for="item in mainList"
							      :key="item.categoryId"
							      :label="item.categoryName"
							      :value="item">
							    </el-option>
							  </el-select>
						</template>
					</el-table-column>
					<el-table-column label="小类名称" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.goodsCategory" @change="changeSmall" @focus="()=>{
									if(!scope.row.productCategory){return this.$message.warning('请先选择大类！');}
								}" :disabled="isEdit != scope.$index || formData.flag == 'OK'" value-key="categoryId" placeholder="请选择" style="width: 100%;">
							    <el-option
							      v-for="item in scope.row.productCategory.items"
							      :key="item.categoryId"
							      :label="item.categoryName"
							      :value="item">
							    </el-option>
							  </el-select>
						</template>
					</el-table-column>
					<el-table-column label="辅材名称" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.goods" @change="changeGoods" value-key="goodsId" :disabled="isEdit != scope.$index || formData.flag == 'OK'" 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="goods.goodsCode" align="center" label="商品代码"></el-table-column>
					<el-table-column prop="goods.goodsSpecification" align="center" label="规格型号"></el-table-column>
					<el-table-column prop="" align="center" label="原售价">
						<template slot-scope="scope">
							{{scope.row.goods.oldPrice || scope.row.goods.price}}
						</template>
					</el-table-column>
					<el-table-column prop="" align="center" label="新售价" >
						<template slot-scope="scope">
							<el-input type="number" v-model="scope.row.newPrice" :disabled="isEdit != scope.$index || formData.flag == 'OK'" placeholder="请输入"></el-input>
						</template>
					</el-table-column>
					<el-table-column prop="goods.qty" align="center" label="库存数量"></el-table-column>
					<el-table-column label="操作" align="right" width="140">
						<template slot-scope="scope" v-if="formData.flag != 'OK'">
							<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>
		<div class="page-footer">
			<div class="footer">
				<el-button size="small" type="info" @click="goBack">返回</el-button>
				<el-button v-if="formType != 2" size="small" type="primary" @click="submit()">提交</el-button>
				<el-button v-if="formType == 1" size="small" type="primary" @click="confirm()">审核通过</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	import { getWebsit } from "@/api/customerManagement";
	import ImageUpload from '@/components/file-upload'
	import { getWorker, getCategory, getGoods } from "@/api/auxiliaryFittings/auxiliarySalesOrder";
	import { getDetail, add, edit, confirm } from "@/api/auxiliaryFittings/auxiliaryAdjustPriceOrder";
	export default {
		components: { ImageUpload },
		props: ['id','title','formType'],
		data() {
			return {
				dataList: [],
				websitList: [],
				workerList: [],
				mainList: [],
				formData: {
					websit: {},
					websitId: '',
					websitName: '',
					file_url: [],
					sheetId: '',
					flag: '',
					createBy: '',
					createTime: '',
					confirmBy: '',
					confirmTime: '',
					remark: ''
				},
				productCategory: {},
				goodsCategory: {},
				isEdit: 0,
				companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
				rules: {
					websitId: [
						{ required: true, message: '请选择网点', trigger: 'change' }
					],
					worker: [
						{ required: true, message: '请选择师傅', trigger: 'change' }
					],
					source: [
						{ required: true, message: '请选择订单来源', trigger: 'change' }
					],
					payType: [
						{ required: true, message: '请选择订单来源', trigger: 'change' }
					],
					idcard: [
						{ required: true, message: '请输入师傅身份证', trigger: 'blur' },
						{ pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
					],
					phone: [
						{ 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.getDetail()
			}
			this.getWebsit()
		},
		mounted() {
			console.log(111,this.mainList)
		},
		methods: {
			// 返回
			goBack() {
				this.$emit('back');
			},
			async getDetail(){
				const that = this
				getDetail({sheetId: this.id}).then(async res => {
					this.formData.flag = res.data.flag
					this.formData.websit = {websitId: res.data.websitId,name: res.data.websitName}
					this.formData.websitId = res.data.websitId
					this.formData.websitName = res.data.websitName
					this.formData.sheetId = res.data.sheetId
					this.formData.createBy = res.data.createBy
					this.formData.createTime = res.data.createTime
					this.formData.confirmBy = res.data.confirmBy
					this.formData.confirmTime = res.data.confirmTime
					this.getCategory(res.data.websitId)
					this.formData.remark = res.data.remark
					for(var item of res.data.items){
						item.productCategory = {categoryId: item.parentCategoryId,categoryName: item.parentCategoryName,items: [{categoryId: item.goodsCategoryId,categoryName: item.goodsCategoryName}]}
						item.goodsCategory = {categoryId: item.goodsCategoryId,categoryName: item.goodsCategoryName}
						var ress = await that.getGoods(item.goodsCategoryId,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.items
				})
			},
			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)
			},
			getCategory(websitId){
				getCategory({websitId}).then(res => {
					this.mainList = res.data
				})
			},
			async getGoods(categoryId,goodsName,type){
				const that = this
				if(type == 1){
					return new Promise((resolve, reject) => {
						getGoods({websitId: this.formData.websitId,categoryId: categoryId,type: 'M',goodsName: goodsName}).then(res => {
							resolve({
								data: res.data[0]
							})
						})
					})
				}else{
					getGoods({websitId: this.formData.websitId,categoryId: categoryId,type: 'M'}).then(res => {
						that.dataList[that.isEdit].goodsList = res.data
					})
				}
			},
			getWorker(name){
				const that = this
				getWorker({pageNum: 1,pageSize: -1,params: [{param: 'a.nick_name',compare: '=',value: name},{param: 'b.websit_id',compare: '=',value: this.formData.websitId}]}).then(res => {
					if(name){
						that.formData.idcard = res.data.records[0].idCard
						that.formData.phone = res.data.records[0].mobile
					}else{
						this.workerList = res.data.records
					}
				})
			},
			changeWorker(e){
				this.getWorker(e)
			},
			workerBlur(e){
				this.formData.worker = e.target.value
				this.$forceUpdate()
			},
			changeMain(e){
				this.dataList[this.isEdit].goodsList = [],
				this.dataList[this.isEdit].productCategory = e,
				this.dataList[this.isEdit].parentCategoryId = e.categoryId,
				this.dataList[this.isEdit].parentCategoryName = e.categoryName,
				this.dataList[this.isEdit].goodsCategory = {},
				this.dataList[this.isEdit].goodsCategoryName = '',
				this.dataList[this.isEdit].goodsCategoryId = '',
				this.dataList[this.isEdit].goods = {},
				this.dataList[this.isEdit].goodsId = '',
				this.dataList[this.isEdit].goodsName = '',
				this.dataList[this.isEdit].goodsSalesUnit = '',
				this.dataList[this.isEdit].goodsSpecification = '',
				this.dataList[this.isEdit].goodsCode = '',
				this.dataList[this.isEdit].newPrice = '',
				this.dataList[this.isEdit].oldPrice = '',
				this.dataList[this.isEdit].qty = '',
				this.dataList[this.isEdit].goodsType = 'M'
			},
			async changeSmall(e){
				this.dataList[this.isEdit].goods = {},
				this.dataList[this.isEdit].goodsId = '',
				this.dataList[this.isEdit].goodsName = '',
				this.dataList[this.isEdit].goodsSalesUnit = '',
				this.dataList[this.isEdit].goodsSpecification = '',
				this.dataList[this.isEdit].goodsCode = '',
				this.dataList[this.isEdit].newPrice = '',
				this.dataList[this.isEdit].oldPrice = '',
				this.dataList[this.isEdit].qty = '',
				this.dataList[this.isEdit].goodsCategoryId = e.categoryId
				this.dataList[this.isEdit].goodsCategoryName = e.categoryName
				getGoods({websitId: this.formData.websitId,categoryId: e.categoryId,type: 'M'}).then(res => {
					this.dataList[this.isEdit].goodsList = res.data
				})
			},
			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].goodsSpecification = e.goodsSpecification
				this.dataList[this.isEdit].oldPrice = e.price
				this.dataList[this.isEdit].goodsCode = e. goodsCode
				this.dataList[this.isEdit].qty = e.qty
			},
			add(){
				if(this.dataList.length != 0){this.isEdit += 1}
				this.dataList.push({
					goodsList: [],
					productCategory: {},
					parentCategoryId: '',
					parentCategoryName: '',
					goodsCategory: {},
					goodsCategoryName: '',
					goodsCategoryId: '',
					goods: {},
					goodsId: '',
					goodsName: '',
					goodsSalesUnit: '',
					goodsSpecification: '',
					goodsCode: '',
					newPrice: '',
					oldPrice: '',
					qty: '',
					goodsType: 'M'
				})
			},
			confirm(){
				this.$confirm(`请确认是否审核通过, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					confirm({
						sheetId: this.formData.sheetId,
						flag: 'OK'
					}).then(res => {
						if(res.code == 200){
							this.$message.success('审核成功！')
							this.goBack()
						}
					})
				});
			},
			submit(){
				this.$refs.formData.validate((valid, invalidFields, errLabels) => {
					if (valid) {
						if(this.formType == 0){
							add({
								remark: this.formData.remark,
								websitId: this.formData.websitId,
								websitName: this.formData.websitName,
								file_url: this.formData.file_url.map(item=>item.url).join(","),
								items: this.dataList
							}).then(res => {
								if(res.code == 200){
									this.$message.success('提交成功！')
									this.goBack()
								}
							})
						}else if(this.formType == 1){
							edit({
								sheetId: this.formData.sheetId,
								remark: this.formData.remark,
								websitId: this.formData.websitId,
								websitName: this.formData.websitName,
								file_url: this.formData.file_url.map(item=>item.url).join(","),
								items: this.dataList
							}).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>