<template> 
  <view class="page"> 
    <view v-if="ready">
	 <!-- <l-select
		@input="setValue('Purchase_Travel.DepartmentId', $event)"
		:value="getValue('Purchase_Travel.DepartmentId')"
		:disabled="!edit"
		:range="dataSource.Purchase_Travel.DepartmentId"
		title="申请部门"
		required
		disabled
	  /> -->
	  <l-organize-picker
	    @input="setValue('Purchase_Travel.CreatorId', $event)"
	    :value="getValue('Purchase_Travel.CreatorId')"
	    :readonly="!edit"
	    type="user"
	    title="申请人"
		required
		readonly
	  />
	 <l-datetime-picker
	    @input="setValue('Purchase_Travel.CreateTime', $event)"
	    :value="getValue('Purchase_Travel.CreateTime')"
	    :disabled="!edit"
	    title="申请时间"
		required
	  />
	  <l-input @input="setValue('Purchase_Travel.TravelAddress', $event)" :value="getValue('Purchase_Travel.TravelAddress')" title="出差地址" required :disabled="!edit"/>
	  <l-input @input="setValue('Purchase_Travel.Traveler', $event)" :value="getValue('Purchase_Travel.Traveler')" title="出差人员" required :disabled="!edit"/>
	  <l-textarea
	    @input="setValue('Purchase_Travel.Follows', $event)"
	    :value="getValue('Purchase_Travel.Follows')"
	    :readonly="!edit"
	    title="随行人员"
	  />
	  <l-datetime-picker
	     @input="setValue('Purchase_Travel.Starttime', $event)"
	     :value="getValue('Purchase_Travel.Starttime')"
	     :disabled="!edit"
	     title="开始时间"
	   />
	   <l-datetime-picker
	      @input="setValue('Purchase_Travel.Endtime', $event)"
	      :value="getValue('Purchase_Travel.Endtime')"
	      :disabled="!edit"
	      title="结束时间"
	    />
	  <l-textarea
	    @input="setValue('Purchase_Travel.Reason', $event)"
	    :value="getValue('Purchase_Travel.Reason')"
	    :readonly="!edit"
	    title="出差原因"
	  />
	  <l-upload-file
	    @input="setValue('Purchase_Travel.FilePath', $event)"
	    :value="getValue('Purchase_Travel.FilePath')"
	  	tableName="Purchase_Travel"
		fieldName="FilePath"
	    title="附件"
	    :number="9"
		:readonly="!edit"
	  />
	 <!-- <l-select
	  	@input="setValue('Purchase_Travel.Status', $event)"
	  	:value="getValue('Purchase_Travel.Status')"
	  	:disabled="!edit"
	  	:range="dataSource.Purchase_Travel.Status"
	  	title="是否提交"
	  />
	  <l-datetime-picker
	    @input="setValue('Purchase_Travel.SubmitTime', $event)"
	    :value="getValue('Purchase_Travel.SubmitTime')"
	    :disabled="!edit"
	    title="提交时间"
	  /> -->
	<!--  <l-select
	  	@input="setValue('Purchase_Travel.CheckStatus', $event)"
	  	:value="getValue('Purchase_Travel.CheckStatus')"
	  	:disabled="!edit"
	  	:range="dataSource.Purchase_Travel.CheckStatus"
	  	title="审核状态"
	  />
	  <l-datetime-picker
	    @input="setValue('Purchase_Travel.CheckTime', $event)"
	    :value="getValue('Purchase_Travel.CheckTime')"
	    :disabled="!edit"
	    title="审核时间"
	  />
	  <l-organize-picker
	    @input="setValue('Purchase_Travel.CheckUserId', $event)"
	    :value="getValue('Purchase_Travel.CheckUserId')"
	    :readonly="!edit"
	    type="user"
	    title="审核人"
	  /> -->
	  <!-- <l-input
	    @input="setValue('Purchase_Travel.TotalAmount', $event)"
	    :value="getValue('Purchase_Travel.TotalAmount')"
	    disabled
	    title="采购总价"
		disabled
	  /> -->
	  <!-- <l-customform-table
	    @input="DetailsEntityChange($event)"
	    :value="getValue('Purchase_Travel.Purchase_Travel_Details')"
	    :item="scheme.Purchase_Travel.Purchase_Travel_Details"
	    :edit="edit"
	  /> -->
	</view>
    <!-- 指派审核人弹窗 -->
    	<l-modal v-model="modal" @close="reviewer = ''" title="指派审核人">
    		<l-checkbox-picker @input="(e)=>{reviewer = e}" :value="reviewer" :readonly="false" :range="reviewerList"
    			required title="审核人" />
    		<l-button @click="userAssign" color="blue" class="block" block>确定指派</l-button>
    		<l-button @click="()=>{modal = false;reviewer = ''}" line="blue" class="block margin-top-sm" block>取消</l-button>
    	</l-modal>
        <view v-if="ready && current.Purchase_Travel && current.Purchase_Travel.status != '1'" 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" @click="action('save',true)" size="lg" color="orange" 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-2020 上海力软信息技术有限公司 
 * 创建人：超级管理员 
 * 日  期：2020-10-20 09:25 
 * 描  述：活动安排 
 */
  
