UNPKG

ttk-app-core

Version:
1,290 lines 52.4 kB
import React from 'react'
import ReactDOM from 'react-dom'
import { action as MetaAction, AppLoader } from 'edf-meta-engine'
import config from './config'
import { Map, fromJS } from 'immutable'
import moment from 'moment'
import utils, { fetch } from 'edf-utils'
import extend from './extend'
import { consts, common } from 'edf-constant'
import {FormDecorator, Form, Select, Button, DatePicker, Input, Checkbox, CheckboxGroup, Icon, ColumnsSetting} from 'edf-component'

const FormItem = Form.Item
const Option = Select.Option

class action {
    constructor(option) {
        this.metaAction = option.metaAction
        this.extendAction = option.extendAction
        this.voucherAction = option.voucherAction
        this.config = config.current
        this.webapi = this.config.webapi
    }

    onInit = ({ component, injections }) => {
        this.extendAction.gridAction.onInit({ component, injections })
        this.voucherAction.onInit({ component, injections })
        this.component = component
        this.injections = injections
        let addEventListener = this.component.props.addEventListener
        if (addEventListener) {
            addEventListener('onTabFocus', :: this.onTabFocus)
        }
        injections.reduce('init')
        this.initLoad(this.component.props.id || null)
        this.renderNum = 1
    }

    initLoad = async (id) => {
        const response = await this.webapi.delivery.init({ id: id })
        this.injections.reduce('initLoad', response)
    }

    load = async (voucher) => {
        this.injections.reduce('load', voucher)
    }

    onTabFocus = async (params) => {
        params = params.toJS()
        if (params.accessType != 0) {
            if (params.id) {
                this.initLoad(params.id)
            } else {
                this.initLoad(null)
            }
        } else {
            let data = this.metaAction.gf('data').toJS(),
            other = data.other,
            form = data.form,
            isChange = false

            const fileArr = [
                {label:'customer', name: 'Customer'}, 
                {label:'department', name: 'Department'}, 
                {label:'purchasePerson', name: 'Person'},
                {label:'project', name: 'Project'}, 
                {label:'bankAccount', name: 'BankAccount'},
            ]

            const result = await this.webapi.delivery.init(params.id)
            if (result.beginDate.replace(/-/g,'') != other.beginDate.replace(/-/g, '')) {
                isChange = true
                other.beginDate = result.beginDate
            }
            for (let i = 0; i < fileArr.length; i++) {
                const item = fileArr[i]
                if (other[item.label] && form[`${item.label}Id`]) { //找出点击并选择了的档案这样就可以减少没有必要的更新

                    await this.voucherAction[`get${item.name}`]({}, `data.other.${item.label}`)

                    let voucherList = this.metaAction.gf(`data.other.${item.label}`)
                    if (voucherList) {
                        voucherList = voucherList.toJS()
                        let selected = voucherList.find(o => {
                            if (o.id == form[`${item.label}Id`]) {
                                return true
                            } else {
                                return false
                            }
                        })
                        if (!selected) {
                            other[item.label] = voucherList
                            delete form[`${item.label}Id`]
                            delete form[`${item.label}Name`]

                            data.other = other
                            data.form = form
                            isChange = true
                        }
                    }
                }
            }
            isChange && this.metaAction.sf('data', fromJS(data))
        }
    }

    getDom = () => {
        let content = document.getElementsByClassName("edfx-app-portal-content-main"),
        detailsDom = document.getElementsByClassName("app-sa-delivery-card-form-details")[0],
        cardFormHead = document.getElementsByClassName("app-sa-delivery-card-form-header")[0],
        card = content[0],
        cardHeight = card.clientHeight,
        value=[],
        data = this.metaAction.gf('data').toJS(),
        details = data.form.details,
        length = details.length

        // const cardFormHeadHeight = cardFormHead&&cardFormHead.clientHeight ? cardFormHead&&cardFormHead.clientHeight : 106
        const cardFormHeadHeight = cardFormHead&&cardFormHead.clientHeight 
        let height = cardHeight-10 -245- cardFormHeadHeight
        
        let columnSetting = this.metaAction.gf('data.other.columnSetting')
        columnSetting = columnSetting && columnSetting.toJS() 

        if (!detailsDom || !cardFormHeadHeight || !columnSetting) {
            setTimeout(() => {
                this.renderNum = this.renderNum + 1
                return this.getDom()
            },100)
        } else {
            const detailHeight = this.metaAction.gf('data.other.detailHeight')
            this.metaAction.sf('data.other.detailHeight', height + 'px')

            if (card.length != 0) {
                length = Math.ceil(height / 35) > 5 ? Math.ceil(height / 35) : 5
                const blankDetail = {
                    warehouseId: null,
                    inventoryId: null,
                    unitId: null,
                    quantity: null,
                    price: null,
                    taxInclusivePrice: null,
                    taxRateId: null,
                    tax: null,
                    amount: null,
                    taxInclusiveAmount: null
                }
                value = Array(length - 5).fill(blankDetail);
            }
            details = details.concat(value)
            this.injections.reduce('setrowsCount', details, details.length)
        }
    }

    componentDidUpdate = () => {
        console.log(this.metaAction.gf('data.form.details').toJS())
    }

