import React from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { Button, Dropdown, Menu, message, Modal } from "antd";
import { WeaLocaleProvider, WeaNewScroll, WeaSelect, WeaSlideModal, WeaTab, WeaTools, WeaTop } from "ecCom";
import { getSearchs, renderNoright } from "../../../util";
import SlideModalTitle from "../../../components/slideModalTitle";
import TipLabel from "../../../components/TipLabel";
import DefaultSlideForm from "./defaultSlideForm";
import CustomNewModal from "./customNewModal";
import { paymentScopeEnum, welfareTypeEnum } from "./enum";
import CustomPaginationTable from "../../../components/customPaginationTable";
import TwoColContent from "../../../components/twoColContent";
import CopySchemaModal from "./copySchemaModal";
import CustomBenefitsTable from "./customBenefitsTable";
import { conditons } from "./columns";
import "./index.less";

const getKey = WeaTools.getKey;
const { getLabel } = WeaLocaleProvider;
@inject("programmeStore", "taxAgentStore", "salaryFileStore")
@observer
export default class Programme extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      searchValue: "",
      slideVisiable: false,
      currentOperate: "add",
      copyModalValue: "",
      copyId: "",
      customNewVisible: false,
      customEdit: false,
      showSearchAd: false
    };

    this.pageInfo = { current: 1, pageSize: 10 };
  }

  componentWillMount() {
    const { programmeStore, salaryFileStore, taxAgentStore } = this.props;
    const { doInit, planSearchForm } = programmeStore;
    doInit();
    const { commonEnumList } = salaryFileStore;
    commonEnumList("user", { enumClass: "com.engine.salary.enums.sicategory.SharedTypeEnum" });
    const { getTaxAgentSelectListAsAdmin } = taxAgentStore;
    getTaxAgentSelectListAsAdmin();
    planSearchForm.initFormFields(_.map(conditons, item => {
      return {
        ...item,
        items: _.map(item.items, o => {
          if (getKey(o) === "paymentTypeEnum") {
            return {
              ...o,
              options: [
                { key: "SCHEME_TOWN", showname: getLabel(19702, "城镇") },
                { key: "SCHEME_VILLAGE", showname: getLabel(19703, "农村") }
              ]
            };
          }
          return { ...o };
        })
      };
    }));
  }

  // 增加编辑功能，重写columns绑定事件
  getColumns = columns => {
    const { taxAgentStore: { showOperateBtn } } = this.props;
    let newColumns = columns.filter(
      item => item.dataIndex !== "id" && item.dataIndex !== "paymentArea"
    );

    newColumns = newColumns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        //前端元素转义
        let valueSpan =
          record[newColumn.dataIndex + "span"] !== undefined
            ? record[newColumn.dataIndex + "span"]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === "id") newColumn.display = false;
        switch (newColumn.dataIndex) {
          case "operate":
            return (
              <a href="javascript: void(0);" onClick={() => this.onEdit(record)}>编辑</a>
            );
          default:
            return <div dangerouslySetInnerHTML={{ __html: valueSpan }}/>;
        }
      };
      return newColumn;
    });

    newColumns.push({
      title: "操作",
      dataIndex: "operate",
      width: 120,
      render: (text, record) => {
        return (
          <React.Fragment>
            <a href="javascript:void(0);" onClick={() => this.onEdit(record)}
               style={{ marginRight: 10 }}>{showOperateBtn ? "编辑" : "查看"}</a>
            {
              showOperateBtn &&
              <a href="javascript:void(0)" onClick={() => this.onCopy(record)}
                 style={{ marginRight: 10 }}>{getLabel(77, "复制")}</a>
            }
            {
              showOperateBtn &&
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item>
                      <a href="javascript:void(0)" onClick={() => this.onDelete(record)}>{getLabel(535052, "删除")}</a>
                    </Menu.Item>
                  </Menu>
                }>
                <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
              </Dropdown>
            }
          </React.Fragment>
        );
      }
    });
    return newColumns;
  };

  onEdit = (record) => {
    let id = record.id;
    const { programmeStore } = this.props;
    const { getForm, selectedKey } = programmeStore;
    getForm({
      welfareTypeEnum: selectedKey,
      id
    }).then(() => {
      this.setState({ slideVisiable: true, customEdit: true, currentOperate: "update" });
    });
  };

  onCopy = (record) => {
    this.setState({
      copyId: record.id,
      copyModalValue: record.schemeName,
      copyModalVisible: true
    });
  };

  onDelete = (record) => {
    const { programmeStore: { deleteScheme, deleteLoading, selectedKey } } = this.props;
    Modal.confirm({
      title: "确认信息",
      content: "确认删除本条数据吗？",
      confirmLoading: deleteLoading,
      onOk: () => {
        deleteScheme({ ids: [record.id], welfareTypeEnum: selectedKey });
      },
      onCancel: () => {
      }
    });
  };

  onCustomEdit = (record) => {
    const {
      programmeStore: { getCustomForm, setCustomNewVisible, setCustomRequest },
      taxAgentStore: { showOperateBtn }
    } = this.props;
    if (!showOperateBtn) {
      message.warning("请设置编辑权限！");
      return;
    }
    getCustomForm();
    setCustomNewVisible(true);
    this.setState({
      customEdit: true
    });
    setCustomRequest({
      insuranceName: record["insuranceName"],
      id: record.id,
      isUse: record.isUse,
      paymentScope: record["paymentScope"].split(",").map(item => paymentScopeEnum[item]).join(","),
      welfareType: welfareTypeEnum[record.welfareType]
    });
  };

  // 页面跳转
  handlePageChange(value) {
    const { programmeStore: { form, getTableDatas, selectedKey } } = this.props;
    this.pageInfo.current = value;
    getTableDatas(selectedKey, this.pageInfo);
  }

  render() {
    const { showSearchAd } = this.state;
    const { programmeStore, taxAgentStore: { showOperateBtn } } = this.props;
    const { loading, hasRight, form, getTableDatas } = programmeStore;
    const {
      selectedKey,
      setSelectedKey,
      customSelectkey,
      setCustomSelectkey,
      requestParams,
      setRequestParams,
      formCondition,
      setCustomNewVisible,
      customNewVisible,
      tableDataSource,
      tableColumns,
      tablePageInfo,
      planSearchForm
    } = programmeStore;
    if (!hasRight && !loading) return renderNoright();

    const topTab = [
      {
        title: "社保",
        viewcondition: "SOCIAL_SECURITY"
      },
      {
        title: "公积金",
        viewcondition: "ACCUMULATION_FUND"
      },
      {
        title: "企业年金及其他福利",
        viewcondition: "OTHER"
      },
      {
        title: "自定义福利",
        viewcondition: "custom"
      }
    ];

    const options = [
      {
        showname: "全部",
        key: ""
      },
      {
        showname: "社保",
        key: "SOCIAL_SECURITY"
      },
      {
        showname: "公积金",
        key: "ACCUMULATION_FUND"
      },
      {
        showname: "企业年金及其他福利",
        key: "OTHER"
      }
    ];

    const handleNewClick = () => {
      const {
        programmeStore: { initSlideParms, getForm, selectedKey }
      } = this.props;
      initSlideParms();
      this.setState({ slideVisiable: true, currentOperate: "add" });
      getForm({ welfareTypeEnum: selectedKey });
    };

    const handleCustomNewClick = () => {
      const {
        programmeStore: {
          getCustomForm,
          setCustomNewVisible,
          setCustomRequest
        }
      } = this.props;
      getCustomForm();
      setCustomRequest({});
      setCustomNewVisible(true);
      this.setState({ customEdit: false });
    };

    const handleOnSave = () => {
      const { programmeStore } = this.props;
      const { currentOperate } = this.state;
      const {
        selectedKey,
        defaultPersonDataSource,
        defaultCompanyDataSource,
        createScheme,
        requestParams,
        updateScheme
      } = programmeStore;
      let { schemeName, remarks, paymentArea, paymentType, sharedType, taxAgentIds } = requestParams;
      let request = {
        insuranceScheme: {
          paymentType,
          welfareType: selectedKey,
          schemeName,
          remarks,
          paymentArea,
          sharedType,
          taxAgentIds
        },
        insuranceSchemeDetailList: [
          ...defaultPersonDataSource,
          ...defaultCompanyDataSource
        ]
      };
      if (currentOperate == "add") {
        createScheme(request).then(res => {
          if (res.status) this.setState({ slideVisiable: false });
        });
      } else if (currentOperate == "update") {
        request.insuranceScheme.id = requestParams.id;
        updateScheme(request).then(res => {
          if (res.status) this.setState({ slideVisiable: false });
        });
      }
    };

    const renderCustomRightContent = () => {
      let tipList = [
        "1、可以为社保、公积金、企业年金及其他福利新增自定义的福利项，如：残疾保险等",
        "2、新增自定义福利默认启用，社保福利方案中的自定义福利项均未开启缴纳，当前页面的自定义福利项才可以停用；停用后再新增方案时没有该福利项",
        "3、自定义福利若要缴纳，需要在方案里填写缴纳相关数据"
      ];
      return <TipLabel tipList={tipList}/>;
    };

    const handleCopyModalSave = () => {
      const { programmeStore: { copyScheme } } = this.props;
      const { copyId, copyModalValue } = this.state;
      if (_.isEmpty(this.refs.copyRef.state.value)) {
        this.refs.copyRef.refs.weaError.showError();
      } else {
        copyScheme({ id: copyId, schemeName: copyModalValue }).then(() => {
          this.setState({ copyModalVisible: false });
        });
      }
    };

    const handleSlideClose = () => {
      this.setState({ slideVisiable: false, customEdit: false });
      const { programmeStore: { initSlideParms } } = this.props;
      initSlideParms();
    };
    const customButtons = [
      <WeaSelect
        options={options}
        value={customSelectkey}
        style={{ width: "150px" }}
        onChange={v => {
          setCustomSelectkey(v);
          this.customBenefitsTableRef.getCustomCategoryList({ current: 1, welfareTypeEnum: v });
        }}
      />
    ];
    const tabButtons = [
      <Button type="primary" onClick={() => {
        selectedKey === "custom" ? handleCustomNewClick() : handleNewClick();
      }}>{getLabel(365, "新建")}</Button>
    ];
    return (
      <div className="socialSecurityAndWelfareSchemeWrapper">
        <WeaTop
          title="社保福利方案" icon={<i className="icon-coms-fa"/>}
          iconBgcolor="#F14A2D" showDropIcon={false}
        >
          <WeaTab
            datas={topTab} keyParam="viewcondition" selectedKey={selectedKey}
            searchType={selectedKey !== "custom" ? ["base", "advanced"] : []}
            showSearchAd={showSearchAd}
            setShowSearchAd={bool => this.setState({ showSearchAd: bool })}
            advanceHeight={200} searchsAd={getSearchs(planSearchForm, _.map(conditons, item => {
            return {
              ...item,
              items: _.map(item.items, o => {
                if (getKey(o) === "paymentTypeEnum") {
                  return {
                    ...o,
                    options: [
                      { key: "SCHEME_TOWN", showname: getLabel(19702, "城镇") },
                      { key: "SCHEME_VILLAGE", showname: getLabel(19703, "农村") }
                    ]
                  };
                }
                return { ...o };
              })
            };
          }), 2, false)}
            onAdSearch={() => getTableDatas(selectedKey)}
            onAdReset={v => planSearchForm.resetForm()}
            onSearch={() => getTableDatas(selectedKey)}
            onChange={v => {
              setSelectedKey(v);
              handleSlideClose();
              v !== "custom" && getTableDatas(v);
            }}
            onSearchChange={v => planSearchForm.updateFields({ schemeName: v })} // 在搜索框中输入的文字改变时的回调: 这里需要同步高级搜索和外部搜索框的值
            searchsBaseValue={planSearchForm.getFormParams().schemeName}
            buttons={!showOperateBtn ? [] : selectedKey !== "custom" ? tabButtons : [...tabButtons, ...customButtons]}
          />
          <div className="tableWrapper">
            <WeaNewScroll height="100%">
              {selectedKey === "custom"
                ? <TwoColContent
                  leftContent={
                    <CustomBenefitsTable
                      ref={dom => this.customBenefitsTableRef = dom}
                      showOperateBtn={showOperateBtn}
                      welfareTypeEnum={customSelectkey}
                      onCustomEdit={this.onCustomEdit}
                    />
                  }
                  rightContent={renderCustomRightContent()}
                />
                : <CustomPaginationTable
                  loading={loading}
                  columns={this.getColumns(tableColumns)}
                  dataSource={tableDataSource}
                  total={toJS(tablePageInfo).total}
                  current={toJS(tablePageInfo).pageNum}
                  pageSize={this.pageInfo.pageSize}
                  onPageChange={value => {
                    this.handlePageChange(value);
                  }}
                  onShowSizeChange={(current, pageSize) => {
                    this.pageInfo = { current, pageSize };
                    const {
                      programmeStore: { form, getTableDatas, selectedKey }
                    } = this.props;
                    getTableDatas(selectedKey, this.pageInfo);
                  }}
                />}
            </WeaNewScroll>
          </div>
        </WeaTop>
        <WeaSlideModal
          className="slideOuterWrapper"
          visible={this.state.slideVisiable}
          top={0}
          measureT="%"
          width={100}
          measureX="%"
          height={100}
          measureY="%"
          direction={"right"}
          title={
            <SlideModalTitle
              subtitle={
                this.state.customEdit ?
                  `修改${_.find(topTab, it => it.viewcondition === selectedKey).title}方案` :
                  `新增${_.find(topTab, it => it.viewcondition === selectedKey).title}方案`
              }
              editable={true}
              showOperateBtn={showOperateBtn}
              onSave={() => handleOnSave()}
            />
          }
          content={
            this.state.slideVisiable ?
              <DefaultSlideForm
                customEditVisible={this.state.customEdit}
                requestParams={requestParams}
                onChange={requestParams => {
                  setRequestParams(requestParams);
                }}
              /> : null
          }
          onClose={() => {
            handleSlideClose();
          }}
        />

        {this.state.copyModalVisible &&
          <CopySchemaModal
            ref="copyRef"
            title={_.filter(topTab, it => it.viewcondition === selectedKey)[0].title}
            visible={this.state.copyModalVisible}
            value={this.state.copyModalValue}
            onChange={value => this.setState({ copyModalValue: value })}
            onCancel={() => {
              this.setState({ copyModalVisible: false });
            }}
            footer={
              [<Button
                type="primary"
                onClick={() => {
                  handleCopyModalSave();
                }}>
                保存
              </Button>]
            }
          />}

        {customNewVisible &&
          <CustomNewModal
            visible={customNewVisible}
            condition={formCondition}
            form={form}
            edit={this.state.customEdit}
            onCancel={(isRefresh) => {
              setCustomNewVisible(false);
              isRefresh && this.customBenefitsTableRef.getCustomCategoryList();
            }}
          />}
      </div>
    );
  }
}
