import { observable, action, computed } from "mobx"
import { last } from 'lodash'
import { toJS } from 'mobx'
import { WeaInput, WeaLocaleProvider, WeaInputNumber } from 'ecCom'
import { Modal } from 'antd'
import { i18n } from "../../public/i18n"
const confirm = Modal.confirm
const getLabel = WeaLocaleProvider.getLabel;

//编号组成
export default class NumberComposition {
    constructor(scope){
        this.root = scope || {};
    }
    selectedKey = '1'
    dateRelatedId = ['year#', 'month#', 'date#']
    orgRelatedId = ['sub#', 'dept#']
    serialFieldColumns = [
        { title: '', dataIndex: 'text', com: [{ type: "INPUT", key: "text", viewAttr: 1 }],width:'20%' },
        { title: '', dataIndex: 'input', com: [{ type: "INPUT", key: "input" }], width:'70%',render: (text, record, index) => this.reRenderRow(text, record, index) }
    ]

    @observable serialFieldDatas = [
        { id: '1', text: `${i18n.label.string()}1`, input: '' },
        { id: 'serial', text: i18n.label.numberDigits(), input: (this.root.serialtype == 'USER') ? 4 : 3 }
    ]
    @observable visible = false
    @observable serialFieldOptions = [
        { key: '1', showname: i18n.label.string(), selected: true },
        { key: '2', showname: i18n.label.curYear(), selected: false },
        { key: '3', showname: i18n.label.curMonth(), selected: false },
        { key: '4', showname: i18n.label.curDate(), selected: false }
    ]
    @observable selectedRowKeys  =[]

    @action onRowSelect  =(keys) => {
        this.selectedRowKeys = keys
    }

    //获取日期相关的id
    @computed get dateRelatedFieldIds() {
        return this.serialFieldDatas
            .filter(data => this.dateRelatedId.includes(data.id))
            .map(data => data.id)
    }

    @computed get orgRelatedFieldIds() {
        return this.serialFieldDatas
            .filter(data => this.orgRelatedId.includes(data.id))
            .map(data => data.id)
    }

    //是否包含可设置单独流水的字段
    @computed get hasFlowRuleField() {
        return this.serialFieldDatas.some(data => data.id.includes('#'))
    }

    //是否包含日期相关的编号字段
    @computed get hasDateRelatedField() {
        return this.dateRelatedFieldIds.length > 0
    }

    @computed get hasOrgField() {
        return this.serialFieldDatas.find(data => this.orgRelatedId.includes(data.id))
    }

    @computed get hasPostField() {
        return this.serialFieldDatas.find(data => data.id == 'post#')
    }