    componentDidMount = () => {
        this.getDom()
        const win = window
        if (win.addEventListener) {
            document.body.addEventListener('keydown', this.bodyKeydownEvent, false)
        } else if (win.attachEvent) {
            document.body.attachEvent('onkeydown', this.bodyKeydownEvent)
        }
        //this.injections.reduce('renderFormRender',false)
    }
    componetWillUnmount = () => {
        const win = window
        if (win.removeEventListener) {
            document.body.removeEventListener('keydown', this.bodyKeydownEvent, false)
        } else if (win.detachEvent) {
            document.body.detachEvent('onkeydown', this.bodyKeydownEvent)
        }
    }

    bodyKeydownEvent = (e) => {
        const dom = document.getElementById('app-sa-delivery-card')
        const modalBody = document.getElementsByClassName('ant-modal-body')
        if (dom && modalBody && modalBody.length<1){
            this.keyDownCickEvent({event:e})
        }
    }

    //监听键盘事件
    keyDownCickEvent = (keydown) => {
        if (keydown && keydown.event) {
            let e = keydown.event
           
            if (e.ctrlKey && e.altKey && (e.key == 'n' || e.keyCode == 78)) { //新增
                // this.add()
                if (e.preventDefault) {
                    e.preventDefault()
                }
                if (e.stopPropagation) {
                    e.stopPropagation()
                }
            }
            else if (e.ctrlKey && !e.altKey && (e.key == 's' || e.keyCode == 83)) { // 保存
                this.save(false)
                if (e.preventDefault) {
                    e.preventDefault()
                }
                if (e.stopPropagation) {
                    e.stopPropagation()
                }
            }
            else if (e.ctrlKey && !e.altKey && (e.key == '/' || e.keyCode == 191)) { // 保存并新增
                this.save(true)
                if (e.preventDefault) {
                    e.preventDefault()
                }
                if (e.stopPropagation) {
                    e.stopPropagation()
                }
            }
            else if (e.ctrlKey && !e.altKey && (e.key == 'y' || e.keyCode == 89)) {
                //审核
                this.audit()
                if (e.preventDefault) {
                    e.preventDefault()
                }
                if (e.stopPropagation) {
                    e.stopPropagation()
                }
            }
            //判断设备是否为mac
            else if (navigator.userAgent.indexOf('Mac OS X') !== -1) {
                if (e.ctrlKey && !e.altKey && (e.key == "[" || e.keyCode == 219)) {
                    //上一张
                    this.prev()
                }

                else if (e.ctrlKey && !e.altKey && (e.key == "]" || e.keyCode == 221)) {
                    //下一张
                    this.next()
                }
            } else {
                if (e.ctrlKey && !e.altKey && (e.key == "[" || e.keyCode == 37 || e.keyCode == 219)) {
                    //219 win7 IE11下的keyCode
                    //上一张
                    this.prev()
                }
                else if (e.ctrlKey && !e.altKey && (e.key == "]" || e.keyCode == 39 || e.keyCode == 221)) {
                    //221 win7 IE11下的keyCode
                    //下一张
                    this.next()
                }
            }
        }
    }

    prev = async () => {
        const code = this.metaAction.gf('data.form.code')
        const response = await this.webapi.delivery.previous({ code,isReturnValue: true })
        if (response) {
            if (response.result == false && response.error) {
                this.metaAction.sfs({
                    'data.other.prevDisalbed':true,
                    'data.other.nextDisalbed': false
                })
                this.metaAction.toast('error', response.error.message)
            } else {
                this.metaAction.sf('data.other.nextDisalbed', false)
                this.load(response)
            }
        }
    }

    next = async () => {
        const code = this.metaAction.gf('data.form.code')
        const response = await this.webapi.delivery.next({ code,isReturnValue: true })
        if (response) {
            if (response.result == false && response.error) {
                this.metaAction.sfs({
                    'data.other.prevDisalbed':false,
                    'data.other.nextDisalbed': true
                })
                this.metaAction.toast('error', response.error.message)
            } else {
                this.metaAction.sf('data.other.prevDisalbed', false)
                this.load(response)
            }
        }
    }

    setting = async () => {
        // this.metaAction.toast('error', '请实现设置功能')
       
        let setting = this.metaAction.gf('data.other.columnSetting')
        setting = setting && setting.toJS()
        let initOption = []

        if (setting) {
            let obj = {
                key: setting.code,
                name: setting.name
            }
            obj.option = setting.header && setting.header.cards

            let detailObj = {}
            const objItem = setting.body.tables[0]
            if (objItem) {
                detailObj.key = objItem.name
                detailObj.name = objItem.caption
                detailObj.option = objItem.details
            }
            initOption.push(obj)
            initOption.push(detailObj)
        }

        const res =  await this.metaAction.modal('show',{
            title: '显示设置',
            width: 500,
            iconType: null,
            children: <ColumnsSetting 
                option={initOption} 
                singleKey='id'
                sort={true}
                editName={true}
                checkedKey='isVisible' 
                labelKey="caption"
            />
        })

        if (res && res.type == 'confirm') {
            this.handleConfirmSet(res.option)
        } else if (res && res.type == 'reset') {
            this.handleResetSet(setting.code)
        }
    }

    //设置 恢复默认设置
    handleResetSet = async (code) => {
        if (code) {
            const result = await this.webapi.delivery.reInitByUser({code: code})
            this.metaAction.sf('data.other.columnSetting', fromJS(result))
        }
    }

    handleConfirmSet = async (params) => {
        if (params) {
            const setting = this.metaAction.gf('data.other.columnSetting').toJS()
            
            const cards = params[0] && params[0].option
            const tables = params[1] && params[1].option

            if (setting) {
                setting.header.cards = cards
                setting.body.tables[0].details = tables
            }

            const result = await this.webapi.delivery.updateWithDetail(setting)
            // console.log(result, 'result')
            this.metaAction.sf('data.other.columnSetting', fromJS(result))
        }
    }

