import {
    observable,
    action,
    computed,
} from 'mobx'
import { Fragment } from 'react'
import {
    WeaForm,
    WeaSwitch,
} from 'comsMobx'
import {
    WeaFormItem,
    WeaSelect,
    WeaCheckbox,
    WeaHelpfulTip,
    WeaInputNumber,
    WeaLocaleProvider,
} from 'ecCom'
import { FormStore, DialogStore } from '../public/valhalla/stores/index.js'
import OvertimeRule from '../components/overtimeRule/OvertimeRule.js'
import { flatten,debounce } from 'lodash'
import { Button, message } from 'antd'
import { i18n } from '../public/i18n.js'
import {addContentPath} from '../util/index.js'
const getLabel = WeaLocaleProvider.getLabel

export default class OvertimeRuleFormStore {
    constructor(store) {
        this.parentStore = store
    }
    //overtimeEnable：允许加班 | computingMode：加班方式计算 | startTime：加班起算时间 | before_startTime：加班起算时间 
    //minimumLen：最小加班时长 | paidLeaveEnableType：加班补偿 | paidLeaveEnableDefaultType：默认加班补偿规则 | paidLeaveEnableFlowType：根据员工在加班流程上选择的加班补偿类型进行补偿
    //paidLeaveEnable：转为调休余额 | lenOfOvertime：加班时长 | lenOfLeave：调休时长 | has_cut_point：自定义跨天加班归属分界点
    //cut_point：自定义跨天加班归属分界点 | restTimeType2：排除休息时间

    errorRefs = {}
    domkeySuffixs = ['2', '3', '1'] //2、3、1分别标识工作日、休息日和节假日
    restTimeTypeShowname = [] //存放【排除休息时间】下拉框选项的showname值
    paidLeaveEnableTypeShowname = [] //存放【加班补偿】下拉框选项的showname值
    paidLeaveEnableDefaultType2Option = [] //【默认加班补偿规则】下拉选项
    paidLeaveEnableFlowType2Option = [] //【根据员工在加班流程上选择的加班补偿类型进行补偿】下拉选项
    //自定义渲染表单元素domkey值的集合
    customRenderKeyList = flatten(this.domkeySuffixs.map(v => ['startTime', 'before_startTime', 'minimumLen', 'maxmumLen','paidLeaveEnable', 'lenOfOvertime', 'lenOfLeave', 'paidLeaveEnableDefaultType', 'paidLeaveEnableFlowType', 'cut_point', 'restTimeType'].map(key => `${key}${v}`)))

    @observable demonstration = []
    @observable overtimeCompensationRuleDefault2 = [] //工作日加班补偿规则
    @observable overtimeCompensationRuleFlow2 = []
    @observable overtimeCompensationRuleDefault3 = [] //休息日...
    @observable overtimeCompensationRuleFlow3 = []
    @observable overtimeCompensationRuleDefault1 = [] //节假日...
    @observable overtimeCompensationRuleFlow1 = []
    @observable restTime2 = [] //工作日排除休息时间
    @observable overtime2 = []
    @observable restTime3 = [] //休息日...
    @observable overtime3 = []
    @observable restTime1 = [] //节假日...
    @observable overtime1 = []
    @observable formStore = new FormStore(this.parentStore.api.getOvertimeRulesForm, this)
    @observable dialogStore = new DialogStore(this)

    renderCustomField = (configs, form) => {
        const { customRenderItem } = this.formStore

        return (
            configs.map(config => {
                const { key, label } = config
                const item = customRenderItem[key]
                if (key && this.customRenderKeyList.includes(key)) {
                    return this.renderFormItem(form, item)
                } else {
                    return <span>{label}</span>
                }
            })
        )
    }

