import React, { Component } from "react";
import { toJS } from "mobx";
import { inject, observer } from "mobx-react";
import { i18n } from "../../public/i18n";
import LeftTree from "./components/leftTree";
import NewAndEditDialog from "../NewAndEditDialog";
import { WeaFormItem, WeaLeftRightLayout, WeaRightMenu, WeaTab, WeaTop } from "ecCom";
import { Button, Col, message, Modal, Row, Spin, Switch } from "antd";
import { WeaSwitch, WeaTableNew } from "comsMobx";
import "./index.less";
import { renderNoright } from "../../util";
import ImportDialog from '../ImportDialog';


const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
@inject("officeManageStore")
@inject('importDialog')
@observer
export default class OfficeManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: "",
      editId: "",
      loading: false,
      deleteOfficeClassifyFlag: false
    };
  }

  componentDidMount() {
    const { officeManageStore } = this.props;
    officeManageStore.getTreeData && officeManageStore.getTreeData();
    officeManageStore.getHasRight && officeManageStore.getHasRight();
    officeManageStore.getPostInfoTable && officeManageStore.getPostInfoTable();
  }

  getDropMenuDatas = () => {
    const { officeManageStore } = this.props;
    const { rightMenu } = officeManageStore;
    let menus = [];
    toJS(rightMenu).map((item, index) => {
      let obj = {
        key: item.menuFun,
        icon: <i className={`${item.menuIcon}`}/>,
        content: item.menuName
      };
      if (
        item.menuFun == "collection" ||
        item.menuFun == "help" ||
        item.menuFun == "pageAddress"
      ) {
        obj.disabled = true;
      }
      menus.push(obj);
    });
    return menus;
  };

  showlog = () => {
    window.setLogViewProp({
      logMoudleType: 6,
      keys: new Date().getTime()
    });
  };

  handleMenuClick = key => {
    const { officeManageStore,importDialog } = this.props;
    const { isPanelShow, tableStore, officeClassifyId } = officeManageStore;
    isPanelShow && officeManageStore.setPanelStatus(false);
    switch (key) {
      case "new":
        officeManageStore.getPostInfoForm({ planId: officeClassifyId });
        officeManageStore.setVisible(true);
        officeManageStore.setNeDialogTitle(i18n.label.newOfficeName());
        break;
      case "log":
        this.showlog();
        break;
      case "custom":
        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
        break;
      case "import":
        importDialog.importVisible=true;
        importDialog.importModule='postInfo';
        importDialog.current = 0;
        importDialog.getImportForm();
        break;
      default:
        break;
    }
  };

  handleSave() {
    const {
      form,
      condition,
      savePostInfo,
      updatePostInfo
    } = this.props.officeManageStore;
    const { editId } = this.state;
    form.validateForm().then(f => {
      if (f.isValid) {
        // 验证通过, balabala业务代码
        const payload = editId
          ? { ...form.getFormParams(), id: editId }
          : { ...form.getFormParams() };
        this.setState({ loading: true });
        if (editId) {
          updatePostInfo(payload).then(({ code, msg }) => {
            this.setState({ loading: false });
            if (code === 200) {
              message.success("编辑成功");
              this.setState({ editId: "" }, () => {
                this.props.officeManageStore.setVisible(false);
                this.props.officeManageStore.getPostInfoTable(this.props.officeManageStore.officeClassifyId);
              });
            } else {
              message.error(msg || "编辑失败");
            }
          });
          return;
        }
        savePostInfo(payload).then(({ code, msg }) => {
          this.setState({ loading: false });
          if (code === 200) {
            message.success("新增成功");
            this.setState({ editId: "" }, () => {
              this.props.officeManageStore.setVisible(false);
              this.props.officeManageStore.getPostInfoTable(this.props.officeManageStore.officeClassifyId);
            });
          } else {
            message.error(msg || "新增失败");
          }
        });
      } else {
        f.showErrors();
        this.setState({ date: new Date() }); // 改变一个state的变量,强制页面刷新
      }
    });
  }

  getTopMenuBtns = () => {
    const { officeManageStore,importDialog } = this.props;
    const { topMenu, tableStore, officeClassifyId } = officeManageStore;
    let btns = [];
    topMenu.map((item, i) => {
      if (item.menuFun !== "batchDelete" && item.menuFun !== "delPlan") {
        btns.push(
          <Button
            type="primary"
            disabled={item.menuFun == "editPlan" && !officeClassifyId}
            onClick={() => {
              const { officeManageStore } = this.props;
              if (item.menuFun == "new") {
                officeManageStore.isPanelShow &&
                officeManageStore.setPanelStatus(false);
                officeManageStore.getPostInfoForm({ planId: officeClassifyId });
                officeManageStore.setVisible(true);
                officeManageStore.setNeDialogTitle(i18n.label.newOfficeName());
              } else if (
                item.menuFun == "addPlan" ||
                item.menuFun == "editPlan"
              ) {
                officeManageStore.getPostForm(
                  item.menuFun == "editPlan" ? officeClassifyId : ""
                );
                officeManageStore.setOfficeVisible({
                  bool: true,
                  type: item.menuFun
                });
              }else if(item.menuFun == "import") {
                importDialog.importVisible=true;
                importDialog.importModule='postInfo';
                importDialog.current = 0;
                importDialog.getImportForm();
              }
            }}>
            {item.menuName}
          </Button>
        );
      } else if (item.menuFun === "delPlan") {
        btns.push(
          <Button
            type="primary"
            onClick={() => {
              confirm({
                title: i18n.confirm.defaultTitle(),
                content: i18n.confirm.delete(),
                okText: i18n.button.ok(),
                cancelText: i18n.button.cancel(),
                onOk: () => {
                  this.setState({
                    deleteOfficeClassifyFlag: !this.state
                      .deleteOfficeClassifyFlag
                  });
                },
                onCancel() {
                  return false;
                }
              });
            }}
            disabled={
              !officeClassifyId ||
              (officeClassifyId && !_.isEmpty(toJS(tableStore.datas)))
            }>
            {item.menuName}
          </Button>
        );
      } else {
        btns.push(
          <Button
            type="primary"
            onClick={() => {
              const { officeManageStore } = this.props;
              const { tableStore } = officeManageStore;
              const ids = toJS(tableStore.selectedRowKeys).toString();
              this.showConfirm("batchDel", ids);
            }}
            disabled={tableStore.selectedRowKeys.length > 0 ? false : true}>
            {item.menuName}
          </Button>
        );
      }
    });
    return btns;
  };

  showConfirm = (v, ids) => {
    confirm({
      title: i18n.confirm.defaultTitle(),
      content:
        v == "del" ? i18n.confirm.delete() : i18n.confirm.batchDeleteConfirm(),
      okText: i18n.button.ok(),
      cancelText: i18n.button.cancel(),
      onOk: () => this.deletePostinfoByIds(ids),
      onCancel() {
        return false;
      }
    });
  };

  deletePostinfoByIds = ids => {
    const { officeManageStore } = this.props;
    const { deletePostinfoByIds } = officeManageStore;
    deletePostinfoByIds({ ids }).then(({ code, msg }) => {
      if (code === 200) {
        message.success("删除成功");
        officeManageStore.getPostInfoTable(officeManageStore.officeClassifyId);
      } else {
        message.error(msg || "删除失败");
      }
    });
  };

  reRenderColumns = columns => {
    let _this = this;
    columns.forEach((c, index) => {
      if (c.dataIndex == "forbidden_tag") {
        c.render = function (text, record) {
          return (
            <Switch
              checked={record.forbidden_tag == "0" ? true : false}
              onChange={checked => {
                confirm({
                  title: i18n.confirm.defaultTitle(),
                  content:
                    record.forbidden_tag === "0" ? "确定禁用该记录吗？" : "确定启用该记录吗？",
                  okText: i18n.button.ok(),
                  cancelText: i18n.button.cancel(),
                  onOk: () => _this.updateForbiddenTag(checked, record.id),
                  onCancel() {
                    return false;
                  }
                });
              }}
            />
          );
        };
      }
    });
  };

  updateForbiddenTag = (forbiddentag, id) => {
    const { officeManageStore } = this.props;
    const { updateForbiddenTagById } = officeManageStore;
    const payload = {
      id,
      forbiddentag
    };
    updateForbiddenTagById(payload).then(({ code, msg }) => {
      if (code === 200) {
        message.success("操作成功");
        officeManageStore.getPostInfoTable(officeManageStore.officeClassifyId, true);
      } else {
        message.error(msg || "操作失败");
      }
    });
  };

  onOperatesClick = (record, index, operate) => {
    operate.index == "0" && this.doEdit(record.randomFieldId);
    operate.index === "1" && this.showConfirm("del", record.randomFieldId);
  };
  doEdit = editId => {
    this.setState({ editId });
    const { officeManageStore } = this.props;
    officeManageStore.isPanelShow && officeManageStore.setPanelStatus(false);
    officeManageStore.getPostInfoForm({ id: editId });
    officeManageStore.setVisible(true);
    officeManageStore.setNeDialogTitle(i18n.label.editOfficeName());
  };

  getPanelComponents = () => {
    const { officeManageStore } = this.props;
    const {
      searchCondition,
      form2,
      searchConditionLoading
    } = officeManageStore;
    let arr = [];
    let formParams = form2.getFormParams();
    const { isFormInit } = form2;
    isFormInit &&
    searchCondition.map(c => {
      c.items.map((field, index) => {
        arr.push(
          <Col
            ecId={`${(this && this.props && this.props.ecId) ||
            ""}_Col@4cc308@${index}`}
            span={index % 2 == 0 ? 10 : 11}
            offset={1}>
            <div style={{ marginTop: 20 }}>
              <WeaFormItem
                ecId={`${(this && this.props && this.props.ecId) ||
                ""}_WeaFormItem@u6ex85@${index}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}>
                {
                  <WeaSwitch
                    ecId={`${(this && this.props && this.props.ecId) ||
                    ""}_WeaSwitch@p7d3td@${index}`}
                    fieldConfig={field}
                    form={form2}
                    formParams={formParams}
                  />
                }
              </WeaFormItem>
            </div>
          </Col>
        );
      });
    });

    if (searchConditionLoading) {
      return (
        <div className="hrm-loading-center-small" style={{ top: "25%" }}>
          <Spin
            ecId={`${(this && this.props && this.props.ecId) ||
            ""}_Spin@lbktzb`}
            spinning={searchConditionLoading}
          />
        </div>
      );
    } else {
      return (
        <Row
          ecId={`${(this && this.props && this.props.ecId) || ""}_Row@ppeb6z`}
          onKeyDown={e => {
            if (e.keyCode == 13 && e.target.tagName === "INPUT") {
              officeManageStore.getPostInfoTable();
              officeManageStore.setPanelStatus(false);
            }
          }}>
          {arr}
        </Row>
      );
    }
  };
  getTabBtn = () => {
    const { officeManageStore } = this.props;
    const { form2 } = officeManageStore;

    const btn = [
      <Button
        ecId={`${(this && this.props && this.props.ecId) || ""}_Button@bx87i8`}
        type="primary"
        onClick={() => {
          officeManageStore.getPostInfoTable();
          officeManageStore.setPanelStatus(false);
        }}>
        {i18n.button.search()}
      </Button>,
      <Button
        ecId={`${(this && this.props && this.props.ecId) || ""}_Button@218ju6`}
        onClick={() => form2.reset()}>
        {i18n.button.reset()}
      </Button>,
      <Button
        ecId={`${(this && this.props && this.props.ecId) || ""}_Button@5u9mfz`}
        onClick={() => officeManageStore.setPanelStatus(false)}>
        {i18n.button.cancel()}
      </Button>
    ];

    return btn;
  };
  onSearchChange = val => {
    const { officeManageStore } = this.props;
    const { form2 } = officeManageStore;
    officeManageStore.setPostInfoName(val);
    !_.isEmpty(form2.getFormParams()) && officeManageStore.updateFields(val);
  };

  render() {
    const { officeManageStore,importDialog } = this.props;
    const { date, loading, deleteOfficeClassifyFlag } = this.state;
    const {
      isPanelShow,
      form2,
      postInfoName,
      conditionNum,
      tableStore,
      nEdialogTitle,
      visible,
      condition,
      form,
      dialogLoading,
      hasRight
    } = officeManageStore;
    const {importVisible} = importDialog;

    if (hasRight === false) {
      return renderNoright();
    }

    return (
      hasRight && <div className="office-wapper">
        <WeaTop
          ecId={`${(this && this.props && this.props.ecId) ||
          ""}_WeaTop@446d12`}
          title={i18n.label.officeName()}
          icon={<i className="icon-coms-hrm"/>}
          iconBgcolor="#217346"
          loading={true}
          buttons={this.getTopMenuBtns()}
          showDropIcon={true}
          dropMenuDatas={this.getDropMenuDatas()}
          onDropMenuClick={e => this.handleMenuClick(e)}>
        </WeaTop>
        <WeaLeftRightLayout
          isNew={true}
          leftCom={
            <LeftTree deleteOfficeClassifyFlag={deleteOfficeClassifyFlag}/>
          }>
          <WeaRightMenu
            ecId={`${(this && this.props && this.props.ecId) ||
            ""}_WeaRightMenu@cea97d`}
            datas={this.getDropMenuDatas()}
            onClick={key => this.handleMenuClick(key)}>
            <WeaTab
              ecId={`${(this && this.props && this.props.ecId) ||
              ""}_WeaTab@39c727`}
              searchType={["base", "advanced"]}
              showSearchAd={isPanelShow}
              searchsBaseValue={
                _.isEmpty(form2.getFormParams())
                  ? postInfoName
                  : form2.getFormParams().postInfoName
              }
              setShowSearchAd={bool => officeManageStore.setPanelStatus(bool)}
              hideSearchAd={() => officeManageStore.setPanelStatus(false)}
              searchsAd={isPanelShow ? this.getPanelComponents() : <div/>}
              advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
              hasMask={false}
              buttonsAd={this.getTabBtn()}
              onSearch={() => officeManageStore.getPostInfoTable()}
              onSearchChange={val => this.onSearchChange(val)}
            />
            <WeaTable
              ecId={`${(this && this.props && this.props.ecId) ||
              ""}_WeaTable@b43a4c`}
              comsWeaTableStore={tableStore}
              hasOrder={true}
              needScroll={true}
              rowSelection={{
                getCheckboxProps: record => {
                  console.log(record);
                  return {
                    disabled: true // 配置无法勾选的列
                  };
                }
              }}
              getColumns={c => this.reRenderColumns(c)}
              onOperatesClick={(record, index, operate) =>
                this.onOperatesClick(record, index, operate)}
            />
            <NewAndEditDialog
              ecId={`${(this && this.props && this.props.ecId) ||
              ""}_NewAndEditDialog@q4rrwm`}
              title={nEdialogTitle}
              visible={visible}
              condition={toJS(condition)}
              form={form}
              isFormInit={form.isFormInit}
              loading={dialogLoading || loading}
              isEdit={true}
              height={400}
              conditionLen={1}
              save={() => this.handleSave()}
              onCancel={() => {
                officeManageStore.setVisible(false);
                this.setState({ editId: "" });
              }}
            />
          </WeaRightMenu>
          {importVisible && <ImportDialog ecId={`${this && this.props && this.props.ecId || ''}_ImportDialog@633i8k`} />}
        </WeaLeftRightLayout>
      </div>
    );
  }
}