    add = async () => {
        const res = await this.metaAction.modal('confirm',{
            title: '放弃',
            content: '点击放弃会重置你所有的操作,确定要放弃吗?',
        })
        if (res) {
            this.initLoad()
        }
    }

    audit = async () => {
        const id = this.metaAction.gf('data.form.id'),
              ts = this.metaAction.gf('data.form.ts'),
              status = this.metaAction.gf('data.form.status')
        if (!id && !ts) {
            this.metaAction.toast('error', '请保存单据')
            return
        }

        if (status == consts.consts.VOUCHERSTATUS_NotApprove || status == consts.consts.VOUCHERSTATUS_Rejected) {
            // const response = await this.webapi.delivery.audit({ id, ts })
            // this.metaAction.toast('success', '单据审核成功')
            // this.load(response)
            const response = await this.webapi.delivery.audit({ id, ts, isReturnValue: true })
            if (response) {
                if (response.result == false && response.error) {
                    this.metaAction.toast('error', response.error.message)
                } else {
                    this.metaAction.toast('success', '单据审核成功')
                    this.load(response)
                }
            }
        } else {
            // const response = await this.webapi.delivery.unaudit({ id, ts })
            // this.metaAction.toast('success', '单据反审核成功')
            // this.load(response)
            const response = await this.webapi.delivery.unaudit({ id, ts, isReturnValue: true })
            if (response) {
                if (response.result == false && response.error) {
                    this.metaAction.toast('error', response.error.message)
                } else {
                    this.metaAction.toast('success', '单据反审核成功')
                    this.load(response)
                }
            }
        }
    }

    getAuditBtnText = () => {
        const status = this.metaAction.gf('data.form.status')
        return status == consts.consts.VOUCHERSTATUS_Approved ? '反审核' : '审核'
    }

    history = async () => {
        this.component.props.setPortalContent('销售', 'app-sa-delivery-list')
    }

    moreMenuClick = (e) => {
        switch (e.key) {
            case 'del':
                this.del()
                break
            // case 'generateReturn':
            //     this.generateReturn()
            //     break
            case 'receive':
                this.receive()
                break
            case 'antiAudit':
            this.audit()
            break
        }
    }

    del = async () => {
        const id = this.metaAction.gf('data.form.id'),
              ts = this.metaAction.gf('data.form.ts')
        const ret = await this.metaAction.modal('confirm', {
            title: '删除',
            content: '确认删除?'
        })

        if (ret) {
            const response = await this.webapi.delivery.del({ id, ts })
            this.metaAction.toast('success', '删除单据成功')
            this.initLoad()
        }
    }

    generateReturn = async () => {
        //生成红字销售订单
        
        let id = this.metaAction.gf(`data.form.id`),
            ts = this.metaAction.gf(`data.form.ts`)
        if (!id && !ts) {
            voucher.toast('请保存单据!')
            return
        }

        let response = await this.webapi.delivery.init({ "deliveryTypeId": 133 })
        if (response) {
            let responseValue = this.metaAction.gf('data.form').toJS()
            let data = {
                form: {
                    code: responseValue.code,
                    enclosures: responseValue.enclosures,
                    businessDate: responseValue.businessDate,
                    orgId: responseValue.orgId,
                    invoiceNumber: responseValue.invoiceNumber,
                    invoiceCode: responseValue.invoiceCode,
                    creatorName: responseValue.creatorName,
                    //invoiceType: responseValue.invoiceType,
                    invoiceTypeId: responseValue.invoiceType.enumItemId,
                    invoiceTypeName: responseValue.invoiceType.enumItemName,
                    //responseValue.defaultInvoiceTypeName
                    titleText: '红字销售订单',
                    deliveryTypeId: 133,
                    settledAmount: responseValue.settledAmount,
                    totalAmount: responseValue.totalAmount,
                    totalAmountWithTax: responseValue.totalAmountWithTax,
                    totalSettleAmount: responseValue.totalSettleAmount,
                    receiveAmount: responseValue.receiveAmount,
                    remark: responseValue.remark,
                    customerId: responseValue.customer.id,
                    customerName: responseValue.customer.name,
                    departmentId: responseValue.department.id,
                    departmentName: responseValue.department.name,
                    salesPersonId: responseValue.person.id,
                    salesPersonName: responseValue.person.name,
                    bankAccountId: responseValue.bankAccount.id,
                    bankAccountName: responseValue.bankAccount.name,
                    projectId: responseValue.project.id,
                    projectName: responseValue.project.name,
                    details: [

                    ],
                    other: {
                        status: consts.status.VOUCHER_STATUS_ADD,
                    }
                }
            }
            data.form.details = responseValue.details.map(o => {
                if (o.inventory && o.inventory.id) {
                    return {
                        voucherId: o.voucherId,
                        createTime: o.createTime ? moment(o.createTime).format('YYYY-MM-DD HH:mm:ss') : '',
                        amount: -(o.amount),
                        amountWithTax: -(o.amountWithTax),
                        status: o.status,
                        orderNumber: o.orderNumber,
                        inventoryId: o.inventory.id,
                        inventoryName: o.inventory.name,
                        inventoryCode: o.inventory.code,
                        codeAndName: o.inventory.codeAndName,
                        specification: o.inventory.specification,
                        unit: o.inventory.unit,
                        quantity: -(o.quantity),
                        price: o.price,
                        tax: -(o.tax),
                        taxRateId: o.taxRate.id,
                        taxRateName: o.taxRate.name,
                        taxRate: o.taxRate.value,
                        creator: o.creator
                    }
                }
            })

            this.injections.reduce('load', data.form)
        }
    }

