import { observable, action, computed } from "mobx"
import NumberComposition from './numberComposition'
import NumberFlowRule from './numberFlowRule'
import StartReservedNumberSet from './startReservedNumberSet'
import { message } from 'antd'
import { last } from 'lodash'
import * as api from '../../apis/serialNumber.js'
import { i18n } from "../../public/i18n"
import {AuthorityStore} from '../../public/valhalla/stores/index.js'

//人员编号设置
export class ResourceNumberSettingStore {
    serialtype = 'USER'

    get dropMenuDatas(){
        return [{
            key: "1",
            icon: <i className='icon-coms-Preservation' />,
            content: i18n.button.save(),
            onClick: this.handleSave
        }, {
            key: "2",
            icon: <i className='icon-coms-Print-log' />,
            content: i18n.button.log(),
            onClick: this.handleLog
        }]
    } 
    @observable numberCompositionStore = new NumberComposition(this)
    @observable numberFlowRuleStore = new NumberFlowRule()
    @observable startReservedNumberSetStore = new StartReservedNumberSet()
    @observable generationSwitchChecked = '0'
    @observable authorityStore = new AuthorityStore(api.getHasRight)

    @computed get hasNumberComposition() {
        return this.generationSwitchChecked == '1'
    }

    @computed get hasNumberFlowRule() {
        const { hasFlowRuleField } = this.numberCompositionStore

        return (this.generationSwitchChecked == '1' && hasFlowRuleField)
    }

    @computed get hasStartReservedNumberSet() {
        return this.generationSwitchChecked == '1'
    }

    get saveParams() {
        const { serialFieldDatas } = this.numberCompositionStore
        const { dateChecked, dateOptionValue, orgChecked, orgOptionValue, postChecked } = this.numberFlowRuleStore
        const params = {
            datas: JSON.stringify({
                serialenable: this.generationSwitchChecked,
                details: this.transSerialFieldDatasToDetails(serialFieldDatas),
                dateSerial: { enable: dateChecked, key: dateChecked != '0' ? this.transIdToRuletype(dateOptionValue) : 'YEAR' },
                deptSerial: { enable: orgChecked, key: orgChecked != '0' ? this.transIdToRuletype(orgOptionValue) : 'SUBCOMPANY' },
                jobtitlesSerial: { enable: postChecked, key: 'JOBTITLES' },
                serialtype: this.serialtype
            })
        }
        return params
    }

    init = () => {
        const params = {
            serialtype: this.serialtype
        }
        this.authorityStore.fetchAuthority(params).then(() => {
            this.numberFlowRuleStore.rely(this.numberCompositionStore)
            this.numberCompositionStore.rely(this.numberFlowRuleStore)
            this.startReservedNumberSetStore.rely(this)
            this.numberCompositionStore.extendSerialFieldOptions([
                { key: '5', showname: i18n.label.subNumber(), selected: false },
                { key: '6', showname: i18n.label.deptNumber(), selected: false },
                { key: '7', showname: i18n.label.postNumber(), selected: false },
            ])
            this.getCodeSetting()
        })
    }

    @action getCodeSetting = () => {
        const params = {
            serialtype: this.serialtype
        }
        api.getCodeSetting(params).then(res => {
            if (res.api_status) {
                this.resAdapter(res)
            } else {
                message.error(res.message)
            }
        })
    }

    /**
     * 概述：数据适配(对接口返回的数据进行转换)
     */
    resAdapter = (res) => {
        const { dateSerial, serialenable, details, deptSerial,jobtitlesSerial } = res
        const { setSerialFieldDatas } = this.numberCompositionStore
        const { setDateChecked, setDateOptionValue, setOrgChecked, setOrgOptionValue,setPostChecked } = this.numberFlowRuleStore
        this.generationSwitchChecked = serialenable

        if (details.length > 0) {
            setSerialFieldDatas(this.transDetailToSerialFieldDatas(details))
        }
        if (dateSerial) {
            setDateChecked(dateSerial.enable)
            setDateOptionValue(this.transKeyToDateOptionValue(dateSerial.key))

            setOrgChecked(deptSerial.enable)
            setOrgOptionValue(this.transKeyToDateOptionValue(deptSerial.key))

            setPostChecked(jobtitlesSerial.enable);
        }
    }

