<template>
	<view class="page">
		<view>
			<view class="cu-bar bg-white cu-title solid-bottom">
				<view class="action" style="vertical-align: middle;">
					<text class="margin-right-xs text-blue cuIcon-title">
						<span></span>
					</text>
					<text class="text-xl">
						<span>经费开支申报单</span>
					</text>
				</view>
			</view>
		</view>
		<view v-if="ready">
			<l-input @input="setValue('FundsApply.EnCode', $event)" :value="getValue('FundsApply.EnCode')"
				title="申报单号" /> <!-- v-if="!edit" :disabled="!edit" -->
			<l-select @input="setValue('FundsApply.ApplyDept', $event)" :value="getValue('FundsApply.ApplyDept')"
				:range="dataSource.FundsApply.ApplyDept" title="报批部门" disabled />
			<!-- :disabled="!edit" v-if="!edit" -->
			<l-select @input="setValue('FundsApply.ApplyUser', $event)" :value="getValue('FundsApply.ApplyUser')"
				:range="dataSource.FundsApply.ApplyUser" title="报批人" disabled /> <!-- v-if="!edit" -->
			<l-datetime-picker @input="setValue('FundsApply.ApplyTime', $event)"
			:value="getValue('FundsApply.ApplyTime')" title="填报时间" disabled /> <!-- required :disabled="!edit" -->
			<l-select @input="($event)=>{DeclarationDeptChange($event)}" :value="getValue('FundsApply.DeclarationDept')"
				:range="dataSource.FundsApply.DeclarationDept" title="申报部门" :disabled="!edit" />
			<!-- :disabled="!edit" v-if="!edit" -->
			<l-select @input="setValue('FundsApply.Informant', $event)" :value="getValue('FundsApply.Informant')"
				:range="dataSource.FundsApply.Informant" title="申报人"  :disabled="!edit"/> 
			<l-select @input="setValue('FundsApply.DeclarationType', $event)"
				:value="getValue('FundsApply.DeclarationType')" :range="dataSource.FundsApply.DeclarationType"
				title="申报类型" :disabled="!edit" />
			<l-select @input="setValue('FundsApply.IsFixedAssets', $event)"
				:value="getValue('FundsApply.IsFixedAssets')" :range="dataSource.FundsApply.IsFixedAssets"
				title="是否固定资产" :disabled="!edit" /> <!-- v-if="!edit" -->
			<l-textarea @input="setValue('FundsApply.Remark', $event)" :value="getValue('FundsApply.Remark')" title="备注"
				:readonly="!edit" /> <!-- v-if="!edit" :readonly="!edit" -->
			<!-- <l-input @input="setValue('FundsApply.Remark', $event)" :value="getValue('FundsApply.Remark')"
				title="申请人" :disabled="!edit" /> -->
			<l-input @input="Statusitem(setValue('FundsApply.Status', $event)) "
				:value="Statusitem(getValue('FundsApply.Status'))" title="审批状态" disabled v-if="!edit" />
			<!--  :disabled="!edit" -->
			<!-- 附件上传 -->
			<l-input
			@input="setValue('FundsApply.Path', $event)"
			:value="getValue('FundsApply.Path')"
			disabled="disabled"
			v-show="false"
			title="附件值"
			/> 
			<uploadFile :number="5" :folderId="folderId" :value="fileList" :readonly="!edit" :title="fileTitle" :required="false"></uploadFile>
		</view>
		
		<view class="welT" style="padding-top: 10px;">
			明细操作
			<text v-if="edit" class="text-xxl cuIcon cuIcon-add" @click="add('FundsApplyDetails')"></text>
		</view>

		<view class="welBox" id="StuInfoFreshEmergePeople" v-show="FundsApplyDetail.length != 0">
			<view class="welCon" v-for="(item, i) in FundsApplyDetail" :key='i'>
				<l-input v-model="item.ProjectContent" title="项目明细" placeholder="请填写" right :disabled="!edit" />
				<l-input v-model="item.Number" type="number" @blur.native.capture="SumAmountChange(item,'Number')" title="数量" :disabled="!edit" placeholder="请填写" right />
				<l-label title="单位">
				  <picker
				    @change="changeitem($event,item)"
				    :range="dataSource.FundsApply.Unit"
				    :disabled="!edit"
					range-key="text"
				  >
				    <view class="picker">{{ item.Unit ? mapitem(item.Unit)  : '请选择单位' }}</view>
				  </picker>
				</l-label>
				<l-input v-model="item.Price" type="digit"  @blur.native.capture="blurChange(item)" title="单价（元）" :disabled="!edit" placeholder="请填写" right />
				<l-input v-model="item.Amount" title="金额（元）" disabled placeholder="请填写" right />
				<!-- <l-select  @input="setValue('item.Unit', $event)" :value="getValue('item.Unit')" :range="dataSource.FundsApply.Unit" title="单位" :disabled="!edit" /> -->
				
				
				
				<view v-if="edit||create" class="welDel" @click="del('FundsApplyDetails', i)"><text
						class="text-xxl cuIcon cuIcon-move"></text></view>
						
				<view  v-if="edit||create" class="welAdd" @click="add('FundsApplyDetails')">
					<text class="text-xxl cuIcon cuIcon-add"></text>
				</view>		
			</view>
		</view>
		
		<view v-if="ready">
			<l-input @input="setValue('FundsApply.SumAmount', $event)" :value="getValue('FundsApply.SumAmount')"
				title="合计" disabled="" /> <!-- v-if="!edit" :disabled="!edit" -->
			<l-input @input="setValue('FundsApply.UpperAmount', $event)" :value="getValue('FundsApply.UpperAmount')"
				title="人民币（大写）" disabled /> <!-- v-if="!edit" :disabled="!edit" -->
		</view>
		
		
		


		<view v-if="ready&&edit" class="bg-white margin-tb padding" style="padding-top: 0; overflow: hidden;">
			<l-button v-if="edit" @click="action('save')" size="lg" color="green" class="block margin-top" block>
				保存
			</l-button>
			<l-button v-if="!edit && mode !== 'create'" @click="action('edit')" size="lg" line="orange"
				class="block margin-top" block>
				编辑本页
			</l-button>
			<l-button v-if="edit && mode !== 'create'" @click="action('reset')" size="lg" line="red"
				class="block margin-top" block>
				取消编辑
			</l-button>
			<l-button v-if="!edit && mode !== 'create'" @click="action('delete')" size="lg" line="red"
				class="block margin-top" block>
				删除
			</l-button>
		</view>
	</view>
