<template>
  <a-modal
    :title="title"
    :width="1600"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <!-- 主表单区域 -->
      <a-form :form="form">
        <a-row>

          <a-col :span="8">
            <a-form-item label="登记人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-popup
                v-decorator="['registrant', validatorRules.registrant]"
                placeholder="请选择登记人"
                :trigger-change="true"
                org-fields="realname,depart_name"
                dest-fields="registrant,registrantDept"
                code="user_dept"
                @callback="popupCallback"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="登记部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'registrantDept', validatorRules.registrantDept]" placeholder="请输入登记部门" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="报销总额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="[ 'totalAmount', validatorRules.totalAmount]" placeholder="请输入报销总额" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="财务经办人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-popup
                v-decorator="['financeOperator', validatorRules.financeOperator]"
                placeholder="请选择财务经办人"
                :trigger-change="true"
                org-fields="realname,depart_name"
                dest-fields="financeOperator,financeDept"
                code="user_dept"
                @callback="popupCallback"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="财务经办部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'financeDept', validatorRules.financeDept]" placeholder="请输入财务经办部门" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="财务负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="[ 'financeHead', validatorRules.financeHead]" placeholder="请输入财务负责人" disabled></a-input>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="车辆费用报销明细" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="carfareDetailTable.loading"
            :columns="carfareDetailTable.columns"
            :dataSource="carfareDetailTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"
            @valueChange="calculateTotal"
            />
        </a-tab-pane>
        
      </a-tabs>

    </a-spin>
  </a-modal>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'CarfareModal',
    mixins: [JEditableTableMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          span: 6
        },
        wrapperCol: {
          span: 16
        },
        labelCol2: {
          span: 3
        },
        wrapperCol2: {
          span: 20
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          registrant: {rules: [
            {required: true, message: '请选择登记人!'},
          ]},
          registrantDept: {rules: [
          ]},
          totalAmount: {rules: [
            {required: true, message: '请填写完整报销明细!'},
          ]},
          financeOperator: {rules: [
            {required: true, message: '请选择财务经办人!'},
          ]},
          financeDept: {rules: [
          ]},
          financeHead: {rules: [
            {required: true, message: '请输入财务负责人!'},
          ]},
        },
        refKeys: ['carfareDetail', ],
        tableKeys:['carfareDetail', ],
        activeKey: 'carfareDetail',
        // 车辆费用报销明细
        carfareDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '报销日期',
              key: 'reimbursementDate',
              type: FormTypes.date,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '支付凭证编号',
              key: 'paymentNo',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '车牌号',
              key: 'carNo',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '报销人',
              key: 'submitter',
              type: FormTypes.popup,
              popupCode:"user_dept",
              destFields:"submitter,dept",
              orgFieldse:"realname,depart_name",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '部门',
              key: 'dept',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              disabled: true
            },
            {
              title: '报销内容',
              key: 'content',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '金额',
              key: 'amount',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入金额（保留两位小数）' },
              ]
            },
            {
              title: '附件',
              key: 'attachment',
              type: FormTypes.file,
              token:true,
              responseName:"message",
              width:"200px",
              placeholder: '请选择文件',
              defaultValue: '',
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
          ]
        },
        url: {
          add: "/oa/carfare/add",
          edit: "/oa/carfare/edit",
          carfareDetail: {
            list: '/oa/carfare/queryCarfareDetailByMainId'
          },
          user:{
            queryFinanceManager: '/sys/user/queryFinanceManager'
          }
        }
      }
    },
    methods: {
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'registrant','registrantDept','totalAmount','financeOperator','financeDept','financeHead')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.carfareDetail.list, params, this.carfareDetailTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          carfareDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'registrant','registrantDept','totalAmount','financeOperator','financeDept','financeHead'))
     },
     initFinanceManager(){
      
      getAction(this.url.user.queryFinanceManager, { position: '财务经理' }).then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
                financeHead: res.result.realname,
            })
          })
        }
      })
     },
     calculateTotal({ type, row, column, value, target }){
      if(column.key == 'amount'){
        this.$refs.carfareDetail.getValues((error, values) => {
          let totalAmount = 0
          totalAmount = values.map(v=>{
            return Number(v.amount || 0)
          }).reduce((sum,v)=>{
            return sum+v
          },0)
          this.form.setFieldsValue({
            totalAmount: totalAmount.toFixed(2),
          })
        })
      }

     }
    }
  }
</script>

<style scoped>
</style>