    /**
     * 概述：自定义行渲染
     * 当渲染到当前年份、当前月份、当前日期等行时，编号字段不设置默认值，同时不可编辑。
     * @param  {[String]} text   [单元格值]
     * @param  {[Object]} record [行数据]
     * @param  {[Number]} index  [行索引]
     * @return {[Component]}        [单元格元素]
     */
    reRenderRow = (text, record) => {
        const { id } = record;
        if (id.includes('#')) {
            return <span />
        } else if (id == 'serial') {
            return <WeaInputNumber ecId={`${this && this.props && this.props.ecId || ''}_WeaInputNumber@753vyj`} min={1} value={text} onChange={this.handleInputChange.bind(this, id)} onBlur={val=>this.handleInputBlur(id,val)} />
        } else {
            return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@z3wwd0`} defaultValue={text} onChange={this.handleInputChange.bind(this, id)} />
        }
    }

    /**
     * 概述：禁用行选择
     * 1. 当列表中包含"当前月份"行时，则"当前年份"行不能被删除; 当列表中包含"当前日期"行时，则"当前月份"行不能被删除
     * 2. "流水号位数"行禁止删除
     */
    getRowSelection = rowSelection => {
        rowSelection.getCheckboxProps = record => {
            const { id } = record
            const rely = {
                'year#': 'month#',
                'month#': 'date#'
            }
            if (rely[id]) {
                return { disabled: this.isFieldExist(rely[id]) }
            }
            if (id == 'serial') {
                return { disabled: true }
            }
            return false
        };
        return rowSelection
    }

    /**
     * 概述：点击【保存】后，执行的逻辑
     * 1.判断选中的编号字段是否需要检验，不需要校验的话，则直接添加到serialFieldDatas中；
     * 2.当字段需要校验时，首先校验该字段是否已经在serialFieldDatas中存在；
     * 3.部分字段在添加前，需要判断其依赖编号字段是否存在。
     */
    @action handleAdd = () => {
        //选中字段的名称
        const { showname } = this.serialFieldOptions.find(option => option.key == this.selectedKey)
        const tmp = this.serialFieldDatas.filter(data => new RegExp("[0-9]").test(data.id))

        //需要校验的编号字段对应的key值集合
        const needValidateFieldKeys = this.serialFieldOptions.map(option => option.key).filter(key => key != '1')

        if (needValidateFieldKeys.includes(this.selectedKey)) {
            const keyToId = {
                '2': 'year#',
                '3': 'month#',
                '4': 'date#',
                '5': 'sub#',
                '6': 'dept#',
                '7': 'post#',
            }
            const id = keyToId[this.selectedKey];
            //编号字段已经存在
            if (this.isFieldExist(id)) {
                const msgs = {
                    'year#': i18n.label.yearAdded(),
                    'month#': i18n.label.monthAdded(),
                    'date#': i18n.label.dateAdded(),
                    'sub#': i18n.label.subAdded(),
                    'dept#': i18n.label.deptAdded(),
                    'post#': i18n.label.postAdd(),
                }
                this.showConfirm(msgs[id])
                return
            }
            const dependance = {
                'month#': 'year#',
                'date#': 'month#'
            }
            const dependanceIndex = this.getDependenceIndex(dependance[id])
            //依赖编号字段不存在
            if (id != 'year#' && ['month#', 'date#'].includes(id) && dependanceIndex == -1) {
                const msgs = {
                    'month#': i18n.label.addYearBeforeMonth(),
                    'date#': i18n.label.addYearMonthBeforeDate()
                }
                this.showConfirm(msgs[id])
                return
            }
            if (['sub#', 'dept#', 'post#'].includes(id)) {
                this.insertOrgPost(id, showname)
            } else {
                this.insertDate(id, tmp, dependanceIndex, showname)
            }

        } else {
            this.insertString(tmp)
        }

        this.onCancel()
    }

    /**
     * 概述：获取依赖字段的索引值
     * @param  {[String]} dependanceId [标识依赖字段]
     * @return {[Number]}              [索引值]
     */
    getDependenceIndex = (dependanceId) => {
        return this.serialFieldDatas.findIndex(data => data.id == dependanceId)
    }

    /**
     * 概述：通过传入当前字段的id，来判断serialFieldDatas中是否已经存在该编号字段
     * @param  {String} selfId [标识当前字段]
     * @return {Boolean}        [当前字段是否已存在]
     */
    isFieldExist = (selfId) => {
        return this.serialFieldDatas.findIndex(data => data.id == selfId) > -1
    }

    onSelectChange = (key) => {
        this.selectedKey = key
    }

    handleInputChange = (id, val) => {
        this.serialFieldDatas.find(data => data.id == id).input = val;
    }

    handleInputBlur = (id, val)=> {
        const input = this.serialFieldDatas.find(data => data.id == id).input;
        if (!input) {
            this.serialFieldDatas.find(data => data.id == id).input = 1;
        }
    }

    @action setSerialFieldDatas = (datas) => {
        this.serialFieldDatas = datas
    }

    @action onOpen = () => {
        this.selectedKey = '1'
        this.visible = true
    }

    @action onCancel = () => {
        this.visible = false
    }

    @action onDelete = (datas) => {
        const {setDateChecked,setOrgChecked,setPostChecked} = this.numberFlowRuleStore
        this.showConfirm(getLabel(83877, '确定要删除吗？'), () => {
            this.serialFieldDatas = datas
            this.selectedRowKeys = []
            
            let a =0, b=0,c =0;
           datas.map(data=>{
            const{id} =data;
            if (['year#','month#','date#'].includes(id)) {
               a+=1;
            }
            if (['sub#','dept#'].includes(id)) {
               b+=1;
            }
            if (id == 'post#') {
               c = 1;
            }
           });
           if (a == 0) {
            setDateChecked('0');
           }
           if (b == 0) {
            setOrgChecked('0');
           }
           if (c == 0) {
            setPostChecked('0');
           }
        })
    }

    @action extendSerialFieldOptions = (options) => {
        options.forEach(opt => {
            if (!this.serialFieldOptions.find(oldOpt => oldOpt.key === opt.key)) {
                this.serialFieldOptions.push(opt)
            }
        })
    }

    showConfirm = (content, callback) => {
        confirm({
            title: getLabel(131329, '信息确认'),
            content,
            okText: getLabel(33703, '确认'),
            className: !callback ? 'numberComposition-confirm' : '',
            onOk() {
                callback && callback()
            },
        });
    }


    insertDate(id, tmp, dependanceIndex, showname) {
        const sIndex = (id == 'year#') ? tmp.length : dependanceIndex + 1
        this.serialFieldDatas.splice(sIndex, 0, { id, text: showname, input: showname })
    }

    insertOrgPost(id, showname) {
        this.serialFieldDatas.splice(-1, 0, { id, text: showname, input: showname })
    }

    insertString(tmp) {
        if (tmp.length) {
            const compare = (attr) => {
                return (a,b) => {
                    return a[attr] - b[attr]
                }
            }
            tmp.sort(compare('id'))
            const { id } = tmp[tmp.length - 1]
            this.serialFieldDatas.splice(tmp.length, 0, { id: (parseInt(id) + 1) + '', text: `${i18n.label.string()}${parseInt(id) + 1}`, input: '' })
        }else{
            this.serialFieldDatas.unshift({ id: '1', text: `${i18n.label.string()}1`, input: '' })
        }
    }

    rely = (store) =>{
        this.numberFlowRuleStore = store
    }
}