import { observable, action, computed } from "mobx";
import { WeaTableNew, WeaSwitch } from "comsMobx";
import { WeaBrowser, WeaFormItem, WeaSelect, WeaUpload, WeaHelpfulTip, WeaLocaleProvider, WeaNewScroll, WeaError} from "ecCom";
import {WeaLogView} from 'comsMobx';
import { Button, message, Table, Radio} from "antd";
import HrmBaseStore from "../../hrmComsPublic/stores/baseStore";
import {importScheduleCode} from './importScheduleCode';
import * as api from "../apis/scheduleCode";
import { i18n } from "../public/i18n";
import { uniq, find, findIndex, has, fill, concat, dropRight, filter, isEmpty, forEach} from "lodash";
const RadioGroup = Radio.Group;
const { WeaTable, TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

export class ScheduleCode extends HrmBaseStore {
  /********************* unobservable list *********************/
  opId;
  orgTreeProps = {
    needSearch: true,
    isLoadAllSub: false,
    isLoadSubDepartment:true,
    topPrefix: "hrmSearch",
    inputLeftDom: `<b>${i18n.label.organization()}</b>`,
    // needDropMenu: true,
    treeNodeClick: this.treeNodeClick,
    params: {
      rightStr: "ScheduleCode:Edit"
    }
  };
  mainTabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "main",
        title: "",
        viewCondition: "1",
        searchType: ["base", "advanced"],
        searchKey: "lastname",
        doSearch: () => {
          this.selectedSubCompany=null;
          this.getTableData()
        }
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1"
  };
  @computed get dialogTabConfig(){
    return {
      tabs: [
        {
          color: "#000000",
          groupId: "dialog",
          title: "",
          viewCondition: "1",
          searchType: ["base", "advanced"],
          searchKey: "devicename",
          doSearch: () => {
            this.getDeviceTableData()
          },
          tabButtonDef: [
            {
              comType: "button",
              icon: "icon-coms-Add-to-hot",
              label: i18n.label.create,
              rightMenuIcon: this.menuIconCollection.create,
              onClickHandle: () => this.doDeviceCreateEdit()
            },
            {
              comType: "button",
              icon: "icon-coms-form-delete-hot",
              label: i18n.label.multiDelete,
              rightMenuIcon: this.menuIconCollection.remove,
              onClickHandle: () => this.deleteScheduleDevice(),
              checkAction: "memberRemoveable"
            }
          ]
        }
      ],
      keyParam: "viewCondition",
      activeTabKey: "1"
    }
  };
  @observable dialogParams = {
    ...this.dialogPropsDef,
    opType: "create",
    style: {
      width: 800,
      height: 400
    },
    onCancel: () => {
      this.dialogParams.visible = false;
      this.dialogParams.opType = "create";
      this.opId = null;
    }
  };
  @observable deviceDialogParams = {
    ...this.dialogPropsDef,
    opType: "create",
    style: {
      width: 800,
      height: 400
    },
    onCancel: () => {
      this.deviceDialogParams.visible = false;
      this.deviceDialogParams.opType = "create";
      this.opId = null;
    }
  };

  @observable deviceEditDialogParams = {
    ...this.dialogPropsDef,
    opType: "create",
    style: {
      width: 600,
      height: 300
    },
    onCancel: () => {
      this.deviceEditDialogParams.visible = false;
      this.deviceEditDialogParams.opType = "create";
      this.opId = null;
    }
  };

  @computed
  get memberRemoveable() {
    return this.devicetable.selectedRowKeys.length === 0;
  }
  
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable
  spinning = false;
  @observable
  selectedSubCompany;
  @observable
  table = new TableStore();
  @observable
  batchEditVal = new Map();
  @observable
  editTable = {};
  @observable
  editTableData = [];

  @observable
  devicetable = new TableStore();
  @observable
  showAllLevel = true;
  @observable
  isOneDevice = true;

  @observable canAdd = false;

  /********************* action list *********************/
  @action
  init = () => {
    this.selectedSubCompany = null;
    this.single = null;
    api.getScheduleCodeCondition().then(
      data => {
        this.setFormData("conditionForm", data.conditions);
        if (this.formTarget.conditionForm.isFormInit){
          this.containerInitFinished.init = true;
        }
        this.getTableData();
      },
      error => {}
    );
  }

  @action
  getTopProps = (single) => {
    let buttons = [(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8e01dh`} size="small" style={{height: '28px'}} onClick={()=>this.changeShowAllLevel()} title={this.showAllLevel?getLabel(508024,'包含下级'):getLabel(387277,'不包含下级')}>
        <span>{this.showAllLevel ? <i className='icon-coms-DisplaySubordinates' style={{color: '#2db7f5'}}/> : <i className='icon-coms-NoDisplayOfSubordinates'/>}</span>
      </Button>
    )];
    if(this.canAdd){
      this.isOneDevice && buttons.push((
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nfag13`} type="primary" op="save" onClick={() => this.save()}>{i18n.label.save()}</Button>
      ));
      buttons.push((
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r1kxzg`} type="primary" op="import" onClick={() => this.import()}>{i18n.label.import()}</Button>
      ));
    };
    // buttons = [
    //   <Button
    //   type="primary"
    //   op="log"
    //   onClick={() => this.showLog({logSmallType: this.logTypeDef.HRM_ENGINE_SCHEDULECODE})}
    //   >
    //   {i18n.label.log()}
    // </Button>
    // ];
    let menus = this.convertToMenus(buttons);
    menus = menus.filter(obj=>obj.key!=='0');
    return {
      buttons,
      menus: [
        ...menus,
        {
          key: menus.length + 1 + "",
          content: i18n.label.scheduledevice(),
          icon: <i className={this.menuIconCollection['setting']}/>,
          onClick: () => this.scheduleDevice()
        },
        ...this.getBasicMenus("HRM_ENGINE_SCHEDULECODE")
      ]
    };
  };

  changeShowAllLevel() {
    this.showAllLevel = !this.showAllLevel;
    this.getTableData();
  }

  @action
  treeNodeClick = (event, ids, nodeids, nodes) => {
    const { data: nodeData } = event.node.props;
    this.selectedSubCompany = nodeData;
    this.formTarget.conditionForm.resetConditionValue();

    this.getTableData();
  };

  @action
  getTableData = () => {
    const params = this.formTarget.conditionForm.getFormParams();
    Object.assign(params, {
      subcompanyid: (this.selectedSubCompany && this.selectedSubCompany.type=='1') ? this.selectedSubCompany.id : params.subcompanyid,
      departmentid: (this.selectedSubCompany && this.selectedSubCompany.type=='2') ? this.selectedSubCompany.id : params.departmentid,
      showAllLevel:this.showAllLevel?"1":"0"
    });
    api.getScheduleCodeList(params).then(
      data => {
        if (data.status === "1") {
          this.canAdd = data.canAdd || false;
          this.table = new TableStore();
          this.table.getDatas(data.sessionkey, 1);
          this.isOneDevice = data.isOneDevice; 
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  };

  getDeviceTableData = () => {
    const params = this.formTarget.deviceConditionForm.getFormParams();
    api.getScheduleDeviceList(params).then(
      data => {
        if (data.status === "1") {
          this.devicetable = new TableStore();
          this.devicetable.getDatas(data.sessionkey, 1);
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  };

  @action 
  resetBaseForm = () => {
    delete this.formTarget.shiftSchedulceForm;
    delete this.formTarget.shiftSchedulceFormFields;
  }

  @action
  openHrm=(id)=>{
    window.open(`/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/${id}`,'_blank');
  }

  @action
  setBatchEditVal(id, val) {
    this.batchEditVal.set(id, val);
  }

  @action
  doEdit = (params={}) => {
    api.getScheduleCodeForm(params).then(
      data => {
        if (data.status === "1") {
          this.canAdd = data.canAdd;
          this.editTable=data.table;
          this.editTableData = data.table.datas;
        } else {
          message.error(data.message);
        }
        this.opId = params.id;
        this.dialogParams.title = params.lastname+"-"+ getLabel("27960","考勤编号");
        this.dialogParams.opType = "edit";
        this.dialogParams.visible = true;
      },
      error => {}
    );
  };

  @action
  onEditTableChange=(datas=[])=>{
    this.editTableData = datas;
  }

  @action
  save=(params={})=>{
    params.cmd='batch';
    params.resourceids = [...this.batchEditVal.keys()].join(';');
    params.schedulecodes = [...this.batchEditVal.values()].join(';');
    if (params.resourceids == '' && params.schedulecodes == '') return;
    api.saveScheduleCode(params).then(data => {
      if (data.status == '1') {
        message.success(i18n.message.saveSuccess());
        this.getTableData();
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  /**
	 * 设置WeaTableEdit的refs对象
	 * @param  {Object} refs [WeaTableEdit]
	 */
	setEditTable = (refs, name) => {
		this.editTable[name] = refs;
  }
  
  @action
	recordOP = (target, type, callback = null) => {
		switch (type) {
			case 'add':
				target.refs.edit.doAdd()
				break;
			case 'remove':
				target.refs.edit.doDelete()
				break;
			case 'copy':
				target.refs.edit.doCopy()
				break;
			case 'valid':
				return target.refs.edit.doRequiredCheck()
			default:
				break;
		}
	}

  @action
  savePerson=(params={})=>{
    const {
			pass,
			index,
			key
		} = this.recordOP(this.editTable['fieldDef'], 'valid');
		if (!pass || this.editTable.columns === 0 )
      return;
      
    params.datas=this.editTableData;
    params.resourceid=this.opId;
    api.saveScheduleCode({ data: JSON.stringify(params) }).then(data => {
      if (data.status == '1') {
        message.success(i18n.message.saveSuccess());
        this.getTableData();
        this.dialogParams.visible = false;
      } else {
        message.warning(data.message);
      }
    }, error => {
      message.warning(error.message);
    })
  }

  @action
  import = () => {
		const params = [getLabel('129833', '导入模板'), getLabel('511419', "考勤编号导入"), 'kqScheduleCode', true];

		const funcs = ['setTempletName', 'setImportDialogTitle', 'setImportType', 'setImportDialogVisible'];

		funcs.map((func, index) => {
			importScheduleCode[func](params[index]);
    })
    importScheduleCode.importDialog.visible=true;
  }
  
  @action
  scheduleDevice = (params={}) => {
    api.getScheduleDeviceCondition().then(
      data => {
        if (data.status === "1") {
          this.setFormData("deviceConditionForm", data.conditions);
          if (this.formTarget.deviceConditionForm.isFormInit){
            this.containerInitFinished.init = true;
          }
          this.getDeviceTableData();
          this.opId = params.id;
          this.deviceDialogParams.title = getLabel("513116","考勤机管理");
          this.deviceDialogParams.opType = "edit";
          this.deviceDialogParams.visible = true;
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  }

  @action
  doDeviceCreateEdit(params={}){
    api.getScheduleDeviceForm(params).then(
      data => {
        if (data.status === "1") {
          this.setFormData("deviceEditConditionForm", data.condition);
          if (this.formTarget.deviceEditConditionForm.isFormInit){
            this.containerInitFinished.init = true;
          }
          this.deviceEditDialogParams.title = params.id?getLabel(513253, '编辑考勤机'):getLabel(513252, '新建考勤机');
          this.deviceEditDialogParams.opType = params.id?"edit":"create";
          this.deviceEditDialogParams.visible = true;
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  }

  @action
  doSaveScheduleDevice = () => {
    this.formTarget.deviceEditConditionForm.validateForm().then(f => {
      if (f.isValid) {
        if(this.spinning)
        return;
        this.spinning = true;
        const params = this.formTarget.deviceEditConditionForm.getFormParams();
        api.saveScheduleDevice(params).then(data => {
          if (data.status === '1') {
            this.deviceEditDialogParams.visible = false;
            message.success(i18n.message.saveSuccess());
            this.formTarget.deviceEditConditionForm.resetConditionValue();
            this.getDeviceTableData();
          } else
            message.error(data.message);
          this.spinning = false;
        }, error => this.spinning = false)
      } else {
        f.showErrors();
        this.showError = new Date().getTime();
      }
    })
  }

  @action
  deleteScheduleDevice = (params) => {
    let content;
    if (params == null) {
      params = {
        ids: this.devicetable.selectedRowKeys
      };
      content = i18n.confirm.deleteSelected();
    } else {
      content = i18n.confirm.delete();
    }
    this.confirmInfo({
      content,
      onOk: () => {
        api.delScheduleDevice({...params}).then(data => {
          if (data.status === "1") {
            message.success(i18n.message.deleteSuccess());
            this.devicetable.getDatas(null, 1);
            this.getDeviceTableData();
          }
        });
      }
    });
  }

  formItemRender = {
    id: (field, textAreaProps, form, formParams) => null
  }
}

export const scheduleCodeStore = new ScheduleCode();