    receive = () => {
        // 收款
        const data = this.metaAction.gf('data').toJS()
        data.form.details = data.form.details.filter(o => o.amount)
        let details = data.form.details.map((item) => {
            return {
                businessTypeId: 3001002001001,
                supplierId: data.form.supplierId,
                departmentId: data.form.departmentId,
                personId: data.form.personId,
                projectId: data.form.projectId,
                amount: item.amount,
                fees: null,
                remark: null
            }
        })
        const obj = {
            businessDate: data.form.businessDate,
            // bankAccountId: data.form.bankAccountId,
            summary: null,
            remark: data.form.remark,
            details: details,
            attachments: data.form.attachments
        }
        // console.log(obj, 'obj')
        this.component.props.setPortalContent &&
        this.component.props.setPortalContent(
            '收款单',
            'ttk-scm-app-proceeds-card',
            { accessType: 1, obj}
        )
    }

    getControlVisible = () => {
        let v = true,
            invoiceType = this.metaAction.gf('data.form.invoiceType')
        if (invoiceType) {
            if (invoiceType.get('enumItemId') === consts.ticketType.pp.id) return false
        }
        return v
    }

    save = async (isNew) => {
        if (!this.checkForSave()) return
        let form = this.metaAction.gf('data.form').toJS()
        
        if (form.details) {
            form.details = form.details.filter(detail => {
                return (detail.inventoryId || detail.quantity || detail.price || detail.amount)
            })
        }

        if (form.settles.length != 0) {
            form.settles = form.settles.filter((item) => {
                return item.bankAccountId
            })
            form.settles = form.settles.map((item) => { //去除多余的字段
                if (item.bankAccountName) {
                    delete item.bankAccountName
                }
                return item
            })
        }
        
        let {attachmentFiles, ...otherParmas} = form
        let params = {
            ...otherParmas,
            attachments: attachmentFiles
        }

        const isDisableBank = this.metaAction.gf('data.other.isDisableBank')
        if (isDisableBank) { //退货业务不支持现结
            params.settles = []
        }

        if (params.id || params.id == 0) {
            const response = await this.webapi.delivery.update(params)
            if (response) {
                this.metaAction.toast('success', '保存更新成功')
                if (!isNew) {
                    this.load(response)
                } else {
                    this.initLoad()
                }
            }
        }
        else {
            const response = await this.webapi.delivery.create(params)
            if (response) {
                this.metaAction.toast('success', '保存单据成功')
                if (!isNew) {
                    this.load(response)
                } else {
                    this.initLoad()
                }
            }
        }
    }

    checkForSave = () => {
        const form = this.metaAction.gf('data.form').toJS(),
        chargeAmount = this.metaAction.gf('data.other.chargeAmount'),
        isDisableBank = this.metaAction.gf('data.other.isDisableBank')

        // let msg = this.voucherAction.checkSave(form)
        let msg = this.voucherAction.checkSaveInvoice(form, 'sa')

        if (msg.length > 0) {
            this.metaAction.toast('error', this.getDisplayErrorMSg(msg))
            return false
        }

        let otherErrorMsg = this.voucherAction.checkSaveOtherInvoice(form)
        if (otherErrorMsg.length > 0) {

            this.metaAction.toast('error', this.getDisplayErrorMSg(otherErrorMsg))
            return false
        }

        if (chargeAmount < 0 && !isDisableBank) { //当不是退货 剩余金额小于0时
            this.metaAction.toast('error', '现结金额不能大于价税合计金额')
            return false
        }

        return true
    }

    getDisplayErrorMSg = (msg) => {
        return <div style={{ display: 'inline-table' }}>{msg.map(item => <div>{item}<br /></div>)}</div>
    }

    // cancel = async () => {
    //     await this.voucherAction.cancel()
    // }
    cancel = () => {
        this.injections.reduce('init')
    }

    onFieldChange = (field, storeField,rowIndex,rowData, index) => (id) => {
        if (!field || !storeField) return
        let value = this.metaAction.gf(storeField).find(o => o.get('id') == id)

        if (value) {
            Object.keys(field).forEach(key => {
                this.metaAction.sf(field[key], value.get(key))
            })
        }

        if (storeField == 'data.other.inventory') {
            const amount = utils.number.round(rowData.amount, 2),
                tax = utils.number.round(amount * value.get('taxRate'), 2),
                taxInclusiveAmount = utils.number.round(amount + tax, 2)

            this.metaAction.sfs({
                [`data.form.details.${rowIndex}.taxRateId`]: value.get('rate'),
                [`data.form.details.${rowIndex}.taxRateName`]: value.get('rateName'),
                [`data.form.details.${rowIndex}.taxRate`]: value.get('taxRate'),
                [`data.form.details.${rowIndex}.tax`]: tax,
                [`data.form.details.${rowIndex}.taxInclusiveAmount`]: taxInclusiveAmount,
            })
        }

        if (storeField == 'data.other.bankAccount') {
            if (value) {
                let settles = this.metaAction.gf('data.form.settles')
                settles = settles ? settles.toJS() : []
                const id = value.toJS().id, name = value.toJS().name,amount = this.metaAction.gf('data.form.paymentAmount')
             
                if (settles.length == 0) {
                    const obj ={
                        bankAccountId: id,
                        amount: '',
                        bankAccountName: name,
                    }
                    settles.push(obj)
                } else {
                    settles[index].bankAccountId = id
                    settles[index].bankAccountName = name
                }
               
                this.metaAction.sf('data.form.settles', fromJS(settles))
            }
        }
        this.metaAction.sf('data.other.auditVisible', false)
        // if (storeField == 'data.other.customer') { //现结账户不在由选择客户带出默认
        //     this.customerChange(value)
        // }
    }