</template>


<script>
	/*
	 * 版 本 Learun-ADMS V7.0.3 力软敏捷开发框架(http://www.learun.cn)
	 * Copyright (c) 2013-2021 上海力软信息技术有限公司
	 * 创建人：超级管理员
	 * 日  期：2021-02-21 10:07
	 * 描  述：会议管理
	 */

	/**
	 * 本段代码由移动端代码生成器输出，移动端须 2.2.0 版本及以上可以使用
	 * 请在移动端 /pages.json 中的 pages 字段中添加一条记录：
	 * { "path": "pages/PersonnelManagement/FundsApply/single", "style": { "navigationBarTitleText": "表单详情页" } }
	 * 
	 * （navigationBarTitleText 字段为本页面的标题文本，可以修改）
	 * （必须自行操作该步骤，力软代码生成器不会自动帮您修改 /pages.json 文件）
	 */

	import get from 'lodash/get'
	import set from 'lodash/set'
	import moment from 'moment'
	import customPageMixins from '@/common/custompage.js'
	import uploadFile from '@/components/upload-file2.vue'

	export default {
		mixins: [customPageMixins],
		components:{
		  	uploadFile,
		  },

		data() {
			return {
				// 页面相关参数
				id: null,
				mode: null,
				edit: null,
				ready: false,
				create: null,
				// 表单数据
				current: {},
				origin: {},
				fileList:[],//附件列表
				folderId:null,//附件随机文件夹id
				fileTitle:'附件上传',//附件label值
				FundsApplyDetail: [],
				FundsApplyDetails: {
					ProjectContent: '',
					Number: '',
					Price: '',
					Amount: '',
					Unit:''
				},
				// 表单项数据结构
				scheme: {
					FundsApply: {
						EnCode: {
							type: 'text',
							title: '申报单号'
						},
						ApplyDept: {
							type: "select",
							dataSource: '1',
							dataSourceId: 'ApplyDept'
						},
						ApplyTime: {
							type: 'datetime',
							title: '开始时间',
							dateformat: '1',
							verify: "NotNull"
						},
						ApplyUser: {
							type: "select",
							dataSource: '1',
							dataSourceId: 'ApplyUser'
						},
						DeclarationDept: {
							type: "select",
							dataSource: '1',
							dataSourceId: 'DeclarationDept'
						},
						Informant: {
							type: "select",
							dataSource: '1',
							dataSourceId: 'Informant'
						},
						DeclarationType: {
							type: "select",
							title: '申报类别',
							dataSourceId: 'DeclarationType',
						},
						IsFixedAssets: {
							type: "select",
							title: '是否固定资产',
							dataSource: '1',
							dataSourceId: 'IsFixedAssets',
							verify: 'NotNull'
						},
						Remark: {
							type: 'texteditor',
							title: '备注',
						},
						// Remark: {
						// 	type: 'text',
						// 	title: '申请人',
						// },
						SumAmount: {
							type: 'text',
							title: '合计'
						},
						UpperAmount: {
							type: 'text',
							title: '合计',
							verify: 'NotNull'
						},
						Status: {
							type: 'text',
							title: '审批状态'
						},
						Path: { 
							type: "text",
							title: "附件上传",
						},

					},

				},

				// 数据源
				dataSource: {
					FundsApply: {
						ApplyDept: [],
						ApplyUser: [],
						Informant: [],
						DeclarationDept: [],
						IsFixedAssets: Object.values(this.GET_GLOBAL('dataDictionary').YesOrNoInt).map(t => ({
							value: t.value,
							text: t.text
						})),
						DeclarationType: Object.values(this.GET_GLOBAL('dataDictionary').DeclarationType).map(t => ({
							value: t.value,
							text: t.text
						})),
						Unit:Object.values(this.GET_GLOBAL('dataDictionary').sldw).map(t => ({
							value: t.value,
							text: t.text
						})),
					}
				},
				EnCode: '',
				index:0
			}
		},

		async onLoad({
			type,
			id
		}) {
			// console.log(this.GET_GLOBAL('dataDictionary').sldw,"1")
			// console.log(this.GET_GLOBAL('dataDictionary').DeclarationType,"2")
			await this.init(type, id)
			// console.log(this.dataSource.FundsApply.Unit)
		},

		methods: {
			// 页面初始化
			async init(type, id) {
				this.folderId=this.GUID();
						// console.log('附件随机文件夹id：'+this.folderId);
				this.LOADING('加载数据中...')

				this.id = id
				this.mode = type
				this.edit = ['create', 'edit'].includes(this.mode)

				// 拉取表单数据，同时拉取所有来自数据源的选单数据
				await Promise.all([
					this.FETCH_DATASOURCE('classdata').then(result => {
						this.dataSource.FundsApply.ApplyDept = result.data.map(t => ({
							text: t.name,
							value: t.id
						}));
					}),
					this.FETCH_DATASOURCE('teacheruserdata').then(result => {
						this.dataSource.FundsApply.ApplyUser = result.data.map(t => ({
							text: t.f_realname,
							value: t.f_userid
						}));
					}),
					this.FETCH_DATASOURCE('classdata').then(result => {
						this.dataSource.FundsApply.DeclarationDept = result.data.filter(t=>t.f_deletemark===0).map(t => ({
							text: t.name,
							value: t.id
						}));
					}),
					this.FETCH_DATASOURCE('teacheruserdata').then(result => {
						this.dataSource.FundsApply.Informant = result.data.map(t => ({
							text: t.f_realname,
							value: t.f_userid
						}));
					}),
					// this.dataSource.FundsApply.DeclarationType = Object.values(this.GET_GLOBAL('dataDictionary').DeclarationType).map(t => ({ value: t.value, text: t.text })),// this.FETCH_DATASOURCE('DeclarationType').then(result => {
					//   this.dataSource.FundsApply.DeclarationType = result.data.map(t => ({  value: t.value, text: t.text }))
					// }),
				])
				await this.fetchForm()

				this.ready = true
				this.HIDE_LOADING()
			},

			// 加载表单数据
			async fetchForm() {
				if (this.mode === 'create') {
					const result = await this.HTTP_GET('/learun/adms/FundsApply/getEnCode')
					const source = {
						ApplyDept: this.user.departmentId,
						ApplyUser: this.user.userId,
						ApplyTime: new Date().getTime()
					};
					let resultres = Object.assign(result, source)
					let EnCoderes = {
						FundsApply: resultres,
					}

					this.origin = await this.formatFormData(EnCoderes)

				} else {
					const result = await this.HTTP_GET('/learun/adms/FundsApply/form', this.id)
					result.FundsApply.SumAmount = Number(result.FundsApply.SumAmount).toFixed(2)
					this.origin = await this.formatFormData(result)
					if(result.FundsApplyDetail.length){
						for(let i =0;i<result.FundsApplyDetail.length;i++){
							result.FundsApplyDetail[i].Price = Number(result.FundsApplyDetail[i].Price).toFixed(2)
							result.FundsApplyDetail[i].Amount = Number(result.FundsApplyDetail[i].Amount).toFixed(2)
						}
						this.FundsApplyDetail = result.FundsApplyDetail
					}
				}
				this.current = this.COPY(this.origin)
				
				//加载附件值数据
				  // console.log('附件值赋值前：'+this.getValue('FundsApply.Files'));
				  if (this.getValue('FundsApply.Path') == ""||this.getValue('FundsApply.Path') == undefined ||this.getValue('FundsApply.Path') == null) {
					this.setValue('FundsApply.Path',this.folderId);
					// console.log('附件值赋值后：'+this.getValue('FundsApply.Path'));
				  }else{
					  this.folderId=this.getValue('FundsApply.Path');
					  // console.log('文件夹id赋值后：'+this.folderId);
					  //请求‘获取附件列表’接口
					  this.fileList =[]
					   this.fileList = await this.FETCH_FILEList(this.getValue('FundsApply.Path'));
				  }
			},

			// 点击 「编辑」、「重置」、「保存」、「删除」 按钮
			async action(type) {
				switch (type) {
					case 'edit':
						this.edit = true
						break

					case 'reset':
						this.current = this.COPY(this.origin)
						this.edit = false
						break

					case 'save':
						
						const verifyResult = this.verifyForm()
						if (verifyResult.length > 0) {
							this.CONFIRM('表单验证失败', verifyResult.join('\n'))
							return
						}
						
						if (this.FundsApplyDetail.some((val) => val.ProjectContent== '')) {
							this.CONFIRM('表单验证失败', '明细项目内容不能为空')
						    return;
						}
						if (this.FundsApplyDetail.some((val) => val.Number== '')) {
							this.CONFIRM('表单验证失败', '明细数量不能为空')
						    return;
						}
						if (this.FundsApplyDetail.some((val) => val.Price== '')) {
							this.CONFIRM('表单验证失败', '明细单价不能为空')
						    return;
						}
						if (this.FundsApplyDetail.some((val) => val.Unit== '')) {
							this.CONFIRM('表单验证失败', '明细单位不能为空')
						    return;
						}
						
						if (!(await this.CONFIRM('提交确认', '确定要提交本页表单内容吗？', true))) {
							return
						}
						
						this.LOADING('正在提交...')
						let postData = {
							strEntity: JSON.stringify(this.current.FundsApply),
							fundsApplyDetailList: JSON.stringify(this.FundsApplyDetail)
						}
						// const postData = await this.getPostData(this.id)
						if (this.id) {
							postData.keyValue = this.id
						}

						this.HTTP_POST('/learun/adms/FundsApply/save', postData, '表单提交保存失败')
							.then(success => {
								this.HIDE_LOADING()
								if (!success) {
									return
								}

								this.EMIT('AssetManagementSystemFundsApply-list-change')
								// this.NAV_BACK()
								uni.navigateBack({})
								this.TOAST('提交保存成功')
							})


						break

					case 'delete':
						if (!(await this.CONFIRM('删除项目', '确定要删除本项吗？', true))) {
							return
						}

						this.LOADING('提交删除中...')
						this.HTTP_POST('/Learun/adms/EducationalAdministration/FundsApply/delete', this.id, '删除失败')
							.then(success => {
								this.HIDE_LOADING()
								if (!success) {
									return
								}

								this.EMIT('AssetManagementSystemFundsApply-list-change')
								this.NAV_BACK()
								this.this.TOAST('删除成功', 'success')
							})
						break

					default:
						break
				}
			},

			// 获取表单值
			getValue(path) {
				return get(this.current, path)
			},

			// 设置表单值
			setValue(path, val) {
				set(this.current, path, val)
			},
			async DeclarationDeptChange($event){
				this.setValue('FundsApply.DeclarationDept', $event)
				this.setValue('FundsApply.Informant', '')
				if (this.getValue('FundsApply.DeclarationDept')) {
					this.FETCH_DATASOURCE('teacheruserdata').then(result => {
						this.dataSource.FundsApply.Informant = result.data.sort((a,b)=>{return a.f_realname-b.f_realname}).filter(t=>t.f_departmentid===this.getValue('FundsApply.DeclarationDept')).map(t => ({
							 text: t.f_realname,
							 value: t.f_userid
						}))
					})
					// this.FETCH_DATASOURCE('Acc_FloorData').then(result => {
					//   this.dataSource.Acc_GoodsDemage.Floor = result.data.sort((a,b)=>{return a.dno-b.dno}).filter(t=>t.parentid===this.getValue('FundsApply.DeclarationDept')).map(t => ({ text: t.name, value: t.id })) 
					// })
				}else{
					this.FETCH_DATASOURCE('teacheruserdata').then(result => {
						this.dataSource.FundsApply.Informant = result.data.map(t => ({
							text: t.f_realname,
							value: t.f_userid
						}));
					})
				}
			},
			Statusitem(data) {
				if (data == '0') {
					return '草稿'
				} else if (data == '1') {
					return '审批中'
				} else if (data == '2') {
					return '审批通过'
				} else {
					return data;
				}
			},
			add(str) {
				let jsons = this.COPY(this[str]);
				this.FundsApplyDetail.push(jsons)
				// console.log(this.FundsApplyDetail)
			},
			del(str, num) {
				let _this = this
				this.FundsApplyDetail.splice(num, 1)
				let Amounts = _this.FundsApplyDetail.map(item => {
					return item.Amount
				})
				
				_this.current.FundsApply.SumAmount = _this.sum(Amounts)
				_this.current.FundsApply.UpperAmount = _this.smalltoBIG(_this.current.FundsApply.SumAmount)
			},
			blurChange(item){
				let _this = this
				item.Price  = Number(item.Price).toFixed(2)
				if (item.Number && item.Price) {
					item.Amount = (item.Number * item.Price).toFixed(2)
					// _this.current.SumAmount = item.Number * item.Price
					let Amounts = _this.FundsApplyDetail.map(item => {
						return Number(item.Amount).toFixed(2)
					})
					_this.current.FundsApply.SumAmount = Number(_this.sum(Amounts)).toFixed(2)
					_this.current.FundsApply.UpperAmount = _this.smalltoBIG(_this.current.FundsApply.SumAmount)
				}
			},
			SumAmountChange(item) {
				let _this = this
				item.Number  = Number(item.Number).toFixed(2)
				if (item.Number && item.Price) {
					
					item.Amount = (item.Number * item.Price).toFixed(2)
					// _this.current.SumAmount = item.Number * item.Price
					let Amounts = _this.FundsApplyDetail.map(item => {
						return item.Amount
					})
					_this.current.FundsApply.SumAmount = Number(_this.sum(Amounts)).toFixed(2)
					_this.current.FundsApply.UpperAmount = _this.smalltoBIG(_this.current.FundsApply.SumAmount)
				}

			},
			sum(args) {
				if(args == 0){
					return ''
				}
				// var args = arguments,//获取所有的参数
				var d = 0, //定义小数位的初始长度，默认为整数，即小数位为0
					sum = 0; //定义sum来接收所有数据的和
				//循环所有的参数
				for (var key in args) { //遍历所有的参数
					//把数字转为字符串
					var str = '' + args[key];
					if (str.indexOf(".") != -1) { //判断数字是否为小数
						//获取小数位的长度
						var temp = str.split(".")[1].length;
						//比较此数的小数位与原小数位的长度，取小数位较长的存储到d中
						d = d < temp ? temp : d;
					}
				}
				//计算需要乘的数值
				var m = Math.pow(10, d);
				//遍历所有参数并相加
				for (var key in args) {
					sum += args[key] * m;
				}
				//返回结果
				return sum / m;
			},
			smalltoBIG(n) {
				if(n == 0){
					return ''
				}
				var fraction = ['角', '分'];
				var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
				var unit = [
					['元', '万', '亿'],
					['', '拾', '佰', '仟']
				];
				var head = n < 0 ? '欠' : '';
				n = Math.abs(n);

				var s = '';

				for (var i = 0; i < fraction.length; i++) {
					s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
				}
				s = s || '整';
				n = Math.floor(n);

				for (var i = 0; i < unit[0].length && n > 0; i++) {
					var p = '';
					for (var j = 0; j < unit[1].length && n > 0; j++) {
						p = digit[n % 10] + unit[1][j] + p;
						n = Math.floor(n / 10);
					}
					s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
				}
				return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
			},
			changeitem(e,item){
				// console.log(item)
				item.Unit = this.dataSource.FundsApply.Unit[e.detail.value].value
			},
			mapitem(data){
				// let items = this.dataSource.FundsApply.Unit.find(item=>{
				// 	return item.value == data
				// }).text
				// console.log(items)
				return this.dataSource.FundsApply.Unit.find(item=>{
					return item.value == data
				}).text
			}
		},
		computed: {
			// Price(){
			// 	// return this.FundsApplyDetail.filter(item=>item.Amount)
			// }
		},


		created() {
			this.user = this.GET_GLOBAL('loginUser');
		}
	}
