<template>
  <view id="notice" class="page">
    <!-- 顶部页签 -->
    <l-nav v-model="tab" :items="['表单信息', '流程信息']" type="flex" class="solid-bottom" />
	<view v-if="ready && tab == 0">
	  <!-- <l-input v-model="formData.FundsApply.ApplyUser"  title="填报人" disabled></l-input> -->
	  <l-select v-model="formData.FundsApply.ApplyDept" :range="dataSource.ApplyDept" title="报批部门" disabled></l-select>
	  <l-select v-model="formData.FundsApply.ApplyUser" :range="dataSource.ApplyUser" title="报批人" disabled></l-select>
	  <l-select v-model="formData.FundsApply.DeclarationDept" :range="dataSource.DeclarationDept" title="申报部门" disabled></l-select>
	  <l-select v-model="formData.FundsApply.Informant" :range="dataSource.Informant" title="申报人" disabled></l-select>
	  <l-input v-model="formData.FundsApply.ApplyTime" title="时间" disabled></l-input>
	  <l-select v-model="formData.FundsApply.DeclarationType" :range="dataSource.DeclarationType" title="申报类别" disabled></l-select>
	  <l-input :value="IsFixedAssetsitem(formData.FundsApply.IsFixedAssets)" title="固定资产" disabled></l-input>
	  <l-textarea v-model="formData.FundsApply.Remark" title="备注" readonly/>
	  <l-input v-model="formData.FundsApply.SumAmount" title="总金额" disabled></l-input>
	  <l-input v-model="formData.FundsApply.UpperAmount" title="人民币大写" disabled></l-input>
	  <l-upload-file
	  :value="fileList"
	  :readonly="true"
	  title="附件"
	  />
	 
	 <view class="welT" style="padding-top: 10px;">
	 	明细
	 </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="请填写" disabled right />
	 		<l-input v-model="item.Number" type="number" @change="SumAmountChange(item)" title="数量" disabled  placeholder="请填写" right />
			<l-label title="单位">
			  <picker
			    :range="dataSource.Unit"
				disabled
				range-key="text"
				>
			    <view class="picker">{{ item.Unit ? mapitem(item.Unit)  : '请选择单位' }}</view>
			  </picker>
			</l-label>
	 		<l-input v-model="item.Price" type="number" @change="SumAmountChange(item)" title="单价（元）" disabled placeholder="请填写" right />
	 		<l-input v-model="item.Amount" title="金额（元）" disabled placeholder="请填写" right />
	 	</view>
	 </view>
	 
	 
		
	 
	 
	 
	 
	  <l-workflow-action
	    @audit="audit"
	    @action="action"
	    :type="type"
	    :currentNode="currentNode"
	    :currentTask="currentTask"
	  />
	</view>
	<view v-if="ready && tab == 1" class="progress"><l-workflow-timeline :processList="processList" /></view>
    <!-- <view class="padding-sm text-grey notice-info">
      <view class="text-right">本页内容发布于 {{ time }}</view>
      <view class="text-right">{{ date }}</view>
    </view> -->
  </view>
</template>

<script>
import moment from 'moment'
import workflowFormMixins from '@/pages/nworkflow/workflow.js'