    filterOption = (inputValue, option, name) => {
        if (!option || !option.props || !option.props.value) {
            return false
        }
        //需要确定部门项目这些是否也需要支持助记码这些的搜索
        let parmasName = null, parmasNameCode = null
        if (name.currentPath) {
            parmasName= name.currentPath
        }
        if (parmasName.indexOf('supplier') != -1) {
            parmasName = 'supplier'
        } else if (parmasName.indexOf('inventoryCode') != -1) {
            parmasName = 'inventory'
            parmasNameCode = 'inventoryCode'
        } else if (parmasName.indexOf('inventory') != -1) {
            parmasName = 'inventory'
        } else if (parmasName.indexOf('departmentItem') != -1) {
            parmasName = 'department'
        } else if (parmasName.indexOf('projectItem') != -1) {
            parmasName = 'project'
        } else if (parmasName.indexOf('person') != -1) {
            parmasName = 'salesPerson'
        }

        const paramsValues = this.metaAction.gf(`data.other.${parmasName}`),
            value = option.props.value
        let paramsValue = paramsValues.find(item => item.get('id') == option.props.value)

        if (!paramsValue) {
            return false
        }

        if (parmasNameCode && parmasNameCode.indexOf('inventoryCode') != -1) {
            let regExp = new RegExp(inputValue, 'i')
            return paramsValue.get('code').search(regExp) != -1
        } 

        let regExp = new RegExp(inputValue, 'i')
        return paramsValue.get('name').search(regExp) != -1
            || paramsValue.get('helpCode').search(regExp) != -1 // TODO 只支持助记码搜索,简拼
    }

    //存货编码
    // filterOptionCode = (inputValue, option) => {
    //     if (!option || !option.props || !option.props.value) {
    //         return false
    //     }
    //     const paramsValues = this.metaAction.gf(`data.other.inventory`),
    //         value = option.props.value
    //     let paramsValue = paramsValues.find(item => item.get('id') == option.props.value)

    //     if (!paramsValue) {
    //         return false
    //     }
    //     let regExp = new RegExp(inputValue, 'i')
    //     return paramsValue.get('code').search(regExp) != -1
    // }

    getColumnVisible = (params) => {
        let columnSetting = this.metaAction.gf('data.other.columnSetting'), visible = false 
        columnSetting = columnSetting && columnSetting.toJS()
        
        if (columnSetting && !!columnSetting.body && columnSetting.body.tables) {
            columnSetting.body.tables.forEach((item) => {
                if (item.details.length != 0) {
                    visible = item.details.filter(o=> o.fieldName == params )[0].isVisible
                }
            })
        }
        return visible
    }

    customerChange = async (value) => {

        let customerId = value && value.toJS().id
        const response = await this.webapi.delivery.queryByCustomer({ customerId })

        let settles = this.metaAction.gf('data.form.settles')
        settles = settles && settles.toJS()
        // 若在选择客户之前添加了现结账户,将改动第一个
        settles.splice(0,1,{
            bankAccountId: response.bankAccountId,
            bankAccountName: response.bankAccountName,
            amount: ''
        })

        if (response) {
            this.metaAction.sf('data.form.settles', fromJS(settles))
        }
    }

    calc = (col, rowIndex, rowData, params) => (v) => {
        params = Object.assign(params, {
            value: v
        })
        //以下两个if 是为了区分 是否修改了价税合计 
        // 修改了价税合计之后在修改税率 算法是不一样的
        if (col === 'taxInclusiveAmount') {
            this.opertionTaxAmount = true
            this.oldIndex = rowIndex
        }
        if (col === 'taxRateName' && rowIndex == this.oldIndex && this.opertionTaxAmount) {
            params = Object.assign(params, {
                hasChangeTaxAmount: true
            })
        }
        this.voucherAction.calc(col, rowIndex, rowData, params)

        const details = this.metaAction.gf('data.form.details').toJS()
        details.find((item) => { //为了判断是否为退货
            if (item.amount < 0 || item.quantity < 0 || item.quantity < 0 || item.taxInclusiveAmount < 0) {
                this.metaAction.sf('data.other.isDisableBank', true)
                return true
            } else {
                this.metaAction.sf('data.other.isDisableBank', false)
                return false
            }
        })
        this.metaAction.sf('data.other.auditVisible', false)
    }

    calcBalance = (data) => {
        const taxInclusiveAmount = this.voucherAction.sum(data.form.details, (a, b) => a + b.taxInclusiveAmount)
        let paymentAmount = this.metaAction.gf('data.form.paymentAmount'), payAmount = 0
              paymentAmount = utils.number.round(paymentAmount,2) || 0

        let settles = this.metaAction.gf('data.form.settles')
        settles = settles ? settles.toJS() : []

        settles.forEach((item, index) => {
            payAmount = payAmount + item.amount
        })

        const chargeAmount = this.voucherAction.numberFormat(taxInclusiveAmount - payAmount, 2)
        this.metaAction.sf('data.other.chargeAmount', chargeAmount)
        return chargeAmount
    }

