import React from "react";
import { Button, Col, Icon, message, Modal, Row } from "antd";
import {
  WeaBrowser,
  WeaFormItem,
  WeaHelpfulTip,
  WeaInput,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaSelect,
  WeaTab
} from "ecCom";
import { inject, observer } from "mobx-react";
import { getQueryString } from "../../util/url";
import "./index.less";

const { getLabel } = WeaLocaleProvider;
@inject("calculateStore", "salaryFileStore")
@observer
export default class UserSure extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showSearchAd: false,
      searchItemsValue: {
        employeeName: "",
        workcode: "",
        departmentIds: "",
        positionIds: "",
        statuses: ""
      },
      selectedKey: "0",
      selectedRowKeys: [], // table 选中项
      userListSearchValue: ""
    };
    this.id = "";
    this.current = 1;
    this.pageInfo = { current: 1, pageSize: 10 };
  }

  componentWillMount() {
    let id = getQueryString("id");
    this.id = id;
    const { calculateStore } = this.props;
    const {
      salaryacctGetForm,
      getSalarySobCycle
    } = calculateStore;
    salaryacctGetForm(id);
    this.current = 1;
    getSalarySobCycle(id);
  }

  Input = (value, key) => {
    const { employeeName, workcode } = this.state.searchItemsValue;
    return (
      <WeaFormItem
        label={value}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaInput value={key === "employeeName" ? employeeName : workcode}
                  onChange={(val) => this.setState({
                    searchItemsValue: {
                      ...this.state.searchItemsValue,
                      [key]: val
                    }
                  })}/>
      </WeaFormItem>
    );
  };
  Browser = (value, key) => {
    const { positionIds, departmentIds } = this.state.searchItemsValue;
    return (
      <WeaFormItem
        label={value}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaBrowser
          isSingle={false}
          value={key === "departmentIds" ? departmentIds : positionIds}
          type={key === "departmentIds" ? 57 : 278}
          onChange={(val) => {
            this.setState({ searchItemsValue: { ...this.state.searchItemsValue, [key]: val } });
          }}/>
      </WeaFormItem>
    );
  };
  Select = (value, key) => {
    const { statuses } = this.state.searchItemsValue;
    return (
      <WeaFormItem
        label={value}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <WeaSelect
          multiple
          value={String(statuses)}
          options={[
            { key: "0", showname: "试用" }, { key: "1", showname: "正式" },
            { key: "2", showname: "临时" }, { key: "3", showname: "试用延期" },
            { key: "4", showname: "解雇" }, { key: "5", showname: "离职" },
            { key: "6", showname: "退休" }
          ]}
          onChange={(val) => this.setState({ searchItemsValue: { ...this.state.searchItemsValue, [key]: val } })}/>
      </WeaFormItem>
    );
  };

  componentDidMount() {
    window.addEventListener("message", this.handleClick, false);
  }

  componentWillUnmount() {
    window.removeEventListener("message", this.handleClick, false);
  }

  handleClick = ({ data }) => {
    const childFrameObj = document.getElementById("atdTable");
    const salaryAcctRecordId = getQueryString("id");
    const { type, data: { id, data: record, extraId = "" } = {} } = data;
    let payload = {};
    if (type === "PC") {
      if (id === "SA") {
        payload = {
          type: "PC",
          listType: "SA",
          url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
          queryParams: {
            salaryAcctRecordId,
            ...this.state.searchItemsValue
          }
        };
        childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*"); //window.postMessage
      } else if (id === "DELETE") {
        this.handleDeleteItem(record);
      } else if (id === "COSTCENTER") {
        window.open(record.url, "_blank");
      } else if (id === "BATCHDELETE") {
        this.onSelectChange(record);
      } else if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = record;
        this.pageInfo = { current, pageSize };
        if (extraId === "SA") {
          const payload = {
            type: "PC",
            listType: "SA",
            url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
            queryParams: {
              salaryAcctRecordId,
              ...this.state.searchItemsValue,
              current,
              pageSize
            }
          };
          childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        } else if (extraId === "MA") {
          const payload = {
            type: "PC",
            listType: "MA",
            url: this.state.selectedKey === "1" ? "/api/bs/hrmsalary/salaryacct/reducedemployee/list" : "/api/bs/hrmsalary/salaryacct/addedemployee/list",
            queryParams: {
              salaryAcctRecordId,
              ...this.state.searchItemsValue,
              current, pageSize
            }
          };
          childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        }
      }
    }
  };

  // 添加人员回调
  handleUserBrowserChange(ids) {
    const childFrameObj = document.getElementById("atdTable");
    const salaryAcctRecordId = getQueryString("id");
    if (ids && ids.length > 0) {
      let idList = ids.split(",");
      const {
        calculateStore: { saveAcctemployee, checkTaxAgent }
      } = this.props;
      saveAcctemployee(this.id, idList).then(() => {
        message.success("添加成功");
        const payload = {
          type: "PC",
          listType: "SA",
          url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
          queryParams: {
            salaryAcctRecordId,
            ...this.state.searchItemsValue,
            ...this.pageInfo
          }
        };
        childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        checkTaxAgent(this.id);
      });
    }
  }

  // 导出
  handleExport() {
    let url = "";
    if (this.state.selectedKey == 0) {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/acctemployee/export?salaryAcctRecordId=${this.id}`;
    } else if (this.state.selectedKey == 1) {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/reducedemployee/export?salaryAcctRecordId=${this.id}`;
    } else {
      url = `${window.location.origin}/api/bs/hrmsalary/salaryacct/addedemployee/export?salaryAcctRecordId=${this.id}`;
    }
    window.open(url, "_self");
  }

  // 批量删除
  handleBatchDelete() {
    const { selectedRowKeys } = this.state;
    const {
      calculateStore: { deleteAcctemployee }
    } = this.props;
    if (selectedRowKeys.length == 0) {
      message.warning("未选择条目");
      return;
    }
    Modal.confirm({
      title: "信息确认",
      content: "确认删除",
      onOk: () => {
        const childFrameObj = document.getElementById("atdTable");
        const salaryAcctRecordId = getQueryString("id");
        deleteAcctemployee(this.id, selectedRowKeys).then(() => {
          message.success("删除成功");
          const payload = {
            type: "PC",
            listType: "SA",
            url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
            queryParams: {
              salaryAcctRecordId,
              ...this.state.searchItemsValue,
              ...this.pageInfo,
              current: 1
            }
          };
          childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        });
      },
      onCancel: () => {
      }
    });
  }

  // 删除人员
  handleDeleteItem = record => {
    const {
      calculateStore: { deleteAcctemployee }
    } = this.props;
    Modal.confirm({
      title: "信息确认",
      content: "确认删除",
      onOk: () => {
        deleteAcctemployee(this.id, [record.id]).then(() => {
          const childFrameObj = document.getElementById("atdTable");
          const salaryAcctRecordId = getQueryString("id");
          const payload = {
            type: "PC",
            listType: "SA",
            url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
            queryParams: {
              salaryAcctRecordId,
              ...this.state.searchItemsValue,
              ...this.pageInfo
            }
          };
          childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
        });
      },
      onCancel: () => {
      }
    });
  };

  // 刷新薪资核算人员的个税扣缴义务人
  handleRefresh = () => {
    const childFrameObj = document.getElementById("atdTable");
    const salaryAcctRecordId = getQueryString("id");
    const {
      calculateStore: { refreshTaxAgent }
    } = this.props;
    refreshTaxAgent(salaryAcctRecordId).then(() => {
      const payload = {
        type: "PC",
        listType: "SA",
        url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
        queryParams: {
          salaryAcctRecordId,
          ...this.state.searchItemsValue,
          ...this.pageInfo
        }
      };
      childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
    });
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys, userListSearchValue: "" });
  };

  // 搜索
  handleUserListSearch = (value) => {
    const childFrameObj = document.getElementById("atdTable");
    const salaryAcctRecordId = getQueryString("id");
    this.pageInfo.current = 1;
    if (this.state.selectedKey == 0) {
      const payload = {
        type: "PC",
        listType: "SA",
        url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
        queryParams: {
          salaryAcctRecordId,
          ...value
        }
      };
      childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
    } else {
      const payload = {
        type: "PC",
        listType: "MA",
        url: "/api/bs/hrmsalary/salaryacct/reducedemployee/list",
        queryParams: {
          salaryAcctRecordId,
          ...value
        }
      };
      childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
    }
  };

  render() {
    const { showSearchAd, selectedKey } = this.state;
    const { calculateStore } = this.props;
    const { calculateBaseForm, baseSalarySobCycle } = calculateStore;

    const adBtn = [
      // 高级搜索内部按钮
      <Button type="primary" onClick={() => {
        this.setState({ showSearchAd: false }, () => {
          this.handleUserListSearch(this.state.searchItemsValue);
        });
      }}>
        搜索
      </Button>,
      <Button type="ghost" onClick={() => this.setState({
        searchItemsValue: {
          employeeName: "",
          departmentIds: "",
          positionIds: "",
          statuses: ""
        }
      })}>
        重置
      </Button>,
      <Button type="ghost" onClick={() => this.setState({ showSearchAd: false })}>
        取消
      </Button>
    ];

    const renderSearch = () => {
      const searchItems = [
        { com: this.Input("姓名", "employeeName") },
        { com: this.Input("工号", "workcode") },
        { com: this.Browser("部门", "departmentIds") },
        { com: this.Browser("岗位", "positionIds") },
        { com: this.Select("状态", "statuses") }
      ];
      return <WeaSearchGroup title={"基本信息"} items={searchItems} showGroup/>;
    };

    return (
      <div className="userSure">
        <div className="baseInfo">基本信息</div>
        <div className="formWrapper">
          <Row>
            <Col span={12}>
              <Row>
                <Col span={6}>
                  薪资所属月：<WeaHelpfulTip
                  title={!_.isEmpty(baseSalarySobCycle) ?
                    <SalaryMonthTip baseSalarySobCycle={baseSalarySobCycle}/> : ""}
                  placement="topLeft"
                />
                </Col>
                <Col span={18}>
                  {calculateBaseForm.formDTO &&
                    calculateBaseForm.formDTO.salaryMonth}
                </Col>
              </Row>
            </Col>
            <Col span={12}>
              <Row>
                <Col span={6}>核算账套：</Col>
                <Col span={18}>
                  {calculateBaseForm.formDTO &&
                    calculateBaseForm.formDTO.salarySobName}
                </Col>
              </Row>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Row>
                <Col span={6}>备注：</Col>
                <Col span={18}>
                  {calculateBaseForm.formDTO &&
                    calculateBaseForm.formDTO.description}
                </Col>
              </Row>
            </Col>
          </Row>
        </div>
        <div className="operateBarWrapper">
          <div className="crumbsWrapper">
            <span
              className={
                this.state.selectedKey == "0"
                  ? "crumbItem crumbItemSelected"
                  : "crumbItem"
              }
              onClick={() => {
                this.setState({ selectedKey: "0" }, () => {
                  const childFrameObj = document.getElementById("atdTable");
                  const salaryAcctRecordId = getQueryString("id");
                  const payload = {
                    type: "PC",
                    listType: "SA",
                    url: "/api/bs/hrmsalary/salaryacct/acctemployee/list",
                    queryParams: {
                      salaryAcctRecordId,
                      ...this.state.searchItemsValue
                    }
                  };
                  childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*"); //window.postMessage
                });
              }}>
              核算人员范围
            </span>
            <WeaHelpfulTip
              width={200}
              title="核算完若薪资档案中个税扣缴义务人发生调整，需先刷新【核算人员范围】再到【薪资核算】中重新核算"
              placement="topLeft"
            />
            <span style={{ margin: "0 8px" }}>|</span>
            <span
              className={
                this.state.selectedKey == "1"
                  ? "crumbItem crumbItemSelected"
                  : "crumbItem"
              }
              onClick={() => {
                this.setState({ selectedKey: "1" }, () => {
                  const childFrameObj = document.getElementById("atdTable");
                  const salaryAcctRecordId = getQueryString("id");
                  const payload = {
                    type: "PC",
                    listType: "MA",
                    url: "/api/bs/hrmsalary/salaryacct/reducedemployee/list",
                    queryParams: {
                      salaryAcctRecordId,
                      ...this.state.searchItemsValue
                    }
                  };
                  childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
                });
              }}>
              环比上月减少人员
            </span>
            <WeaHelpfulTip
              width={200}
              title="提示：环比上期当前选择的账套归档的各个税扣缴义务人下减少的人员"
              placement="topLeft"
            />
            <span style={{ margin: "0 8px" }}>|</span>
            <span
              className={
                this.state.selectedKey == "2"
                  ? "crumbItem crumbItemSelected"
                  : "crumbItem"
              }
              onClick={() => {
                this.setState({ selectedKey: "2" }, () => {
                  const childFrameObj = document.getElementById("atdTable");
                  const salaryAcctRecordId = getQueryString("id");
                  const payload = {
                    type: "PC",
                    listType: "MA",
                    url: "/api/bs/hrmsalary/salaryacct/addedemployee/list",
                    queryParams: {
                      salaryAcctRecordId,
                      ...this.state.searchItemsValue
                    }
                  };
                  childFrameObj.contentWindow.postMessage(JSON.stringify(payload), "*");
                });
              }}>
              环比上月增加人员
            </span>
            <WeaHelpfulTip
              width={200}
              title="提示：环比上期当前选择的账套归档的各个税扣缴义务人下增加的人员"
              placement="topLeft"
            />
          </div>
          <div className="crumbsOperateWrapper">
            <WeaTab
              searchType={selectedKey == 0 ? ["base", "advanced"] : []} // base：基础搜索框 advanced：显示高级搜索按钮
              showSearchAd={showSearchAd} // 是否展开高级搜索面板
              setShowSearchAd={(bool) => this.setState({ showSearchAd: bool })} //高级搜索面板受控
              searchsAd={renderSearch()} // 高级搜索内部数据getSearchs(form, toJS(condition), 2)
              buttonsAd={adBtn} // 高级搜索内部按钮
              onSearch={() => this.handleUserListSearch(this.state.searchItemsValue)} // 点搜索按钮时的回调
              buttons={selectedKey == 0 ? [
                <Icon
                  className="iconItem"
                  style={{ fontSize: 16 }}
                  type="minus-square"
                  onClick={() => {
                    this.handleBatchDelete();
                  }}
                  title="批量删除"
                />,
                <WeaBrowser
                  type={17}
                  title="添加人员"
                  isSingle={false}
                  customized
                  onChange={(ids, names, datas) =>
                    this.handleUserBrowserChange(ids)}>
                  <Icon
                    type="plus-square" title="新增"
                    className="iconItem"
                    style={{ fontSize: 16 }}/>
                </WeaBrowser>,
                <i
                  className="icon-coms-fawen iconItem"
                  onClick={() => {
                    this.handleExport();
                  }}
                  style={{ fontSize: 20, position: "relative", top: 2 }}
                  title="导出"
                />
                // <i
                //   className="icon-coms-Synchro iconItem"
                //   onClick={() => {
                //     this.handleRefresh();
                //   }}
                //   style={{ fontSize: 20, position: "relative", top: 2 }}
                //   title="刷新"
                // />
              ] : [
                <i
                  className="icon-coms-fawen iconItem"
                  onClick={() => {
                    this.handleExport();
                  }}
                  style={{ fontSize: 20, position: "relative", top: 2 }}
                  title="导出"
                />
              ]}
              searchsBasePlaceHolder={"请输入姓名"}
              onSearchChange={(v) =>
                this.setState({
                  searchItemsValue: {
                    ...this.state.searchItemsValue,
                    employeeName: v
                  }
                })
              } // 在搜索框中输入的文字改变时的回调: 这里需要同步高级搜索和外部搜索框的值form.updateFields({ username: v })
              searchsBaseValue={this.state.searchItemsValue.employeeName} // 外部input搜索值受控: 这里和高级搜索的requestname同步form.getFormParams().username
            />
          </div>
        </div>
        <div className="tableWrapper">
          <div style={{ width: "100%", height: "calc(100vh - 261px)" }}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/atdTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/atdTable"
              id="atdTable"
            />
          </div>
        </div>
      </div>
    );
  }
}