export default {
  mixins: [workflowFormMixins],
  data() {
    return {
	  tab:0,
	  type:'view',
	  currentNode:null,
	  currentTask:null,
	  taskId:'',
	  processId:'',
	  processInfo:null,
	  processList:[],
	  formData:{},
      ready: false,
      content: '',
	  
      time: '',
      date: '',
	  fileList:[],
	  
	  // 数据源
	  dataSource: {
		ApplyDept: [],
		DeclarationDept :[],
		ApplyUser: [],
		Informant:[],
		IsFixedAssets: [],
		DeclarationType:[],
		Unit:Object.values(this.GET_GLOBAL('dataDictionary').sldw).map(t => ({
			value: t.value,
			text: t.text
		})),
	  },
	  
	  FundsApplyDetail: [],
	  FundsApplyDetails: {
	  	ProjectContent: '',
	  	Number: '',
	  	Price: '',
	  	Amount: ''
	  },
	  
	  
    }
  },

  async onLoad({type}) {
    await this.init(type)
  },

  methods: {
    async init(type) {
	  if(type){this.type = type}
	  
	  
	  await Promise.all([
	  	this.FETCH_DATASOURCE('classdata').then(result => {
	  		this.dataSource.ApplyDept = result.data.map(t => ({
	  			text: t.name,
	  			value: t.id
	  		}));
	  	}),
	  	this.FETCH_DATASOURCE('teacheruserdata').then(result => {
	  		this.dataSource.ApplyUser = result.data.map(t => ({
	  			text: t.f_realname,
	  			value: t.f_userid
	  		}));
	  	}),
		this.dataSource.IsFixedAssets = Object.values(this.GET_GLOBAL('dataDictionary').YesOrNoInt).map(t => ({
			value: t.value,
			text: t.text
		})),
		this.FETCH_DATASOURCE('classdata').then(result => {
			this.dataSource.DeclarationDept = result.data.map(t => ({
				text: t.name,
				value: t.id
			}));
		}),
		this.FETCH_DATASOURCE('teacheruserdata').then(result => {
			this.dataSource.Informant = result.data.map(t => ({
				text: t.f_realname,
				value: t.f_userid
			}));
		}),
		this.dataSource.DeclarationType = Object.values(this.GET_GLOBAL('dataDictionary').DeclarationType).map(t => ({ value: t.value, text: t.text })),
		
	  ])
	  // let aaa = Object.values(this.GET_GLOBAL('dataDictionary').DeclarationType).map(t => ({ value: t.value, text: t.text }));
	//   let sss=Object.values(this.GET_GLOBAL('dataDictionary').InventoryResult).map(t => ({ value: t.value, text: t.text }));
	// let a = this.GET_GLOBAL('dataDictionary').DeclarationType;
	// let s = this.GET_GLOBAL('dataDictionary').InventoryResult
	  // console.log(a,s)
      this.LOADING('加载中…')
      const noticeItem = this.GET_PARAM()
	  this.processList = noticeItem.logList
	  this.currentNode = noticeItem.currentNode
	  this.currentTask = noticeItem.currentTask
	  this.processInfo = noticeItem.processInfo
	  this.taskId = this.currentTask.F_TaskId
	  this.processId = this.currentTask.F_Id
	  this.formValue = noticeItem.formValue
	  this.scheme = noticeItem.scheme
	  // console.log(this.processList[0].F_ProcessId)
	  await this.getFormData(this.processList[0].F_ProcessId)
	  this.HIDE_LOADING();
	  
      // this.content = this.CONVERT_HTML(noticeItem.f_content)

      // this.time = moment(noticeItem.f_time).format('HH : mm')
      // this.date = moment(noticeItem.f_time).format('YYYY年 M月 D日')
      // this.SET_TITLE(noticeItem.f_title)
      // this.HIDE_LOADING()
    },
	// 获取表单数据
	getFormData(ProcessId){
		return this.HTTP_GET("learun/adms/FundsApply/shList",{ProcessId},"加载数据时出错").then(async res=>{
			if(res){
				// res.F_SourceName =  res.F_SourceName&&this.GET_GLOBAL('department')[res.F_SourceName]? this.GET_GLOBAL('department')[res.F_SourceName].name : res.F_SourceName
				this.formData = res
				let FundsApplyDetailitem = res.FundsApplyDetail
				if(FundsApplyDetailitem.length>0){
					for(let i=0;i<FundsApplyDetailitem.length;i++){
						FundsApplyDetailitem[i].Price = Number(FundsApplyDetailitem[i].Price).toFixed(2)
						FundsApplyDetailitem[i].Amount = Number(FundsApplyDetailitem[i].Amount).toFixed(2)
					}
				}
				this.FundsApplyDetail = res.FundsApplyDetail
				let fileList = []
				fileList = await this.getFileListById(res.FundsApply.Path);
				if(fileList&&fileList.length){
					this.fileList = fileList
				}
				// let fileList = await this.getFileListById(res.F_NewsImage)
				// if(fileList&&fileList.length){
				// 	this.fileList = [fileList[0]]
				// }
				// this.content = res.F_NewsContent
				this.ready = true
			}
		})
	},
	
	// 点击审批相关按钮
	async audit(action) {
	  this.LOADING('加载中…')
	  const currentTask = this.processInfo.task.find(t => t.F_NodeId === this.currentNode.id)
	  const postData = await this.getPostData(this.formValue, this.scheme)
	  const pageParam = {
	    type: 'sign',
	    processId: currentTask.F_ProcessId,
	    taskId: currentTask.F_Id,
	    formreq: postData.formreq,
	    taskName: this.currentTask.F_Title,
		currentNode:this.currentNode,
		code:this.code||''
	  }
	  // 不是加签
	  if (action.code !== '__sign__') {
	    Object.assign(pageParam, action)
	    pageParam.type = 'verify'
	    pageParam.auditors = JSON.stringify({})
	    pageParam.isFromSignAudit = Number(this.currentTask.F_TaskType) === 3
	  }
	  this.HIDE_LOADING()
	  this.NAV_TO('/pages/nworkflow/myflow/sign', pageParam, true)
	},
	// 点击操作按钮（非审批类按钮）
	async action(taskType) {
	  switch (taskType) {
	    // 点击「催办」/「撤销流程」/「标记已阅」按钮
	    case 'urge':
	    case 'revoke':
	    case 'refer':
	      const actionText = { urge: '催办', revoke: '撤销', refer: '已阅' }[taskType]
	      const actionUrl = { urge: '/urge', revoke: '/revoke', refer: '/refer' }[taskType]
	      
	      let actionData = this.processId
	      if (taskType === 'refer') {
	        actionData = { processId: this.processId, taskId: this.taskId }
	      }
	
	      if (!(await this.CONFIRM(`${actionText}确认`, `确定要提交${actionText}吗？`, true))) {
	        return
	      }
	      this.LOADING(`提交${actionText}中…`)
	      this.HTTP_POST(`/newwf${actionUrl}`, actionData, `提交${actionText}失败`).then(success => {
	        this.HIDE_LOADING()
	        if (success) {
	          this.EMIT('task-list-change')
	          this.TOAST(`成功提交${actionText}`, 'success')
	          if (taskType === 'revoke') {
	            this.NAV_BACK()
	          }
	        }
	      })
	      break
	    // 点击「提交草稿」按钮
	    case 'draft':
		  this.CONFIRM('不支持此操作')
		  return
	      if (!(await this.CONFIRM('提交确认', '确定要提交草稿吗？', true))) {
	        return
	      }
	      this.LOADING('正在提交…')
	      const draftFormValue = this.$refs.form.getFormValue()
	      const draftPostData = await this.getPostData(draftFormValue, this.scheme)
	      this.HTTP_POST('/newwf​/draft', draftPostData, '提交草稿失败').then(success => {
	        this.HIDE_LOADING()
	        if (success) {
	          this.EMIT('task-list-change')
	          this.NAV_BACK()
	          this.TOAST('草稿已保存', 'success')
	        }
	      })
	      break
	    // 点击「发起流程」按钮
	    case 'submit':
		  this.CONFIRM('不支持此操作')
		  return
	      const verifyResult = this.$refs.form.verifyValue()
	      if (verifyResult.length > 0) {
	        this.CONFIRM('表单验证失败', verifyResult.join('\n'))
	        return
	      }
	      if (!(await this.CONFIRM('提交确认', '确定要发起流程吗？', true))) {
	        return
	      }
	      this.LOADING('正在提交…')
	      const formValue = this.$refs.form.getFormValue()
	      const postData = await this.getPostData(formValue, this.scheme)
	      postData.auditors = JSON.stringify({})
	
	      if (this.type === 'child') {
	        postData.parentProcessId = this.processId
	        postData.parentTaskId = this.taskId
	      }
	      const errorTips = '流程发起失败'
	      this.HTTP_POST('/newwf/createchildflow', postData, errorTips).then(success => {
	        this.HIDE_LOADING()
	        if (success) {
	          this.EMIT('task-list-change')
	          this.NAV_BACK()
	          this.TOAST('流程发起成功', 'success')
	        }
	      })
	      break
	    default:
	      break
	  }
	},
	IsFixedAssetsitem(data){
		if(data == 0){
			return '否'
		}else{
			return '是'
		}
	},
	mapitem(data){
		return this.dataSource.Unit.find(item=>{
			return item.value == data
		}).text
	}
  }
}
</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: 18px;
		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%;
	}

	.welImgAdd {
		text-align: center;
		line-height: 0;
	}

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