    quantityFormat = (quantity, decimals, isFocus) => {
        if (quantity) {
            return this.voucherAction.numberFormat(quantity, decimals, isFocus)
        }
    }

    getControlVisible = () => {
        let visible = true,
            invoiceTypeId = this.metaAction.gf('data.form.invoiceTypeId')
        if (invoiceTypeId) {
            visible = invoiceTypeId != consts.consts.INVOICETYPE_generalVATInvoice
        }
        return visible
    }

    //点击增加 现结账户
    addPaymentAmount = () => {
        let settles = this.metaAction.gf('data.form.settles')
        settles = settles ? settles.toJS() : []
        const obj = {
            bankAccountId: '',
            amount: '',
            bankAccountName: '',
        }
        if (settles.length == 0) settles.push(obj)
        settles.push(obj)
        this.metaAction.sf('data.form.settles', fromJS(settles))
    }

    handlePayBlur = (v, index) => {
        let settles = this.metaAction.gf('data.form.settles')
        settles = settles ? settles.toJS() : []
        if (settles.length == 0) {
            const obj ={
                bankAccountId: '',
                amount: v,
                bankAccountName: '',
            }
            settles.push(obj)
        } else {
            settles[index].amount = v
        }

        this.metaAction.sf("data.form.paymentAmount", v)
        this.metaAction.sf("data.form.settles", fromJS(settles))
    }

    //点击删除 现结账户金额
    delPaymentAmount = (index) => {
        if (index) {
            let settles = this.metaAction.gf('data.form.settles')
            settles = settles ? settles.toJS() : []
    
            settles.splice(index, 1)
            this.metaAction.sf('data.form.settles', fromJS(settles))
        }
    }

    renderPayDiv = () => {
        let settles = this.metaAction.gf('data.form.settles')
        settles = settles ? settles.toJS() : []

        const bankAccount = this.metaAction.gf('data.other.bankAccount'),
            bankAccountName = this.metaAction.gf('data.form.bankAccountName'),
            paymentAmount = this.metaAction.gf('data.form.paymentAmount'),
            isDisableBank = this.metaAction.gf('data.other.isDisableBank')

        return settles.map((item, index) => {
            return <div key={index}>
                <Form className='app-pu-arrival-card-form-footer-settlement'>
                    <FormItem label='现结账户' 
                    >
                        <Select
                            showSearch={false}
                            disabled={this.getDisable() || isDisableBank}
                            placeholder='请选择账户'
                            value={item.bankAccountName ? item.bankAccountName : undefined}
                            onFocus={() => this.voucherAction.getBankAccount({}, `data.other.bankAccount`)}
                            onChange={this.onFieldChange({ id: `data.form.bankAccountId`, name: `data.form.bankAccountName` }, `data.other.bankAccount`, null, null, index)}
                        >
                            {this.handleSelect(bankAccount)}
                        </Select>
                    </FormItem>
                    <FormItem
                        label='现结金额'
                        >
                        <Input.Number
                            disabled={this.getDisable() || isDisableBank}
                            value={item.amount}
                            onBlur={(v) => this.handlePayBlur(v, index)}
                        ></Input.Number>
                    </FormItem>
                    <div className='app-pu-arrival-card-form-footer-paymentAmount-iconDiv'>
                        <Icon
                            type='plus'
                            title='新增'
                            disabled={this.getDisable() || isDisableBank}
                            className='app-pu-arrival-card-form-footer-paymentAmount-iconDiv-iconAdd'
                            onClick={this.addPaymentAmount}></Icon>
                        <Icon
                            type='minus'
                            title='删除'
                            disabled={(index == 0 || isDisableBank) ? true : false}
                            className='app-pu-arrival-card-form-footer-paymentAmount-iconDiv-iconDel'
                            onClick={this.delPaymentAmount.bind(null, index)}></Icon>
                    </div>
                </Form>
            </div>
        })
    }

    //附件的下载操作
    download = (ps) => {
        const form = this.metaAction.gf('data.form').toJS()
        if (form.id) {
            ps = ps.file
        }
        this.voucherAction.download(ps)
    }

    getAccessToken = () => {
        let token = fetch.getAccessToken()
        return { token: token }
    }


    delFile = (index) => {
        this.voucherAction.delFile(index, 'vouchers', this.updateEnclosure)
    }

    updateEnclosure = async (res) => {
        const result = await this.webapi.delivery.updateEnclosure(res)
        return result
    }

    beforeUpload = (info,infoList) => {        
        this.voucherAction.beforeUpload(info,infoList)
    }

    attachmentChange = (info) => {
        this.voucherAction.attachmentChange(info, 'vouchers', this.updateEnclosure)
    }

    signChange = (id) => {
        const signAndRetreat = this.metaAction.gf('data.other.signAndRetreat').toJS()
        signAndRetreat.map((obj) => {
            if (obj.id == id) {
                obj.visible = true
            } else {
                obj.visible = false
            }
        })
        // this.metaAction.sf('data.other.signAndRetreat', fromJS(signAndRetreat))
        this.metaAction.sfs({
            'data.other.signAndRetreat': fromJS(signAndRetreat),
            'data.other.auditVisible': false
        })
    }

    getDisable = () => {
        let pageStatus = this.metaAction.gf('data.other.pageStatus')
        let disabled = pageStatus == common.commonConst.PAGE_STATUS.READ_ONLY
        return disabled
    }

    // getRevenueType = async() => {
    //     const res = await this.webapi.delivery.revenueType({enumId:300012})
    //     if (res) {
    //         this.metaAction.sf("data.other.revenueType", fromJS(res))
    //     }
    // }
  