</script>

<style lang="less" scoped>
	.welT {
		font-size: 16px;
		line-height: 26px;
		padding: 0 12px;
		background-color: #ffffff;
		padding-bottom: 12px;
	}

	.welT text {
		width: 26px;
		height: 26px;
		line-height: 24px;
		border: 1px solid #efefef;
		border-radius: 4px;
		float: right;
		text-align: center;
		color: #999;
	}

	.welBox {
		// margin-top: 10px;
	}

	.welCon {
		padding: 10px;
		border: 1px solid #efefef;
		padding-top: 15px;
		border-radius: 4px;
		position: relative;
		// background-color: #ffffff;
		// margin-top: 15px;
	}

	.welDel {
		border-radius: 50%;
		position: absolute;
		top: 4px;
		left: 0px;
		background: #fff;
	}

	.welDel text {
		text-align: center;
		width: 26px;
		height: 26px;
		display: block;
		line-height: 24px;
		border: 1px solid #efefef;
		border-radius: 50%;
	}
	
	.welAdd{
		border-radius: 50%;
		position: absolute;
		top: 4px;
		right: 0px;
		background: #fff;
	}
	.welAdd text {
		text-align: center;
		width: 26px;
		height: 26px;
		display: block;
		line-height: 24px;
		border: 1px solid #efefef;
		border-radius: 50%;
	}
	.welImgAdd {
		text-align: center;
		line-height: 0;
	}

	.passwordDes {
		color: #606266;
		font-size: 14px;
		padding: 8px;
		text-indent: 2em;
	}
</style>