    /**
     * 概述：接口返回的数据格式 {ruletype:'YEAR',rulevalue:'2',showorder:'2'}
     *      需要的数据格式{id:'year#',text:'当前年份',input:'当前年份'}
     * @param  {[Array]} details [接口返回的编号组成数据]
     * @return {[Array]}         [转换后的编号组成数据]
     */
    transDetailToSerialFieldDatas = (details) => {
        const serialFieldDatas = []
        const obj = {
            YEAR: {
                id: 'year#',
                text: i18n.label.curYear(),
                input: i18n.label.curYear()
            },
            MONTH: {
                id: 'month#',
                text: i18n.label.curMonth(),
                input: i18n.label.curMonth()
            },
            DAY: {
                id: 'date#',
                text: i18n.label.curDate(),
                input: i18n.label.curDate()
            },
            NUMBER: {
                id: 'serial',
                text: i18n.label.numberDigits(),
                input: 3
            },
            SUBCOMPANY: {
                id: 'sub#',
                text: i18n.label.subNumber(),
                input: i18n.label.subNumber()
            },
            DEPARTMENT: {
                id: 'dept#',
                text: i18n.label.deptNumber(),
                input: i18n.label.deptNumber()
            },
            JOBTITLES: {
                id: 'post#',
                text: i18n.label.postNumber(),
                input: i18n.label.postNumber()
            }
        }
        details.filter(detail => detail.ruletype).forEach(detail => {
            const { ruletype, rulevalue, showorder } = detail
            if (ruletype == 'STRING') {
                const datas = serialFieldDatas.filter(data => new RegExp("[0-9]").test(data.id))
                if (datas.length > 0) {
                    const sortDatas = datas.map(data => data.showorder).sort().map(showorder => datas.find(data => data.showorder == showorder))
                    const { id } = last(sortDatas)
                    serialFieldDatas.push({ id: `${parseInt(id) + 1}`, text: `${i18n.label.string()}${parseInt(id) + 1}`, input: rulevalue, showorder })
                } else {
                    serialFieldDatas.push({ id: '1', text: `${i18n.label.string()}1`, input: rulevalue, showorder })
                }
            } else {
                const data = obj[ruletype]
                if (typeof data.input == 'number') {
                    data.input = rulevalue
                }
                serialFieldDatas.push({ ...data, showorder })
            }
        })

        return serialFieldDatas.map(data => data.showorder).sort().map(showorder => serialFieldDatas.find(data => data.showorder == showorder))
    }

    transKeyToDateOptionValue = (key) => {
        return {
            YEAR: 'year#',
            MONTH: 'month#',
            DAY: 'date#',
            SUBCOMPANY: 'sub#',
            DEPARTMENT: 'dept#',
            JOBTITLES: 'post#',
        }[key]
    }

    transSerialFieldDatasToDetails = (serialFieldDatas) => {
        return serialFieldDatas.map((data, index) => {
            const { id, input } = data;
            if (new RegExp("[0-9]").test(id)) {
                return { ruletype: 'STRING', rulevalue: input, showorder: index }
            } else {
                return (id == 'serial') ? { ruletype: 'NUMBER', rulevalue: input, showorder: index } : { ruletype: this.transIdToRuletype(id), rulevalue: '', showorder: index }
            }
        })
    }

    transIdToRuletype = (id) => {
        return {
            'year#': 'YEAR',
            'month#': 'MONTH',
            'date#': 'DAY',
            'sub#': 'SUBCOMPANY',
            'dept#': 'DEPARTMENT',
            'post#': 'JOBTITLES',
        }[id]
    }

    handleSave = (showMsg) => {
        return api.saveOrUpdateCodeSetting(this.saveParams).then(res => {
            const { api_status, coderuleid } = res
            if (api_status) {
                this.coderuleid = coderuleid
                showMsg && message.success(i18n.label.sucessSave())
            } else {
                message.error(res.message)
            }
        })
    }

    handleLog = () => {
        window.setLogViewProps({
            logSmallType: '1036',
        });
    }

    @action handleGenerationSwitchChange = (val) => {
        this.generationSwitchChecked = val
    }
}