    //下拉选
    handleSelect = (params) => {
        params = params && params.toJS()
        if (params) {
            return params.map((item,index) => {
                return <Option value={item && item.id}>{item && item.name}</Option>
            })
        }
    }

    //新增档案
    addRecordClick = async (add, params, index, rowData) => {
        if (params == 'inventory') { //新增存货 明细表要带出对应的数据
            await this.voucherAction[add]('data.other.inventoryItem')

            let inventory = this.metaAction.gf('data.other.inventory').toJS()
            const inventoryItem = this.metaAction.gf('data.other.inventoryItem').toJS()
            inventory.push(inventoryItem)
            this.metaAction.sf('data.other.inventory', fromJS(inventory))

            let filed = {
                id:  `data.form.details.${index}.inventoryId`,
                name: `data.form.details.${index}.inventoryName`,
                code: `data.form.details.${index}.inventoryCode`,
                unitId: `data.form.details.${index}.unitId`,
                unitName: `data.form.details.${index}.unitName`,
                taxRateName: `data.form.details.${index}.taxRateName`,
                specification: `data.form.details.${index}.specification`
            }

            this.onFieldChange(filed,'data.other.inventory',index,rowData)(inventoryItem.id)
           
        } else {
            await this.voucherAction[add]({ id: `data.form.${params}Id`, name: `data.form.${params}Name`})
        }
    }

    //新增档案
    handleAddRecord = (paramsU,params,index,rowData) => {
        const add = `add${paramsU}`
        return <Button type='primary' 
        style={{ width: '100%', borderRadius: '0' }}
        onClick={this.addRecordClick.bind(null,add,params,index,rowData)}
        >新增</Button>
    }
    
    //控制显示
    handleVisible = (params) => {
        let columnSetting = this.metaAction.gf('data.other.columnSetting')
        columnSetting = columnSetting && columnSetting.toJS()
        if (columnSetting) {
            return !!columnSetting.header && columnSetting.header.cards.filter(o=> o.fieldName == params )[0].isVisible
        }
    }

    //记账日期控制
    handleDisabledDate = (current) => {
        // Can not select days before today and today
        let beginDate = this.metaAction.gf('data.other.beginDate'), currentDate = current.format('YYYY-MM-DD')
        beginDate = beginDate.replace(/-/g, '')
        currentDate = currentDate.replace(/-/g, '')

        return currentDate && currentDate < beginDate
    }

    filterOptionArchives = (name,inputValue, option) => {
        const namePrmas = {
            currentPath: name
        }
        return this.filterOption(inputValue, option, namePrmas)
    }

    renderArchives = () => {
        let columnSetting = this.metaAction.gf('data.other.columnSetting'),
        departmentName = this.metaAction.gf('data.form.departmentName')?this.metaAction.gf('data.form.departmentName'):undefined,
        salesPersonName = this.metaAction.gf('data.form.salesPersonName')?this.metaAction.gf('data.form.salesPersonName'): undefined,
        projectName = this.metaAction.gf('data.form.projectName') ? this.metaAction.gf('data.form.projectName') : undefined,
        department = this.metaAction.gf('data.other.department')&&this.metaAction.gf('data.other.department'),
        salesPerson = this.metaAction.gf('data.other.salesPerson')&&this.metaAction.gf('data.other.salesPerson'),
        project = this.metaAction.gf('data.other.project')&&this.metaAction.gf('data.other.project')

        columnSetting = columnSetting && columnSetting.toJS()
        const archivesArr = [
            {label:'部门', name: 'department', upName: 'Department', value: departmentName, optionArr: department},
            {label:'业务员', name: 'salesPerson', upName: 'Person', value: salesPersonName, optionArr: salesPerson},
            {label:'项目', name: 'project', upName: 'Project', value: projectName, optionArr: project},   
        ]
        
        if (columnSetting) {
           let domArr = archivesArr.map((item) => {
               let isVisible = !!columnSetting.header && columnSetting.header.cards.filter(o=> o.fieldName == item.name )[0].isVisible
               if (isVisible) {
                    return (
                        <FormItem label={item.label}>
                            <Select
                                showSearch={true}
                                filterOption={this.filterOptionArchives.bind(null, item.name)}
                                placeholder='按名称/拼音搜索'
                                disabled={this.getDisable()}
                                value={item.value}
                                onFocus={() => this.voucherAction[`get${item.upName}`]({}, `data.other.${item.name}`)}
                                dropdownFooter={this.handleAddRecord(`${item.upName}`, `${item.name}`)}
                                onChange={this.onFieldChange({ id: `data.form.${item.name}Id`, name: `data.form.${item.name}Name` }, `data.other.${item.name}`)}
                            >
                                {this.handleSelect(item.optionArr)}
                            </Select>
                        </FormItem>
                    )
               } else {
                   return null
               }
            })
            return domArr
        }
    }

    handleChange = (name,value) => {
        let obj = {
            'data.other.auditVisible': false
        }
        obj[name] = value
        this.metaAction.sfs(obj)
    }
  