export const SalaryMonthTip = (props) => {
  const { baseSalarySobCycle } = props;
  const { salaryCycle, taxCycle, attendCycle, socialSecurityCycle } = baseSalarySobCycle;
  const { fromDate: salaryCycleFromDate, endDate: salaryCycleEndDate } = salaryCycle;
  const { fromDate: attendCycleFromDate, endDate: attendCycleEndDate } = attendCycle;
  return (
    <div className="salaryMonthTip-layout">
      <div className="salaryMonthTipItem">
        <div className="label">{getLabel(543375, "薪资周期")}</div>
        <div className="value">{`${salaryCycleFromDate}${getLabel(15322, "至")}${salaryCycleEndDate}`}</div>
      </div>
      <div className="salaryMonthTipItem">
        <div className="label">{getLabel(542240, "税款所属期")}</div>
        <div className="value">{taxCycle}</div>
      </div>
      <div className="salaryMonthTipItem">
        <div className="label">{getLabel(543475, "考勤取值周期")}</div>
        <div className="value">{`${attendCycleFromDate}${getLabel(15322, "至")}${attendCycleEndDate}`}</div>
      </div>
      <div className="salaryMonthTipItem">
        <div className="label">{getLabel(543466, "福利台账月份")}</div>
        <div className="value">
          {`${getLabel(19422, "引用")}${socialSecurityCycle}${getLabel(543476, "的福利台账数据")}`}
        </div>
      </div>
    </div>
  );
};