    get DialogButtons() {
        return [
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fs8tr3@1`} type='primary' onClick={this.dialogStore.closeDialog}>{i18n.label['528764']()}</Button>
        ]
    }

    get MoreBtn() {
        return {
            datas: []
        }
    }

    get computingModeTip() {
        return {
            computingMode2: ['528765', '528766', '528767'].map(n => i18n.label[n]()),
            computingMode3: [
                i18n.label['528768']()
            ],
            computingMode1: [
                i18n.label['528769']()
            ]
        }
    }

    get OtherComponents() {
        const { form } = this.formStore
        const { has_cut_point2 } = form.getFormParams()
        const minute = { label: `${i18n.label['528770']().replace('{param}', '')}` }

        return {
            //加班方式计算
            computingMode2: (item, form) => {
                const afterWork = [ //最后一次下班
                    // { label: `${i18n.label['528771']()}: ` },
                    { label: i18n.label['528772']() },
                    { key: 'startTime2' },
                    minute,
                    { label: `, ${i18n.label['528773']()}` }
                ],
                    beforeWork = [ //最早一次上班
                        { label: i18n.label['528774']() },
                        { key: 'before_startTime2' },
                        { label: `${i18n.label['528775']().replace('{param}', '')}, ` },
                        { label: i18n.label['528776']() }
                    ]

                return (
                    <div className='startTime'>
                        <span>{`${i18n.label['528771']()}: `}</span>
                        <div>
                            <p>{this.renderCustomField(afterWork, form)}</p>
                            {(has_cut_point2 == '1') && (
                                <p className='beforeWork'>{this.renderCustomField(beforeWork, form)}<WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@9hfm5e`} title={`${i18n.label['528910']()}，${i18n.label['530043']()}`} /></p>
                            )}
                        </div>
                        {this.renderMinimumLen(item, form, '2')}
                        {this.renderMaxmumLen(item, form, '2')}
                    </div>
                )
            },
            computingMode3: (item, form) => (
                <div className='startTime'>
                    {this.renderMinimumLen(item, form, '3')}
                    {this.renderMaxmumLen(item, form, '3')}
                </div>
            ),
            computingMode1: (item, form) => (
                <div className='startTime'>
                    { this.renderMinimumLen(item, form, '1')}
                    {this.renderMaxmumLen(item, form, '1')}
                </div>
            ),
            //自定义跨天加班归属分界点
            has_cut_point2: (item, form) => this.renderCutPoint(item, form, '2'),
            has_cut_point3: (item, form) => this.renderCutPoint(item, form, '3'),
            has_cut_point1: (item, form) => this.renderCutPoint(item, form, '1'),
            //排除休息时间
            hasRestTime2: (item, form) => this.renderRestTime(item, form, '2'),
            hasRestTime3: (item, form) => this.renderRestTime(item, form, '3'),
            hasRestTime1: (item, form) => this.renderRestTime(item, form, '1')
        }
    }

    get linkageConfigs() {
        return flatten(
            this.domkeySuffixs.map(suffix => [
                {
                    passiveKey: `computingMode${suffix}`,
                    activeKey: `overtimeEnable${suffix}`,
                    showValue: '1'
                },
                {
                    passiveKey: `paidLeaveEnableType${suffix}`,
                    activeKey: `overtimeEnable${suffix}`,
                    showValue: '1'
                },
                {
                    passiveKey: `hasRestTime${suffix}`,
                    activeKey: `overtimeEnable${suffix}`,
                    showValue: '1'
                }
            ])
        )
    }

    renderFormItem = (form, item) => {
        return (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@mv6ery`}
                hideLabel
                tipPosition='bottom'
                error={form.getError(item)}
                errorStyle={{ whiteSpace: 'nowrap' }}
            >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@3hh3sz`}
                    fieldConfig={item}
                    form={form}
                    formParams={form.getFormParams()}
                />
            </WeaFormItem>
        )
    }

    /**
     * 概述：获取自定义cut_point表单元素
     */
    renderCutPoint = (item, form, type) => {
        const fragments = [
            { label: i18n.label['528777']() },
            { key: '' },
        ],
            //【自定义跨天加班归属分界点】开关值
            has_cut_point = form.getFormParams()[`has_cut_point${type}`]

        fragments[1].key = `cut_point${type}`

        return (
            <span className='cutPoint'>
                {(has_cut_point == '1') && this.renderCustomField(fragments, form)}
                <span onClick={() => this.showDemonstration(type)}>{i18n.label['528778']()}</span>
            </span>
        )
    }

    renderRestTime = (item, form, type) => {
        const hasRestTime = form.getFormParams()[`hasRestTime${type}`]
        const { customRenderItem } = this.formStore
        if (hasRestTime == '1') {
            return (
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cbxrav`}
                    fieldConfig={customRenderItem[`restTimeType${type}`]}
                    form={form}
                    formParams={form.getFormParams()}
                    onChange={this.handleFormChange}
                />
            )
        }
    }

    /**
     * 概述：获取自定义minimumLen表单元素
     */
    renderMinimumLen = (item, form, type) => {
        const fragments = [
            { label: `${i18n.label['528779']()}: ` },
            { key: '' },
            { label: `${i18n.label['528770']().replace('{param}', '')}` },
            { label: i18n.label['528780']() }
        ]
        fragments[1].key = `minimumLen${type}`

        return (
            <p className='minimumLen'>{this.renderCustomField(fragments, form)}</p>
        )


    }

    renderMaxmumLen = (item, form, type) => {
        const fragments = [
            { label: `${getLabel('546901','最大加班时长')}: ` },
            { key: '' },
            { label: `${i18n.label['528770']().replace('{param}', '')}` },
            { label: <span/> }
        ]
        fragments[1].key = `maxmumLen${type}`

        return (
            <p className='minimumLen'>{this.renderCustomField(fragments, form)}</p>
        )


    }

    @action getForm = () => {
        const fs = this.formStore
        const { dialog: { type }, table: { id } } = this.parentStore
        const params = {}
        fs.setFormConfig({
            isCustomRender: true,
            isCenter: true,
            customRenderKeyList: this.customRenderKeyList,
            linkageConfigs: this.linkageConfigs,
        })
        if (type == 1) {
            params.ruleId = id
        }
        fs.fetchForm(params, this.extractData, this.afterFormInit)
    }

    saveForm = () => {
        const { form, validateForm } = this.formStore
        const formParams = form.getFormParams()

        window.e9HideFormFieldKeys = flatten(this.domkeySuffixs.map(suffix => ['lenOfOvertime', 'lenOfLeave'].map(prefix => `${prefix}${suffix}`)))


        const getPaidLeaveEnableTypeRule = (suffix) => {
            const {
                paidLeaveEnableTypeValue,
                paidLeaveEnableValue,
                paidLeaveEnableDefaultTypeValue,
                paidLeaveEnableFlowTypeValue
            } = this.getFieldValue(suffix, ['paidLeaveEnableType', 'paidLeaveEnable', 'paidLeaveEnableDefaultType', ' paidLeaveEnableFlowType'])

            if (paidLeaveEnableTypeValue == '1') {
                if (paidLeaveEnableValue == '1') {
                    if (paidLeaveEnableDefaultTypeValue == '1') {
                        return []
                    } else {
                        return this[`overtimeCompensationRuleDefault${suffix}`]
                    }
                } else {
                    return []
                }
            } else {
                if (paidLeaveEnableFlowTypeValue == '1') {
                    return []
                } else {
                    return this[`overtimeCompensationRuleFlow${suffix}`]
                }
            }
        }

        const getRestTimeRule = (suffix) => {
            const {
                hasRestTimeValue,
                restTimeTypeValue
            } = this.getFieldValue(suffix, ['hasRestTime', 'restTimeType'])

            if (hasRestTimeValue == '1') {
                if (restTimeTypeValue == '1') {
                    return this[`restTime${suffix}`].map(data => ({ startTime: data.startTime, endTime: data.endTime, startType: data.startType, endType: data.endType }))
                } else {
                    return this[`overtime${suffix}`].map(data => ({ overtime: data.overtime, exclude: data.exclude }))
                }
            } else {
                return []
            }
        }

        const getRules = () => {
            const params = {}
            this.domkeySuffixs.forEach(suffix => {
                Object.assign(params, {
                    [`paidLeaveEnableTypeRule${suffix}`]: JSON.stringify(getPaidLeaveEnableTypeRule(suffix).filter(data => Object.values(data).every(val => val !== ''))),
                    [`restTimeRule${suffix}`]: JSON.stringify(getRestTimeRule(suffix).filter(data => Object.values(data).every(val => val !== '')))
                })
            })
            return params
        }

        validateForm(form).then(() => {
            if (this.validateRule()) {
                const params = Object.assign({}, form.getFormParams(), getRules())
                const { table: { id }, dialog: { type } } = this.parentStore
                if (type == 1) {
                    params.ruleId = id
                }
                const apiName = (type == 1) ? 'editOvertimeRules' : 'addOvertimeRules'
                this.parentStore.api[apiName](params).then(res => {
                    const { api_status, sign } = res
                    const msg = res.message
                    if (api_status) {
                        if (sign == '1') {
                            message.success(msg)
                            this.parentStore.getSearchList()
                            this.parentStore.dialog.visible = false
                        } else {
                            message.warning(msg)
                        }
                    } else {
                        message.error(msg)
                    }
                })
            }
        })
    }

    getFieldValue = (suffix, prefixs) => {
        const { form } = this.formStore
        const values = {}
        prefixs.forEach(prefix => {
            values[`${prefix}Value`] = form.getFormParams()[`${prefix}${suffix}`]
        })
        return values

    }

    validateRule = () => {
        const { form } = this.formStore
        const formParams = form.getFormParams()
        const requiredWarning = () => { message.warning(i18n.label['528781']()) }
        // const repeatWarning = () => { message.warning(i18n.label['528763']()) }
        const repeatWarning  = () => {}
        // const scopeWarning = () => { message.warning(i18n.label['528782']()) }
        const scopeWarning = () =>{}
        for (let i = 0; i < this.domkeySuffixs.length; i++) {
            const suffix = this.domkeySuffixs[i]
            const prefixs = ['overtimeEnable','paidLeaveEnableType', 'paidLeaveEnable', 'paidLeaveEnableDefaultType', 'paidLeaveEnableFlowType', 'hasRestTime', 'restTimeType', 'lenOfOvertime', 'lenOfLeave']
            const {overtimeEnableValue, paidLeaveEnableTypeValue, paidLeaveEnableValue, paidLeaveEnableDefaultTypeValue, paidLeaveEnableFlowTypeValue, hasRestTimeValue, restTimeTypeValue, lenOfOvertimeValue, lenOfLeaveValue } = this.getFieldValue(suffix, prefixs)
            
            if (overtimeEnableValue != '1') {
                continue
            }
            //加班补偿
            if (
                (paidLeaveEnableTypeValue == '1' && paidLeaveEnableValue == '1') ||
                paidLeaveEnableTypeValue == '2'
            ) {
                const defaultFlowTypeValue = (paidLeaveEnableTypeValue == '1') ? paidLeaveEnableDefaultTypeValue : paidLeaveEnableFlowTypeValue
                if (defaultFlowTypeValue == '1') {
                    if ([lenOfOvertimeValue, lenOfLeaveValue].some(v => !v && v !== 0)) {
                        requiredWarning()
                        return
                    }
                } else {
                    const defaultFlowValue = (paidLeaveEnableTypeValue == '1') ? paidLeaveEnableDefaultTypeValue : paidLeaveEnableFlowTypeValue,
                        ruleType = `defaultFlow${defaultFlowValue}`,
                        rules = this.getTargetRules(suffix, ruleType)

                    if (!this.isRuleComplete(rules)) {
                        requiredWarning()
                        return
                    }

                    if (!this.checkDatasRepeat(rules, suffix, ruleType)) {
                        repeatWarning()
                        return
                    }

                }
            }

            //排除休息时间
            if (hasRestTimeValue == '1') {
                const ruleType = (restTimeTypeValue == '1') ? 'restTime' : 'overtime',
                    rules = this.getTargetRules(suffix, ruleType)

                if (!this.isRuleComplete(rules)) {
                    requiredWarning()
                    return
                }

                if (restTimeTypeValue == '1') {
                    if (!this.checkRestTime(rules)) {
                        return
                    }
                } else {
                    if (!this.checkDatasRepeat(rules, suffix, ruleType)) {
                        repeatWarning()
                        return
                    }

                    if (!this.checkExcludeMoreThanOvertime(rules, suffix, ruleType)) {
                        scopeWarning()
                        return
                    }
                }


            }
        }

        return true
    }

    isRuleComplete = (datas) => {
        return datas.every(data => {
            return Object.keys(data).filter(key => !['disabled', 'errorTip'].includes(key)).map(key => data[key]).every(val => (val || val === 0))
        })
    }

    checkRestTime = (rules) => {
        const calculatedTimePoint = (isToday, time) => {
            const val = !isToday ? 24 : 0;

            let str = (parseFloat(time.replace(':', '.')) + val).toString();
            const hasDecimalPoint = str.includes('.');

            str = hasDecimalPoint ? str : `${str}.0`;

            str = (parseInt(str) < 10) ? `0${str}` : str;

            return str.padEnd(5, 0).replace('.', ':');
        }

        //重新计算后的休息时间
        const recalculatedRestTime = rules.map(data => ({ startTime: calculatedTimePoint(data.startType == '0', data.startTime), endTime: calculatedTimePoint(data.endType == '0', data.endTime) }));

        //开始时间是否大于结束时间
        const isStartLaterThanEnd = recalculatedRestTime.some(data => data.startTime > data.endTime);

        const restPointsArray = flatten(recalculatedRestTime.map(data => [data.startTime, data.endTime]).sort());

        const sortedRestPointsArray = [...restPointsArray].sort();

        //休息时间段是否交叉
        const isRestScheduleCrossing = restPointsArray.some((val,idx) => sortedRestPointsArray[idx] !== val);

        if(isStartLaterThanEnd){
            message.warning(i18n.label['528783']())
			return
        }

        if(isRestScheduleCrossing){
            message.warning(i18n.label['528784']())
            return
        }

        return true;

    }

    extractData = (datas) => {
        const getShowname = (item) => {
            return item.options.map(option => option.showname)
        }
        const extendTitle = (title) => {
            return (
                <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@4ygrcp`}>
                    <span style={{ marginRight: 10 }}>{title}</span>
                    {/* <WeaHelpfulTip title={['528302', '528303', '528304'].map(num => i18n.label[num]()).map(label => <p>{label}</p>)} width={700}/> */}
                </Fragment>
            )
        }
        datas.condition.forEach((c, i) => {
            if (i > 0) {
                c.title = extendTitle(c.title)
            }
            c.items.forEach(item => {
                const [key] = item.domkey
                if (key == 'paidLeaveEnableType2') {
                    this.paidLeaveEnableTypeShowname = getShowname(item)
                }
                if (['paidLeaveEnableDefaultType2', 'paidLeaveEnableFlowType2'].includes(key)) {
                    this[`${key}Option`] = item.options
                }
                if (key == 'restTimeType2') {
                    this.restTimeTypeShowname = getShowname(item)
                }

            })
        })

        Object.keys(datas).forEach(key => this[key] = datas[key]);

        const isRest = (arr) => {
            return arr.some(data => data.startTime)
        }
        this.domkeySuffixs.forEach(suffix => {
            const target = datas[`restTimeRule${suffix}`]

            if (Array.isArray(target)) {
                ['restTime' , 'overtime'].forEach(key => {
                    this[`${key}${suffix}`] = ( (isRest(target) && key == 'restTime') || (!isRest(target) && key == 'overtime') )  ? target : []
                })
            } else {
                ['restTime', 'overtime'].forEach(v => {
                    this[`${v}${suffix}`] = []
                })
            }
        })
    }

    afterFormInit = () => {
        this.handleExcludeRestTimeRule()

        const { form } = this.formStore
        const formParams = form.getFormParams()

        this.domkeySuffixs.forEach(suffix => {
            const target = this[`paidLeaveEnableTypeRule${suffix}`],
                paidLeaveEnableTypeValue = formParams[`paidLeaveEnableType${suffix}`]

            if (Array.isArray(target)) {
                if (paidLeaveEnableTypeValue == '2') {
                    this[`overtimeCompensationRuleFlow${suffix}`] = target
                } else {
                    this[`overtimeCompensationRuleDefault${suffix}`] = target
                }
            }
        })

        this.handleConditionItemOption()

    }

    /**
     * 概述：修改【加班补偿】等表单元素的options
     */
    handleConditionItemOption = () => {
        const { conditions, form, customRenderItem } = this.formStore
        const formParams = form.getFormParams()

        conditions.forEach(c => c.items.forEach(item => {
            const [domkey] = item.domkey;

            this.domkeySuffixs.map(v => {
                const prefixs = [
                    'overtimeEnable', 'paidLeaveEnableType', 'paidLeaveEnable',
                    'lenOfOvertime', 'lenOfLeave', 'paidLeaveEnableDefaultType',
                    'paidLeaveEnableFlowType', 'computingMode', 'restTimeType'
                ],
                    keys = prefixs.map(key => `${key}${v}`),
                    paidLeaveEnableTypeKey = keys[1],
                    computingModeKey = keys[7],
                    restTimeTypeKey = keys[8]

                const [
                    overtimeEnableValue, paidLeaveEnableTypeValue, paidLeaveEnableValue,
                    lenOfOvertimeValue, lenOfLeaveValue, paidLeaveEnableDefaultTypeValue,
                    paidLeaveEnableFlowTypeValue, computingModeValue, restTimeTypeValue
                ] = keys.map(key => formParams[key])

                //加班补偿
                if (domkey == paidLeaveEnableTypeKey) {
                    item.options.forEach((option, index) => {
                        const originName = this.paidLeaveEnableTypeShowname[index]

                        //当选择【无需审批，根据打卡时间计算加班时长】时，此项设置置灰不可选
                        option.disabled = (computingModeValue == '3' && option.key == '2') ? true : false

                        //修改加班补偿选中option的showname
                        if (option.key == paidLeaveEnableTypeValue) {
                            const isOcSelectShow = (paidLeaveEnableTypeValue == '1' && paidLeaveEnableValue == '1') || paidLeaveEnableTypeValue == '2',
                                defaultFlowTypeOptions = (paidLeaveEnableTypeValue == '1') ? this.paidLeaveEnableDefaultType2Option : this.paidLeaveEnableFlowType2Option,
                                defaultFlowTypeValue = (paidLeaveEnableTypeValue == '1') ? paidLeaveEnableDefaultTypeValue : paidLeaveEnableFlowTypeValue,
                                isCpShow = (paidLeaveEnableTypeValue == '1' && paidLeaveEnableDefaultTypeValue == '1') || (paidLeaveEnableTypeValue == '2' && paidLeaveEnableFlowTypeValue == '1')


                            const cName = this.getRuleContainerName(paidLeaveEnableTypeValue, v, 'paidLeaveEnableType'),
                                ocDatas = this[cName],
                                ruleType = (ocDatas.length && ocDatas[0].work !== undefined) ? 'defaultFlow2' : 'defaultFlow3'

                            option.showname = (
                                <div>
                                    <span>{originName}</span>
                                    <div className='paidLeaveEnableType'>
                                        <p>
                                            {/*加班补偿类型为【默认加班补偿规则】，显示【转为调休余额】*/}
                                            {paidLeaveEnableTypeValue == '1' && this.renderPaidLeaveEnable(keys[2], paidLeaveEnableValue)}
                                            {/*如果没有设置调休余额规则，则选中后需联动显示调休余额规则设置提示*/}
                                            {!this.hasTXrules && <span><span>( </span>{`${i18n.label['528785']()}, `}<a href={addContentPath('/spa/hrm/staticAttendance4engine/engine.html#/attendance/holidayRule')} target='_blank'>{i18n.label['528786']()}</a> )</span>}
                                        </p>
                                        {/*加班补偿方式下拉框是否显示*/}
                                        {isOcSelectShow && this.renderPaidLeaveEnableDefaultFlowType(defaultFlowTypeValue, defaultFlowTypeOptions, (paidLeaveEnableTypeValue == '1') ? keys[5] : keys[6])}
                                        {
                                            isOcSelectShow && (
                                                isCpShow ?
                                                    this.renderCompensationProportion(v) :
                                                    this.renderRule(ruleType, ocDatas, v)
                                            )
                                        }
                                    </div>
                                </div>
                            )
                        } else {
                            option.showname = originName
                        }
                    })
                }

                //加班方式计算
                if (domkey == computingModeKey) {
                    const { showname } = item.options[2]
                    item.options[2].showname = this.renderHelpfulTip(computingModeKey, showname)
                }

                //排除休息时间
                if (domkey == restTimeTypeKey) {
                    item.options.forEach((option, index) => {
                        const { key } = option
                        option.showname = this.renderRestTimeTypeRule(key, this.restTimeTypeShowname[index], v)
                    })
                }
            })
        }))
    }

    /**
     * 概述：按加班时长比例转调休时长
     */
    renderCompensationProportion = (groupType) => {
        const { form } = this.formStore
        const formParams = form.getFormParams()
        const [overtimeValue, leaveValue] = ['lenOfOvertime', 'lenOfLeave'].map(v => formParams[`${v}${groupType}`])

        return (
            <p className='lenOfOvertime-lenOfLeave'>
                <span>{i18n.label['528787']()}</span>
                {['lenOfOvertime', 'lenOfLeave'].map(key => {
                    const value = (key == 'lenOfOvertime') ? overtimeValue : leaveValue

                    return (
                        <Fragment ecId={`${this && this.props && this.props.ecId || ''}_Fragment@2waoxg@${key}`}>
                            <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@xbc8oi@${key}`} value={value} onChange={val => this.updateFormFields(val, `${key}${groupType}`)} min={0} precision={2} viewAttr={3} />
                            {key == 'lenOfOvertime' && <span> : </span>}
                        </Fragment>
                    )
                })}
                <span>{`${i18n.label['528788']().replace(/{Param1}|{param1}/, overtimeValue).replace('{param2}', leaveValue)}`}</span>
            </p>

        )
    }

    renderRule = (ruleType, datas, groupType) => {
        const width = { defaultFlow2: 430, defaultFlow3: 500, restTime: 510, overtime: 510 }[ruleType],
            delIndex = { defaultFlow2: 2, defaultFlow3: 1, restTime: 0, overtime: 1 }[ruleType]

        const { form } = this.formStore
        let hasBtn
        if (['defaultFlow2', 'defaultFlow3'].includes(ruleType)) {
            hasBtn = true
        } else {
            const restTimeTypeValue = form.getFormParams()[`restTimeType${groupType}`]
            hasBtn = ((ruleType == 'restTime' && restTimeTypeValue == '1') || (ruleType == 'overtime' && restTimeTypeValue == '2')) ? true : false
        }

        return (
            <OvertimeRule ecId={`${this && this.props && this.props.ecId || ''}_OvertimeRule@l186y3`}
                rowConfigs={this.getRuleRowConfigs(ruleType)}
                datas={datas}
                onChange={this.handleRuleInputNumberChange }
                onAdd={this.handleRuleAdd}
                onDel={this.handleRuleDel}
                onRef={this.setErrorRef}
                onBlur={this.handleBlur}
                groupType={groupType}
                ruleType={ruleType}
                width={width}
                startDelIndex={delIndex}
                hasBtn={hasBtn}
                className={ruleType}
            />
        )
    }

    /**
     * 概述：加班补偿方式下拉框
     */
    renderPaidLeaveEnableDefaultFlowType = (value, options, key) => {
        return (
            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@c3x7my`}
                className='paidLeaveEnableDefaultType'
                value={value}
                options={options}
                onChange={(val) => this.updateFormFields(val, key)}
            />
        )
    }

    /**
     * 概述：转为调休余额
     */
    renderPaidLeaveEnable = (key, value) => {
        return (
            <span>
                <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@yhyout`}
                    value={value}
                    onChange={(val) => this.updateFormFields(val, key)}
                />
                <span className='transToBalance'>{i18n.label['528789']()}</span>
            </span>
        )
    }

    /**
     * 概述：添加提示语
     */
    renderHelpfulTip = (computingModeKey, showname) => {
        if (typeof showname == 'string') {
            return (
                <span>
                    <span>{showname}</span>
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@kvgnh6`} title={this.computingModeTip[computingModeKey].map(tip => <p>{tip}</p>)} />
                </span>
            )

        } else {
            return showname
        }

    }

    /**
     * 概述：渲染【设置休息时间】和【根据加班时长扣除】规则
     */
    renderRestTimeTypeRule = (key, showname, groupType) => {
        const cName = this.getRuleContainerName(key, groupType, 'restTimeType'),
            datas = this[cName],
            ruleType = (key == '1') ? 'restTime' : 'overtime'

        return (
            <div>
                <span>{showname}</span>
                {this.renderRule(ruleType, datas, groupType)}
            </div>
        )
    }

    /**
     * 概述：修改表单元素触发的回调函数
     */
    handleFormChange = (datas) => {
        const key = Object.keys(datas)[0],
            needToHandleConditionKeys = flatten(this.domkeySuffixs.map(v => ['paidLeaveEnableType', 'paidLeaveEnable', 'paidLeaveEnableDefaultType', 'paidLeaveEnableFlowType', 'computingMode', 'lenOfOvertime', 'lenOfLeave', 'restTimeType'].map(key => `${key}${v}`))),
            needToInitOvertimeCompensationRuleKeys = flatten(this.domkeySuffixs.map(v => ['paidLeaveEnableDefaultType', 'paidLeaveEnableFlowType'].map(key => `${key}${v}`)))

        const { form } = this.formStore
        const formParams = form.getFormParams()

        if (key.includes('paidLeaveEnableType') || key.includes('paidLeaveEnableDefaultType') ||key.includes('paidLeaveEnableFlowType')  ) {
            const suffix = key.slice(-1);
            ['lenOfOvertime', 'lenOfLeave'].map(v => {
                form.updateFields({
                    [`${v}${suffix}`] : '1'
                })
            })
        }

        //切换转调休方式时，需要初始化规则
        if (needToInitOvertimeCompensationRuleKeys.includes(key)) {
            this.initOvertimeCompensationRule(datas[key], key.slice(-1))
        }

        //当选择【无需审批，根据打卡时间计算加班时长】时，自动选中【默认加班补偿规则】。
        if (this.domkeySuffixs.map(v => `computingMode${v}`).includes(key)) {
            const { value } = datas[key]
            if (value === '3') {
                form.updateFields({
                    [`paidLeaveEnableType${key.slice(-1)}`]: '1'
                })
            }
        }

        //【按加班的时间段设置转调休时长】的加班补偿方式与【根据加班时长扣除】休息时间的方式不可同时存在！
        if (this.domkeySuffixs.map(v => `paidLeaveEnableDefaultType${v}`).includes(key)) {
            if (datas[key] === '3') {
                const _key = `restTimeType${key.slice(-1)}`
                if (formParams[_key] == '2') {
                    message.warning(i18n.label['528790']())
                }
                form.updateFields({
                    [_key]: '1'
                })
                this.handleExcludeRestTimeRule()
            }
        }

        //切换【加班补偿】选项，重置下拉框中的值
        if (this.domkeySuffixs.map(v => `paidLeaveEnableType${v}`).includes(key)) {
            const groupType = key.slice(-1),
                paidLeaveEnableTypeValue = formParams[`paidLeaveEnableType${groupType}`]
            form.updateFields({
                [`${paidLeaveEnableTypeValue == '1' ? 'paidLeaveEnableFlowType' : 'paidLeaveEnableDefaultType'}${groupType}`]: '1'
            })
        }

        if (needToHandleConditionKeys.includes(key)) {
            this.handleConditionItemOption()
        }
        //【设置休息时间】和【根据加班时长扣除】选项切换
        if (this.domkeySuffixs.map(v => `restTimeType${v}`).includes(key)) {
            this.handleExcludeRestTimeRule()
        }
    }

    /**
     * 概述：更新自定义表单元素(非WeaSwicth渲染)的值
     */
    updateFormFields = (val, key) => {
        if (val === undefined) return
        const { form } = this.formStore
        const data = {
            [key]: val + ''
        }
        form.updateFields(data)
        this.handleFormChange(data)
    }

    /**
     * 概述：初始化加班补偿规则(工作日、休息日和节假日分别只能存在一种加班补偿规则)
     */
    initOvertimeCompensationRule = (value, groupType) => {
        const { form } = this.formStore
        const formParams = form.getFormParams();

        this.domkeySuffixs.forEach(v => {
            if (v == groupType) {
                const paidLeaveEnableTypeValue = formParams[`paidLeaveEnableType${v}`]

                this[this.getRuleContainerName(paidLeaveEnableTypeValue, v, 'paidLeaveEnableType')] = (value == '2') ? [{
                    work: 0,
                    rest: 0
                }, {
                    work: 1,
                    rest: 1
                }] : [{
                    time: '19:00',
                    left: 1,
                    right: 1
                }]
            }
        })
    }

    /**
     * 概述：处理【排除休息时间】规则
     * 当【根据加班时长扣除】没有设置项时，默认添加一条规则
     * 当restTimeTypeValue等于1时，【根据加班时长扣除】所有设置项禁用；当restTimeTypeValue等于2时，则反之
     */
    handleExcludeRestTimeRule = () => {
        const { form } = this.formStore
        this.domkeySuffixs.map(suffix => {
            const restTimeTypeValue = form.getFormParams()[`restTimeType${suffix}`]

            const restTimeArr = this[`restTime${suffix}`],
                overTimeArr = this[`overtime${suffix}`]

            if (!restTimeArr.length) {
                restTimeArr.push({
                    startTime: '',
                    endTime: ''
                })
            }

            if (!overTimeArr.length) {
                overTimeArr.push({
                    overtime: 5,
                    exclude: 1
                })
            }
            ['restTime', 'overtime'].forEach((name, index) => {
                this[`${name}${suffix}`].forEach(item => {
                    item.disabled = ((restTimeTypeValue == '1' && index == 1) || (restTimeTypeValue == '2' && index == 0)) ? true : false
                    item.viewAttr = item.disabled ? 2 : 3
                })
            })
        })
    }


    handleRuleInputNumberChange = (val, index, key, groupType, ruleType) => {
        const rules = this.getTargetRules(groupType, ruleType)
        rules[index][key] = val

        // if (['work', 'time', 'overtime'].includes(key)) {
        //     val && this.checkDatasRepeat(rules, groupType, ruleType)
        // }
        // if (['overtime', 'exclude'].includes(key)) {
        //     val && this.checkExcludeMoreThanOvertime(rules, groupType, ruleType)
        // }
    }

    handleBlur = (value, index, key, groupType, ruleType) => {
        const rules = this.getTargetRules(groupType, ruleType)
        const val = rules[index][key]

        if (['work', 'time', 'overtime'].includes(key)) {
            val && this.checkDatasRepeat(rules, groupType, ruleType)
        }
        if (['overtime', 'exclude'].includes(key)) {
            val && this.checkExcludeMoreThanOvertime(rules, groupType, ruleType)
        }
    }

    /**
     * 概述：示例说明
     */
    showDemonstration = (type) => {
        const url = addContentPath('/hrm/hrm_e9/image/overtimeRule'),
            getLabels = arr => arr.map(n => i18n.label[n]()),
            datas = {
                '2': {
                    title: i18n.label['528791'](),
                    content: [{
                        title: i18n.label['528923'](),
                        desc: getLabels(['528925', '528926', '528927']).concat(`${url}/1.jpg`)
                    }, {
                        title: i18n.label['528924'](),
                        desc: getLabels(['528925', '528928', '528929']).concat(`${url}/2.jpg`).concat(getLabels(['528930', '528931'])).concat(`${url}/3.jpg`)
                    }]
                },
                '3': {
                    title: i18n.label['528792'](),
                    content: [{
                        title: i18n.label['528923'](),
                        desc: getLabels(['528932', '528933']).concat(`${url}/4.jpg`)
                    }, {
                        title: i18n.label['528924'](),
                        desc: getLabels(['528934', '528935']).concat(`${url}/5.jpg`)
                    }]
                },
                '1': {
                    title: i18n.label['528793'](),
                    content: [{
                        title: i18n.label['528923'](),
                        desc: getLabels(['528936', '528937']).concat(`${url}/6.jpg`)
                    }, {
                        title: i18n.label['528924'](),
                        desc: getLabels(['528938', '528939']).concat(`${url}/7.jpg`)
                    }]
                }
            }

        const ds = this.dialogStore
        const { title, content } = datas[type]

        this.demonstration = content

        ds.setDialogConfig({
            title,
            style: { width: 900, height: 675 }
        })
        ds.openDialog()
    }

    getRuleContainerName = (value, groupType, fieldType) => {
        if (fieldType == 'paidLeaveEnableType') {
            return `overtimeCompensationRule${value == '1' ? 'Default' : 'Flow'}${groupType}`
        }
        if (fieldType == 'restTimeType') {
            return `${value == '1' ? 'restTime' : 'overtime'}${groupType}`
        }
    }

    /**
     * 概述：添加规则
     */
    handleRuleAdd = (groupType, ruleType) => {
        const rules = this.getTargetRules(groupType, ruleType)
        const { work, rest, time, left, right } = rules[rules.length - 1]

        switch (ruleType) {
            case 'defaultFlow2':
                rules.push({
                    work: parseInt(work) + 1,
                    rest: parseInt(rest) + 1
                })
                break
            case 'defaultFlow3':
                const [hour, minute] = time.split(':')
                const h = parseInt(hour)
                rules.push({
                    time: h < 23 ? `${h + 1}:${minute}` : `00:${minute}`,
                    left,
                    right: right + 1
                })
                break
            case 'restTime':
                rules.push({
                    startTime: '',
                    endTime: '',
                    startType:'',
                    endType:''
                })
                break
            case 'overtime':
                rules.push({
                    overtime: '',
                    exclude: ''
                })
                break

        }
    }

    /**
     * 概述：删除规则
     */
    handleRuleDel = (index, groupType, ruleType) => {
        const rules = this.getTargetRules(groupType, ruleType)
        rules.splice(index, 1)
    }

    getTargetRules = (groupType, ruleType) => {
        const { form } = this.formStore

        const fieldType = ['defaultFlow2', 'defaultFlow3'].includes(ruleType) ? 'paidLeaveEnableType' : 'restTimeType',
            key = `${fieldType}${groupType}`,
            value = form.getFormParams()[key],
            cName = this.getRuleContainerName(value, groupType, fieldType)

        return this[cName]
    }

    setErrorRef = (ref, index, ruleType = '') => {
        this.errorRefs[`ref${index}${ruleType}`] = ref;
    }

    checkDatasRepeat = (rules, groupType, ruleType) => {
        const targetField = { defaultFlow2: 'work', defaultFlow3: 'time', overtime: 'overtime' }[ruleType],
            verifyDatas = rules.map(rule => parseFloat(rule[targetField]) ),
            repeatIndexs = []

        verifyDatas.forEach((value, index) => {
            const otherValues = verifyDatas.filter((w, i) => { if (i != index) return w })
            if (otherValues.includes(value)) {
                repeatIndexs.push(index)
            }
        })

        setTimeout(() => {
            repeatIndexs.forEach(index => {
                const key = `ref${index}${groupType}`
                this.errorRefs[key] && this.errorRefs[key].showError()
            })
        })

        if (repeatIndexs.length == 0) {
            return true
        }
    }

    checkExcludeMoreThanOvertime = (rules, groupType, ruleType) => {
        for (let i = 0; i < rules.length; i++) {
            const rule = rules[i]
            const { overtime, exclude } = rule
            if (parseFloat(exclude) >= parseFloat(overtime)) {
                rule.errorTip = getLabel(-1, '加班时长必须大于扣除时长')
                const refName = `ref${i}`;
                setTimeout(() => {
                    [refName, `${refName}${ruleType}`].forEach(v => {
                        this.errorRefs[v] && this.errorRefs[v].showError()
                    })
                })
                return
            } else {
                rule.errorTip = ''
            }
        }
        return true
    }

    /**
     * 概述：规则的组成
     */
    getRuleRowConfigs = (type) => {
        let configs;
        const hour = {
            label: i18n.label['528794']().replace('{param}', '')
        }
        switch (type) {
            case 'defaultFlow2':
                configs = [{
                    label: i18n.label['528795']()
                }, {
                    label: ' ≥ '
                }, { key: 'work' },
                    hour,
                {
                    label: `, ${i18n.label['528796']()}`
                }, { key: 'rest' },
                    hour
                ]
                break
            case 'defaultFlow3':
                configs = [{
                    label: i18n.label['528797']().replace('{param}', '')
                }, {
                    key: 'time'
                }, {
                    label: `${i18n.label['528798']().replace('{param}', '')}, `
                }, {
                    label: i18n.label['528799']()
                }, {
                    key: 'left',
                }, {
                    label: ' : '
                }, {
                    key: 'right'
                }, {
                    label: i18n.label['528800']().replace('{param}', '')
                }]
                break
            case 'restTime':
                configs = [{
                    label: i18n.label['528801']()
                    
                },{
                    key: 'startType'
                }, {
                    key: 'startTime'
                }, {
                    label: i18n.label['528802']()
                },{
                    key: 'endType'
                }, {
                    key: 'endTime'
                }]
                break
            case 'overtime':
                configs = [{
                    label: i18n.label['528803']()
                }, {
                    key: 'overtime'
                },
                    hour,
                {
                    label: ','
                }, {
                    label: i18n.label['528804']()
                }, {
                    key: 'exclude'
                },
                    hour
                ]
                break
        }
        return configs

    }


}