    renderFormContent = () => {
        const businessDate = this.metaAction.gf('data.form.businessDate'),
              invoiceTypeName = this.metaAction.gf('data.form.invoiceTypeName'),
              invoiceType = this.metaAction.gf('data.other.invoiceType'),
              customerName = this.metaAction.gf('data.form.customerName'),
              customer = this.metaAction.gf('data.other.customer'),
              invoiceCode = this.metaAction.gf('data.form.invoiceCode'),
              invoiceNumber = this.metaAction.gf('data.form.invoiceNumber'),
              invoiceDate = this.metaAction.gf('data.form.invoiceDate'),
              commonlyProject = this.metaAction.gf('data.form.commonlyProject'),
              signProject = this.metaAction.gf('data.form.signProject'),
              remark= this.metaAction.gf('data.form.remark'),
              isSignAndRetreat = this.metaAction.gf('data.other.isSignAndRetreat')

        let signAndRetreat = this.metaAction.gf('data.other.signAndRetreat')//即征即退列表
            signAndRetreat = signAndRetreat && signAndRetreat.toJS()

        let defaultContentArr = [
            <FormItem label='记账日期' required={true}>
                <DatePicker
                    value={this.metaAction.stringToMoment(businessDate)}
                    // onChange={(d) => this.metaAction.sf('data.form.businessDate', this.metaAction.momentToString(d, 'YYYY-MM-DD'))}
                    onChange={(d) => this.handleChange("data.form.businessDate", this.metaAction.momentToString(d, 'YYYY-MM-DD'))}
                    disabled={this.getDisable()}
                    disabledDate={this.handleDisabledDate}
                    >
                </DatePicker>
            </FormItem>,
            <FormItem label='票据类型' required={true}>
                <Select
                    disabled={this.getDisable()}
                    value={invoiceTypeName}
                    onChange={this.onFieldChange({ id: `data.form.invoiceTypeId`, name: `data.form.invoiceTypeName` }, `data.other.invoiceType`)}
                >
                    {this.handleSelect(invoiceType)}
                </Select>
            </FormItem>,
            <FormItem label='客户' required={true}>
                <Select
                    showSearch={true}
                    filterOption={this.filterOptionArchives.bind(null, 'customer')}
                    placeholder='按名称/拼音搜索'
                    disabled={this.getDisable()}
                    value={customerName}
                    onFocus={() => this.voucherAction.getCustomer({}, `data.other.customer`)}
                    dropdownFooter={this.handleAddRecord('Customer', 'customer')}
                    onChange={this.onFieldChange({ id: `data.form.customerId`, name: `data.form.customerName` }, `data.other.customer`)}
                >
                    {this.handleSelect(customer)}
                </Select>
            </FormItem>,
            this.handleVisible('invoiceCode') ?
            <FormItem label='发票代码'>
                <Input
                    value={invoiceCode}
                    // onChange={(e)=>this.metaAction.sf("data.form.invoiceCode",e.target.value)}
                    onChange={(e) => this.handleChange("data.form.invoiceCode", e.target.value)}
                    disabled={this.getDisable()}>
                </Input>
            </FormItem>:null,
            this.handleVisible('invoiceNumber') ?
            <FormItem label='发票号码'>
                <Input
                    value={invoiceNumber}
                    maxLength={8}
                    // onChange={(e)=>this.metaAction.sf("data.form.invoiceNumber",e.target.value)}
                    onChange={(e) => this.handleChange("data.form.invoiceNumber", e.target.value)}
                    disabled={this.getDisable()}>
                </Input>
            </FormItem>: null,
            this.handleVisible('invoiceDate') ?
            <FormItem label='开票日期'>
                <DatePicker
                    value={this.metaAction.stringToMoment(invoiceDate)}
                    // onChange={(d) => this.metaAction.sf('data.form.invoiceDate', this.metaAction.momentToString(d, 'YYYY-MM-DD'))}
                    onChange={(d) => this.handleChange('data.form.invoiceDate', this.metaAction.momentToString(d, 'YYYY-MM-DD'))}
                    disabled={this.getDisable()}>
                </DatePicker>
            </FormItem>:null
        ]
        const defaultContentArr2 = [
            isSignAndRetreat ?
                <FormItem label='征收方式' className='app-sa-delivery-card-form-header-taxWay' >
                    {
                        signAndRetreat ? signAndRetreat.map((item) => {
                            if (item.visible == undefined) {
                                if (item.name == '一般项目') {
                                    item.visible = true
                                } else {
                                    item.visible = false
                                }
                            }
                            return <Checkbox 
                            checked={item.visible}
                            disabled={this.getDisable()} 
                            onChange={() => this.signChange(item.id)}>{item.name}</Checkbox>
                        }) : null
                    }
                </FormItem> 
                : null
            ,
            this.handleVisible('remark') ?
            <FormItem label='备注' className={isSignAndRetreat ? 'app-sa-delivery-card-form-header-remark' : 'app-sa-delivery-card-form-header-remark1'}>
                <Input
                    value={remark}
                    // onChange={(e) => this.metaAction.sf("data.form.remark", e.target.value)}
                    onChange={(e) => this.handleChange("data.form.remark", e.target.value)}
                    disabled={this.getDisable()}>
                </Input>
            </FormItem> : null
        ]

        if (this.renderArchives()) { //档案类
            const archives = this.renderArchives().filter(o => o)
            archives.forEach((item) => {
                defaultContentArr.push(item)
            })
        }

        defaultContentArr = defaultContentArr.concat(defaultContentArr2)
        return defaultContentArr
    }

}

export default function creator(option) {
    const metaAction = new MetaAction(option),
        extendAction = extend.actionCreator({ ...option, metaAction }),
        voucherAction = FormDecorator.actionCreator({ ...option, metaAction }),
        o = new action({ ...option, metaAction, extendAction, voucherAction }),
        ret = { ...metaAction, ...extendAction.gridAction, ...voucherAction, ...o }

    metaAction.config({ metaHandlers: ret })

    return ret
}