import { observable, action, computed } from "mobx";
import { WeaButtonIcon, WeaDropdown, WeaLocaleProvider} from "ecCom";
import {WeaSwitch} from 'comsMobx';
import { Menu, Button, message} from "antd";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import * as api from "../apis/kqMonthReportSetting";
import { i18n } from "../public/i18n";
import findIndex from 'lodash/findIndex';
import filter from 'lodash/filter';
import cloneDeep from 'lodash/cloneDeep';
const getLabel = WeaLocaleProvider.getLabel;
const {ButtonSelect} = WeaDropdown;

export class KQMonthReportSetting extends HrmBaseStore {
  @observable loading = false;

  //#region WeaTop属性
  @observable _topButtons = [];
  @computed get topButtons(){
    return this.toJS(this._topButtons);
  }
  set topButtons(v){
    this._topButtons = v;
  }

  @computed get topBtnAndMenus(){
    const buttons = [], menus = [];
    this.topButtons.map((d, i) => {
      if(1 == d.isTop){
        buttons.push(
          (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@et5r2v@${i}`} type="primary" onClick={() => this[d.menuFun] && this[d.menuFun]()}>{d.menuName}</Button>)
        );
      }
      menus.push({
        key: i + '',
				content: d.menuName,
				icon: <i className={d.menuIcon}/>,
				onClick: () => this[d.menuFun] && this[d.menuFun](),
      })
    });

    return {
      buttons,
      dropMenuDatas: [
        ...menus,
        ...this.getBasicMenus("HRM_ENGINE_KQREPORT_DEFINED")
      ]
    }
  }

  @computed get topProps(){
    return {
      title: getLabel('516794','考勤汇总报表展示列定制'),
      icon: <i className='icon-coms-hrm'/>,
      iconBgcolor: '#217346',
      showDropIcon: true,
      ...this.topBtnAndMenus
    }
  }
  //#endregion

  //#region WeaTab 字段分组tab属性
  @observable mainActiveTabKey = '';
  
  @observable _mainTabs = [];
  @computed get mainTabs(){
    return this.toJS(this._mainTabs);
  }
  set mainTabs(v){
    this._mainTabs = v;
  }

  @observable dropdownSelectedKey = '1';
  @computed get dropdownProps(){
    return {
      type: 'small',
      btnProps: {
        style: { padding: 0, background: 'transparent', border: 'none', color: this.fieldListSelectedRowKeys.length == 0 ? '#dadada' : '#34A2FF', fontSize: 20 },
        disabled: this.fieldListSelectedRowKeys.length == 0
      },
      datas: [
        { key: '1', text: getLabel(131966, '删除'), show: <span className='icon-coms-form-delete-hot' />, selected: this.dropdownSelectedKey == '1' },
        { key: '2', text: getLabel('-81296', "移动到组"), show: <span className='icon-coms-move2' />, selected: this.dropdownSelectedKey == '2', isDropBtn: true }
      ],
      btnDropPropsDatas: {'2': {overlay: this.moveDropDown}},
      btnOnClick: this.btnOnClick,
      menuOnClick: this.menuOnClick
    }
  }

  @computed get moveDropDown(){
    return (
      <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@vn9wst`} onClick={this.dropdownClick}>
        {
          filter(this.mainTabs, tab => {
            try{
              return tab.viewCondition != this.mainActiveTabKey && tab.viewCondition != 'other'
            }catch(e){
              return true;
            }
          }).map((tab, index) => (
            <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@tcew9c@${index}`} key={`${tab.viewCondition}_${tab.title}`}>
              <div>{tab.title}</div>
            </Menu.Item>
          ))
        }
        <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_undefined@edxsjy`} />
        <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_undefined@h03s3b`} key='createAndMove' style={{background: '#E8E8E8', textAlign:'center'}}>
          <div>{getLabel('31194', "新建分组并移动")}</div>
        </Menu.Item>
      </Menu>
    )
  }

  @computed get tabButtons(){
    return [
      <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@91y0il`} buttonType='add' type='primary' onClick={() => this.getFieldDefineForm()} />,
      <ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@ip41us`} {...this.dropdownProps} selectedKey={this.dropdownSelectedKey} />
    ]
  }

  @computed get mainTabProps(){
    const tabConfig = {
      tabs: this.mainTabs,
      keyParam: "viewCondition",
      activeTabKey: this.mainActiveTabKey,
      onTabEdit: (tabKey, action) => this.onTabEdit(tabKey, action, this.refreshMainData)
    }

    return {
      tabConfig,
      activeTabInfo: {
        activeTabKey: tabConfig.activeTabKey,
        activeTabIndex: 0
      },
      rightMenu: this.topBtnAndMenus.dropMenuDatas,
      store: this,
      tabChangeHandle: this.setActiveTab,
      tabBtnDef: this.tabButtons
    }
  };

  @action setActiveTab = k => {
    this.dropdownSelectedKey = '1';
    this.fieldListSelectedRowKeys = [];
    this.mainActiveTabKey = k;
    this.getFieldData();
  }

  @action onTabEdit = async (tabKey, action, callback) => {
    if(findIndex(this.mainTabs, {viewCondition: tabKey}) < 0) return;
		switch (action) {
			case 'remove':
				this.confirmInfo({
					content: i18n.confirm.delete(),
					onOk: () => {
            api.deleteGroup({ids: tabKey}).then(data => {
              if (data.status === '1') {
                message.success(i18n.message.deleteSuccess());
                callback && callback();
              } else {
                message.error(data.message);
              }
            })
					}
				});
				break;
			default:
				break;
		}
	}
  //#endregion

  //#region 初始化数据
  @action cleanData = () => {
    this.dropdownSelectedKey = '1';
    this.fieldListSelectedRowKeys = [];
  }

  @action initData = async () => {
    this.cleanData();
    this.containerInitFinished.init = true;
    const rs = await api.init();
    rs.map((data, index) => {
      if(data.status == null || data.status == 1){
        switch(index){
          case 0:
            this.topButtons = data.btnMenu;
            break;
          case 1:
            this.mainTabs = data.tabs.map((d, i) => {
              if(i == 0) this.mainActiveTabKey = d.key;
              return {
                editable: d.editable,
                color: "#000000",
                title: d.title,
                viewCondition: d.key,
                // searchType: ["base"],
                // searchKey: "groupname",
                // doSearch: () => this.getTableData()
              }
            });
            this.getFieldData();
            break;
        }
      }else
        message.error(resut.message);
    });
  }

  @action init = () => {
    this.initData();
  }
  //#endregion

  //#region 根据groupid获取字段列表
  fieldListDraggable = false;
  fieldListShowTitle = false;
  fieldListColumns = [];
  @observable _fieldListData = [];
  @computed get fieldListData(){
    return this.toJS(this._fieldListData);
  }
  set fieldListData(v){
    this._fieldListData = v;
  }
  @observable _fieldListSelectedRowKeys = [];
  @computed get fieldListSelectedRowKeys(){ return this.toJS(this._fieldListSelectedRowKeys) }
  set fieldListSelectedRowKeys(v){ this._fieldListSelectedRowKeys = v }

  
  defaultShowColComs;
  @computed get cells(){
    return this.fieldListData.map(data => {
      const coms = cloneDeep(this.defaultShowColComs).map(com => ({
        ...com,
        disabled: (data.isenable != 1)
      }));
      return {id: data.id, defaultshow: {com: coms}};
    })
  }

  @computed get fieldListTableProps(){
    this.dropdownSelectedKey;
    return {
      draggable: this.fieldListDraggable,
      showTitle: this.fieldListShowTitle,
      columns: this.fieldListColumns,
      cells: this.cells,
      datas: this.fieldListData,
      initialDatas: this.fieldListData,
      getRowSelection: this.getRowSelection,
      onRowSelect: this.onFieldDataRowSelect,
      selectedRowKeys: this.fieldListSelectedRowKeys,
      onChange: this.fieldListChangeHandle
    }
  }

  getRowSelection = rowSelection => {
    const sel = { ...rowSelection };
    sel.getCheckboxProps = record => {
      const disabled = this.dropdownSelectedKey == '2' ? false : record.disabled;
      return {disabled};
    };
    return sel;
  };

  @action onFieldDataRowSelect = selectedRowKeys => this.fieldListSelectedRowKeys = selectedRowKeys

  @action fieldListChangeHandle = datas => this.fieldListData = datas.map(d => {
    if(d.isenable == 0) Object.assign(d, {defaultshow: 0});
    return d;
  });

  @action getFieldData = async () => {
    if(this.loading)
      return;
    this.loading = true;
    const result = await api.getFieldDefineList({groupid: this.mainActiveTabKey});
    if(result.status == 1 && result.items.length > 0){
      const {table} = result.items[0] || {};
      const {draggable, showTitle, columns, datas} = table;
      this.fieldListDraggable = draggable;
      this.fieldListShowTitle = showTitle;
      this.fieldListColumns = (columns || []).map((d, i) => {
        const {title, dataIndex, width, com, checkVauleType, showCheckAll} = d;
        const colDef = {
          title,
          dataIndex,
          width
        }
        com && Object.assign(colDef, {com});
        dataIndex == 'defaultshow' && (this.defaultShowColComs = com);
        if(dataIndex === 'formulaspan'){
          Object.assign(colDef, {
            com: [
              {
                type: 'CUSTOM',
                key: dataIndex,
                render: (text, record, index, onEdit) => {
                  if(!text || text == "")
                    return null;
                  return (<a onClick={() => this.getFieldDefineForm(record.id)}>{text}</a>);
                }
              }
            ],
          })
        }
        return colDef;
      });
      this.fieldListData = datas || [];
    }else
      message.error(resut.message);
    this.loading = false;
  }

  @action btnOnClick = key => key == '1' && this.deleteFieldDefine();

  @action menuOnClick = key => {
    this.dropdownSelectedKey = key;
    this.fieldListSelectedRowKeys = [];
  }

  @action dropdownClick = e => {
    const {key} = e;
    if(key === 'createAndMove'){
      this.createGroup(true);
    }else{
      const [groupid, groupname] = key.split('_');
      let moveFieldConfirm = getLabel('388100', "确定要移动所选择的记录到分组{params}吗？").replace('{params}', groupname);
      this.confirmInfo({
        content:moveFieldConfirm,
        onOk: () => {
          this.changeFieldGroup(groupid);
        }
      });
    }
  }

  @action deleteFieldDefine = () => {
    this.confirmInfo({
      content: i18n.confirm.deleteSelected(),
      onOk: async () => {
        this.showWeaLoadingGlobal();
        const data = await api.deleteFieldDefine({ids: this.fieldListSelectedRowKeys});
        if (data.status === '1') {
          message.success(i18n.message.deleteSuccess());
          this.fieldListSelectedRowKeys = [];
          this.refreshMainData(this.mainActiveTabKey);
        } else {
          message.error(data.message);
        }
        this.hideWeaLoadingGlobal();
      }
    });
  }
  //#endregion

  //#region 添加自定义展示列
  formid;
  @observable createFieldDefineDialogVisible = false;
  @computed get createFieldDefineDialogProps(){
    let buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pteu8k`} type='primary' op='save' onClick={() => this.saveFieldDefine()}>{i18n.label.save()}</Button>];
    return {
      ...this.dialogPropsDef,
      hasScroll: true,
      title: this.formid == null ? getLabel('516792','添加自定义展示列') : getLabel('516793','编辑自定义展示列'),
      style: {
        width: 500,
        height: 300
      },
      onCancel: () => {
        this.createFieldDefineDialogVisible = false;
      },
      visible: this.createFieldDefineDialogVisible,
      buttons,
      moreBtn: {datas: this.convertToMenus(buttons)},
      key: new Date().getTime()
    }
  }

  feildDefineFormItemRender = {
    fieldlabel: (field, textAreaProps, form, formParams) => {
      return (
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0o3p9w`}
            fieldConfig={{ ...field, ...textAreaProps }}
            form={form}
            formParams={formParams}
            onChange={v => this.onFieldlabelChangeHandle(v.fieldlabel.value)}
          />
      );
    }
  }

  @action onFieldlabelChangeHandle = async v => {
    if(this.formid == null){
      const data = await this.getPinYin({labelName: WeaLocaleProvider.formatMultiLang(v)});
      const {pinyin} = data;
      this.formTarget.createFieldDefineForm.updateFields({
        fieldname: {value: pinyin}
      })
    }
  }

  @action getFieldDefineForm = async id => {
    this.showWeaLoadingGlobal();
    const params = {};
    this.formid = id;
    id && Object.assign(params, {id})
    const data = await api.getFieldDefineForm(params);
    if(data.status == 1){
      this.setFormData("createFieldDefineForm", data.formField);
      if(this.formTarget.createFieldDefineForm.isFormInit)
        this.createFieldDefineDialogVisible = true;
    }else{
      message.error(data.message);
    }
    this.hideWeaLoadingGlobal();
  }

  @action saveFieldDefine = () => {
    const form = this.formTarget.createFieldDefineForm,
    formParams = form.getFormParams();
    form.validateForm().then(f => {
      if (f.isValid) {
        const params = { ...formParams, groupid: this.mainActiveTabKey};
        this.formid && Object.assign(params, {id: this.formid});

        this.confirmInfo({
          content: (<div><div>{getLabel('517312','耗时操作，请错开高峰期执行')}</div><div>{getLabel('518682','保存后需在报表中手动重新计算考勤数据后生效')}</div></div>),
					onOk: async () => {
            this.showWeaLoadingGlobal(getLabel('517313','数据处理中'));
            const data = await api.saveFieldDefine(params);
            if (data.status === "1") {
              message.success(i18n.message.saveSuccess());
              this.createFieldDefineDialogVisible = false;
              this.refreshMainData(this.mainActiveTabKey);
            } else {
              message.error(data.message);
            }
            this.hideWeaLoadingGlobal();
					}
        })
      } else {
        f.showErrors();
        const fields = this.formTarget.createFieldDefineForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.createFieldDefineForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
      }
    });
  }
  //#endregion

  //#region 保存列定制
  @action saveGroup = async () => {
    this.showWeaLoadingGlobal();
    const datas = this.fieldListData.map((d, i) => ({...d, fieldOrder: i}));
    const data = await api.saveFieldDefineList({datas: JSON.stringify(datas)});
    if(data.status == '1') message.success(i18n.message.saveSuccess());
    else message.error(data.message);
    this.hideWeaLoadingGlobal();
  }
  //#endregion

  //#region 移动分组
  @action changeFieldGroup = async groupid => {
    const params = {groupid, ids: this.fieldListSelectedRowKeys};
    const data = await api.changeFieldGroup(params);
    if(data.status == '1'){
      this.fieldListSelectedRowKeys = [];
      this.refreshMainData(params.groupid);
    }else{
      message.error(data.message);
    }
  }
  //#endregion

  //#region 新建分组
  isCreateAndMove = false;
  @observable createGroupDialogVisible = false;
  @computed get createGroupDialogProps(){
    let buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pny25v`} type='primary' op='save' onClick={() => this.doCreateGroup('save', !this.isCreateAndMove ? this.refreshMainData : this.changeFieldGroup)}>{i18n.label.save()}</Button>];
    return {
      ...this.dialogPropsDef,
      title: getLabel('30131','新建分组'),
      style: {
        width: 500,
        height: 135
      },
      onCancel: () => {
        this.createGroupDialogVisible = false;
      },
      visible: this.createGroupDialogVisible,
      buttons,
      moreBtn: {datas: this.convertToMenus(buttons)},
      key: new Date().getTime()
    }
  }

  @action createGroup = async (isCreateAndMove = false) => {
    this.showWeaLoadingGlobal();
    this.isCreateAndMove = isCreateAndMove;
    const result = await api.getGroupForm();
    if(result.status == 1){
      this.setFormData("createGroupForm", result.formField);
      if(this.formTarget.createGroupForm.isFormInit)
        this.createGroupDialogVisible = true;
    }else{
      message.error(result.message);
    }
    this.hideWeaLoadingGlobal();
  }

  @action doCreateGroup = (cmd, callback) => {
    this.showWeaLoadingGlobal();
    switch(cmd){
      case 'save':
        this.saveGroupForm(cmd, callback);
        break;
      case 'savebatch':
        this.saveGroupList(cmd, callback);
        break;
    }
  }

  @action saveGroupForm = (cmd, callback) => {
    const form = this.formTarget.createGroupForm,
    formParams = form.getFormParams();
    form.validateForm().then(f => {
      if (f.isValid) {
        api.saveGroup({ ...formParams, cmd}).then(
          data => {
            if (data.status === "1") {
              message.success(i18n.message.saveSuccess());
              this.createGroupDialogVisible = false;
              callback && callback(data.id);
            } else {
              message.error(data.message);
            }
            this.hideWeaLoadingGlobal();
          },
          error => {this.hideWeaLoadingGlobal()}
        );
      } else {
        this.hideWeaLoadingGlobal();
        f.showErrors();
        const fields = this.formTarget.createGroupForm.fieldMap;
        [...Object.keys(fields)].map(k => {
          const e = this.formTarget.createGroupForm.getError(fields[k]);
          if (e != null && e != "") {
            console && console.debug(e);
          }
        });
        this.showError = new Date().getTime();
      }
    });
  }

  @action saveGroupList = async (cmd, callback) => {
    this.showWeaLoadingGlobal();
    let flag = true;
    let datas = this.groupListData;
    datas = datas.map((d, i) => {
      const data = {...d, showorder: i + 1};
      if(d.id.startsWith('random_')) Object.assign(data, {id: ''});
      flag = flag && d.groupname && d.groupname.trim().length > 0;
      return data;
    });
 
    if(!flag){
      message.error(getLabel('130064','请填写分组名称'));
      this.hideWeaLoadingGlobal();
      return;
    }

    const params = {cmd, datas: JSON.stringify(datas)};
    const data = await api.saveGroup(params);
    if (data.status === "1") {
      this.groupListSettingDialogProps.onCancel();
      callback && callback();
    } else {
      message.error(data.message);
    }
    this.hideWeaLoadingGlobal();
  }

  @action refreshMainData = async groupid => {
    const result = await api.getFieldDefineTabs();
    if(result.status == 1){
      this.mainTabs = result.tabs.map((d, i) => {
        if(groupid == null && i == 0) this.mainActiveTabKey = d.key;
        return {
          editable: d.editable,
          color: "#000000",
          title: d.title,
          viewCondition: d.key,
        }
      });
      groupid && (this.mainActiveTabKey = groupid);
      this.getFieldData();
    }else{
      message.error(result.message);
    }
  }
  //#endregion

  //#region 分组维护
  groupListDraggable = false;
  groupListShowTitle = true;
  groupListColumns = [];
  @observable _groupListData = [];
  @computed get groupListData () {
    return this.toJS(this._groupListData);
  }
  set groupListData(v){
    this._groupListData = v;
  }

  @computed get groupListTableProps(){
    return {
      draggable: this.groupListDraggable,
      showTitle: this.groupListShowTitle,
      columns: this.groupListColumns,
      datas: this.groupListData,
      initialDatas: this.groupListData,
      showCopy: false,
      showMove: false,
      willAdd: this.willAdd,
      willDelete: this.willDelete,
      onChange: this.onChange
    }
  }

  @action willAdd = (datas, addData) => {
    return datas.map(data => {
      if (addData.id === data.id) return { ...data, id: `random_${data.id}`, isshow: '1' };
      return data;
    });
  }

  willDelete = (datas, keys) => new Promise((resolve, reject) => {
    this.confirmInfo({
      content: i18n.confirm.deleteSelected(),
      onOk: () => resolve(true),
      onCancel: () => resolve(false)
    });
  });

  @action onChange = (datas, other, data) => {
    this.groupListData = datas;
  }

  @observable groupListSettingVisible = false;
  @computed get groupListSettingDialogProps(){
    let buttons = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rpljie`} type='primary' op='save' onClick={() => this.doCreateGroup('savebatch', this.refreshMainData)}>{i18n.label.save()}</Button>];
    let moreBtn = {datas: this.convertToMenus(buttons)};
    return {
      ...this.dialogPropsDef,
      title: getLabel('383049','分组维护'),
      style: {
        width: 500,
        height: 500
      },
      buttons,
      moreBtn,
      onCancel: () => {
        this.groupListSettingVisible = false;
      },
      visible: this.groupListSettingVisible,
    }
  }

  @action editGroup = async () => {
    this.showWeaLoadingGlobal();
    const result = await api.getGroupList();
    if(result.status == 1 && result.items.length > 0){
      const {table} = result.items[0] || {};
      const {draggable, showTitle, columns, datas} = table;
      this.groupListDraggable = draggable;
      this.groupListColumns = (columns || []).map((d, i) => {
        const {title, dataIndex, width, com, checkVauleType, showCheckAll} = d;
        return {
          title,
          dataIndex,
          width,
          com,
          checkVauleType,
          showCheckAll: showCheckAll || false
        }
      });
      this.groupListData = datas || [];
      this.groupListSettingVisible = true;
    }else
      message.error(resut.message);
    this.hideWeaLoadingGlobal();
  }
  //#endregion
}

export const kqMonthReportSetting = new KQMonthReportSetting();