/** 
 * 本段代码由移动端代码生成器输出，移动端须 2.2.0 版本及以上可以使用 
 * 请在移动端 /pages.json 中的 pages 字段中添加一条记录： 
 * { "path": "pages/PersonnelManagement/BookBorrow/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 workflowFormMixins from '@/pages/nworkflow/workflow.js'
  
export default {
  mixins: [workflowFormMixins,customPageMixins,], 
  
  data() { 
    return { 
      // 页面相关参数 
      id: null, 
      mode: null, 
      edit: null, 
      ready: false, 
  
      // 表单数据 
      current: {}, 
      origin: {}, 
  
      // 表单项数据结构 
      scheme: { 
        Purchase_Travel: {
          DepartmentId: { type:'select', title: '申请部门' },
		  CreatorId: { type:'organize', title: '申请人' },
		  TravelAddress:{ type:'text', title: '出差地址',verify:'NotNull' },
		  Traveler:{ type:'text', title: '出差人员',verify:'NotNull' },
		  Follows:{ type:'text', title: '随行人员' },
		  Reason:{ type:'text', title: '出差原因'},
		  CreateTime: { type: 'datetime', title: '申请时间', dateformat: '1' }, 
          // TotalAmount: { type:'text', title: '采购总价' },
          // Remark: { type: 'textarea', title: '备注' }, 
		  Starttime:{ type: 'datetime', title: '开始时间', dateformat: '1' },
		  Endtime:{ type: 'datetime', title: '结束时间', dateformat: '1' },
		  FilePath: { type: 'upload', title: '附件' }, 
		  // Status: { type: 'select', title: '是否提交' }, 
		  // SubmitTime:{ type: 'datetime', title: '提交时间', dateformat: '1' },
		  // CheckTime:{ type: 'datetime', title: '审核时间', dateformat: '1' }, 
		  // CheckUserId:{ type: 'organize', title: '审核人' }, 
		  // CheckStatus:{ type: 'select', title: '审核状态', }, 
		 //  Purchase_Travel_Details:{ type: 'girdtable', title: '采购列表', __defaultItem__:{}, fieldsData:[
			// { field:'Name', type:'input', name:'采购物品名称' },
			// { field:'Price', type:'input', name:'价格' },
			// { field:'Quantity', type:'input', name:'采购数量' },
			// { field:'Unit', type:'input', name:'单位' },
			// { field:'UseTo', type:'input', name:'用途' },
		 //  ]},
        },
      },
      // 数据源 
      dataSource: { 
        Purchase_Travel: {
		  DepartmentId:[],
		  Status: [{text:'已提交',value:'1'},{text:'未提交',value:'2'}],
		  CheckStatus:[{text:'审核中',value:'1'},{text:'审核通过',value:'2'},{text:'',value:'草稿'}]
        }, 
  
      },
	  
	  type:null,
	  	  code:null,
	  	  level: '1',
	  	  processId:null,
	  	  // 指派审核人数据
	  	  modal: false,
	  	  userAssignData:{},//收集数据用来判断是否需要审核人
	  	  reviewerListId:'',
	  	  reviewerList:[],
	  	  submitPostData:{},
	  	  reviewer: [],
    }
	
  }, 
  
  async onLoad({ type, id }) { 
    await this.init(type, id) 
  }, 
  
  methods: { 
    // 页面初始化 
    async init(type, id) { 
      this.LOADING('加载数据中...') 
	  
      this.id = id 
      this.mode = type 
      this.edit = ['create', 'edit'].includes(this.mode)
	  
	  this.type = type
	  	  this.code = '0.1'
	  	  const currentTask = this.GET_PARAM()
	  	  // 新建表单则生成
	  	  this.processId = this.GUID('-')
	  	  const processInfo = await this.fetchProcessInfo({ code:this.code })
	  	  const currentNode = this.getCurrentNode(processInfo)
	  	  this.userAssignData.currentTask = currentTask
	  	  this.userAssignData.currentNode = currentNode
	  	  // wfForms 的数组成员 t，表示表单数据项（TAB页），t.type 表示类别，注意它是字符串型，用 Number(t.type) 转换
	  	  // 为 1 则使用工作流表单，依据它的 .formId
	  	  // 不为 1 则使用系统表单，依据它的 .appurl
	  	  const { wfForms } = currentNode
	  	  // 处理没有有效表单的情况，停止加载
	  	  if (!wfForms || wfForms.length <= 0) {
	  	    this.HIDE_LOADING()
	  	    this.TOAST('移动表单数据(wfForms)中无有效表单')
	  	    return
	  	  }
  
      // 拉取表单数据，同时拉取所有来自数据源的选单数据 
      await Promise.all([
		this.FETCH_DATASOURCE('classdata').then(data => {
		  this.dataSource.Purchase_Travel.DepartmentId = data.data.map(t => ({
		  	text: t.name,
		  	value: t.id
		  }));
		}),
        () => {} 
      ])
      await this.fetchForm() 
  
      this.ready = true
      this.HIDE_LOADING() 
    }, 
  
    // 加载表单数据 
    async fetchForm() { 
      if (this.mode === 'create') { 
        this.origin = await this.getDefaultForm()
		let userInfo = this.GET_GLOBAL('loginUser');
		this.origin.Purchase_Travel.DepartmentId = userInfo.departmentId
		this.origin.Purchase_Travel.CreatorId = userInfo.userId
      } else { 
        const result = await this.HTTP_GET('learun/adms/purchasetravel/form', this.id)
        this.origin = await this.formatFormData({Purchase_Travel:{...result.Purchase_Travel}})
      }
      this.current = this.COPY(this.origin)
    },
	
	// 计算采购总价
	DetailsEntityChange($event){
		this.setValue('Purchase_Travel.Purchase_Travel_Details', $event)
		let arr = this.current.Purchase_Travel.Purchase_Travel_Details
		let total = 0
		let isRight = true
		for (let s of arr) {
			let Price = Number(s.Price),Quantity = Number(s.Quantity);
			if(/^(\-|\+)?\d+(\.\d+)?$/.test(Price)&&/^(\-|\+)?\d+(\.\d+)?$/.test(Quantity)){
				total = this.accAdd(total,this.accMul(Price,Quantity))
			}else{
				isRight = false
			}
		}
		this.setValue('Purchase_Travel.TotalAmount', isRight?total:'')
	},
	
	// 乘法函数
	accMul(arg1, arg2){
	    let m = 0,
	        s1 = arg1.toString(),
	        s2 = arg2.toString()
	    try {
	        m += s1.split('.')[1].length
	    } catch (e) {}
	    try {
	        m += s2.split('.')[1].length
	    } catch (e) {}
	    return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
	},
	// 加法函数
	accAdd(arg1, arg2){
	    let r1, r2, m
	    try {
	        r1 = arg1.toString().split('.')[1].length
	    } catch (e) {
	    	r1 = 0
	    }
	
	    try {
	        r2 = arg2.toString().split('.')[1].length
	    } catch (e) {
	    	r2 = 0
	    }
	
	    m = Math.pow(10, Math.max(r1, r2))
	    return (arg1 * m + arg2 * m) / m
	},
	
	// 指派审核人
	    async userAssign() {
	    	this.modal = false
	    	if(!this.reviewer.length){
	    		this.TOAST('请选择审核人')
	    		return
	    	}
	    	this.LOADING('正在提交…')
			let postData = {
			  auditors :JSON.stringify({[this.reviewerListId]:this.reviewer.toString()}),
			  level : this.level,
			   code: this.code,
			   processId: this.processId,
			}
	    	const url = 'learun/adms/newwf/createnoform'
	    	const tips = `流程发起失败`
	    	this.HTTP_POST(url, postData, tips).then(success => {
	    	  this.HIDE_LOADING()
	    	  if (!success) {
	    	    return
	    	  }
			  this.submit1()
	    	})
	    },
	    
	    // 发起流程
	    async submit() {
	      // 判断是否指派审核人
	      let isNext = this.userAssignData.currentNode.isNext
	      Object.assign(this.userAssignData,{ code: 'agree' })
	      if (this.userAssignData.next == '2') {
	    	  isNext = '1';
	      }
	      if (isNext == '1') {
	      	let params = {
	      		code: this.code,
	      		processId: this.processId,
	      		taskId: '',
	      		nodeId: this.userAssignData.currentNode.id,
	      		operationCode: this.userAssignData.code,
	      	}
	    	this.LOADING('正在获取审核人…')
	      	const userList = await this.HTTP_GET('learun/adms/newwf/auditer', params, `获取审核人时发生错误`)
	      	this.HIDE_LOADING()
	    	if (!userList) {
	      		return
	      	}
	      	let arr = Object.entries(userList)
	    	this.reviewerListId = arr[0][0]
	    	this.reviewerList =  arr[0][1].map(item => {
	    	  return {
	    		text: item.Name,
	    		value: item.Id
	    	  }
	      	})
	    	if(this.reviewerList.length>1){
	    		this.modal = true
	    		return
	    	}
	      }
	    
	      this.LOADING('正在提交…')
	      let postData = {
			  auditors :JSON.stringify({}),
			  level : this.level,
			   code: this.code,
			   processId: this.processId,
		  }
	      const url = 'learun/adms/newwf/createnoform'
	      const tips = `流程发起失败`
	      this.HTTP_POST(url, postData, tips).then(success => {
	        this.HIDE_LOADING()
	        if (!success) {
	          return
	        }
			this.submit1()
	      })
	    },
		
		// 提交
		async submit1(){
			// if (!(await this.CONFIRM('提交项目', '是否确认提交该项？', true))) {
			// 	return
			// }
			this.LOADING('正在提交...')
			this.HTTP_POST('learun/adms/purchasetravel/submit', {Id:this.id, ProcessId:this.processId} , '提交失败').then(
				success => {
					this.HIDE_LOADING()
					if (!success) {
						return
					}
					this.TOAST('提交成功', 'success')
					this.EMIT('LogisticsManagement-Purchase_Travel-list-change')
					this.NAV_BACK()
				})
			return
		},
  
    // 点击 「编辑」、「重置」、「保存」、「删除」 按钮 
    async action(type,isSubmit=false) { 
      switch (type) { 
        case 'edit': 
          this.edit = true
          break
  
        case 'reset': 
          this.current = this.COPY(this.origin) 
          this.edit = false
          break
  
        case 'save':
		 //  if(!this.current.Purchase_Travel.TotalAmount){
			// this.CONFIRM('表单验证失败', '[采购列表]：价格和数量为空或错误') 
			// return
		 //  }
          const verifyResult = this.verifyForm()
          if (verifyResult.length > 0) { 
            this.CONFIRM('表单验证失败', verifyResult.join('\n')) 
            return
          }
  
          if (!(await this.CONFIRM('提交确认', '确定要提交本页表单内容吗？', true))) { 
            return
          } 
  
          this.LOADING('正在提交...') 
          const postData = await this.getPostData(this.id)
		  
		  // 处理采购列表数据
		  let strEntity = JSON.parse(postData.strEntity)
		 //  for (let s of strEntity.Purchase_Travel_Details) {
			// s.Price = Number(s.Price);
			// s.Quantity = Number(s.Quantity)
		 //  }
		 //  postData.DetailList = JSON.stringify(strEntity.Purchase_Travel_Details)
		 //  delete strEntity.Purchase_Travel_Details
		  // 赋值部门和人员数据
		  let userInfo = this.GET_GLOBAL('loginUser');
		  let obj = this.dataSource.Purchase_Travel.DepartmentId.find(e=>e.value == this.origin.Purchase_Travel.DepartmentId)
		  strEntity.DepartmentName = obj?obj.text:''
		  strEntity.CreatorName = userInfo.realName
		  
		  postData.strEntity = JSON.stringify(strEntity)
		  // console.log(postData,JSON.parse(postData.strEntity))
          this.HTTP_POST('learun/adms/purchasetravel/save', postData, '表单提交保存失败').then(success => { 
            this.HIDE_LOADING() 
            if (!success) { 
              return
            }
			this.id = success.Id
						if(isSubmit){
							this.submit()
							return
						}
  
            this.EMIT('LogisticsManagement-Purchase_Travel-list-change') 
            setTimeout(()=>this.NAV_BACK(),500)
            this.TOAST('提交保存成功') 
          }) 
          break
  
        case 'delete': 
          if (!(await this.CONFIRM('删除项目', '确定要删除本项吗？', true))) { 
            return
          } 
  
          this.LOADING('提交删除中...') 
          this.HTTP_POST('learun/adms/purchasetravel/delete', this.id, '删除失败').then(success => { 
            this.HIDE_LOADING() 
            if (!success) { 
              return
            } 
  
            this.EMIT('LogisticsManagement-Purchase_Travel-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) 
    },
  } 
} 
</script> 