import React from "react";
import { inject, observer } from "mobx-react";
import { Button, DatePicker, message, Modal } from "antd";
import { WeaLocaleProvider, WeaNewScroll, WeaTop } from "ecCom";
import CustomTab from "../../components/customTab";
import CustomTable from "../../components/customTable";
import GenerateModal from "./generateModal";
import { getDeclareList, withDrawTaxDeclaration } from "../../apis/declare";
import { sysConfCodeRule } from "../../apis/ruleconfig";
import moment from "moment";

const getLabel = WeaLocaleProvider.getLabel;
const { MonthPicker } = DatePicker;
@inject("taxAgentStore")
@observer
export default class Declare extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showWithDrawBtn: false,
      declarationModalVisible: false,
      startDate: moment(new Date()).startOf("year").format("YYYY-MM"),
      endDate: moment(new Date()).startOf("month").format("YYYY-MM"),
      loading: false,
      dataSource: [],
      columns: [],
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  }

  componentWillMount() {
    const { taxAgentStore: { getTaxAgentSelectListAsAdmin } } = this.props;
    this.getDeclareList();
    this.sysConfCodeRule();
    getTaxAgentSelectListAsAdmin();
  }

  getDeclareList = () => {
    const { pageInfo, startDate: fromSalaryMonthStr, endDate: endSalaryMonthStr } = this.state;
    const payload = {
      fromSalaryMonthStr, endSalaryMonthStr,
      ...pageInfo
    };
    this.setState({ loading: true });
    getDeclareList(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, list: dataSource, total, pageNum: current, pageSize } = data;
        this.setState({
          columns, dataSource,
          pageInfo: {
            ...pageInfo,
            total, current, pageSize
          }
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  sysConfCodeRule = () => {
    sysConfCodeRule({ code: "WITHDRAW_TAX_DECLARATION" }).then(({ status, data }) => {
      if (status && data === "1") this.setState({ showWithDrawBtn: data === "1" });
    });
  };
  withDrawTaxDeclaration = (taxDeclarationId) => {
    withDrawTaxDeclaration({ taxDeclarationId }).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(111, "撤回成功"));
        this.getDeclareList();
      } else {
        message.error(errormsg || getLabel(111, "撤回失败"));
      }
    });
  };
  // 日期区间改变事件
  handleRangePickerChange = (type, value) => {
    this.setState({
      [type]: value ? moment(value).format("YYYY-MM") : moment().format("YYYY-MM"),
      pageInfo: { ...this.state.pageInfo, current: 1 }
    }, () => {
      this.getDeclareList();
    });
  };
  handleSearch = () => {
    this.setState({ declarationModalVisible: false }, () => this.getDeclareList());
  };
  handleDataPageChange = (current, pageSize = 10) => {
    this.setState({
      pageInfo: {
        ...this.state.pageInfo,
        current,
        pageSize
      }
    }, () => this.getDeclareList());
  };

  render() {
    const { taxAgentStore: { showOperateBtn } } = this.props;
    const { loading, columns, dataSource, pageInfo, showWithDrawBtn } = this.state;
    const renderRightOperation = () => {
      const { startDate, endDate } = this.state;
      return (
        <div style={{ display: "inline-block" }}>
          <MonthPicker
            value={startDate}
            disabledDate={(current) => {
              return current && endDate && current.getTime() > new Date(endDate).getTime();
            }}
            format="YYYY-MM"
            onChange={(val) => this.handleRangePickerChange("startDate", val)}
          />
          <span className="to" style={{ margin: "0 10px" }}>至</span>
          <MonthPicker
            value={endDate}
            disabledDate={(current) => {
              return current && startDate && current.getTime() < new Date(startDate).getTime();
            }}
            format="YYYY-MM"
            onChange={(val) => this.handleRangePickerChange("endDate", val)}
          />
          {
            showOperateBtn &&
            <Button
              type="primary"
              style={{ marginLeft: "10px", position: "relative", top: "-2px" }}
              onClick={() => {
                this.setState({ declarationModalVisible: true });
              }}>
              生成申报单
            </Button>
          }
        </div>
      );
    };

    return (
      <div className="mySalaryBenefitsWrapper">
        <WeaTop title="个税申报表" icon={<i className="icon-coms-fa"/>}
                iconBgcolor="#F14A2D" showDropIcon={false}
        >
          <CustomTab searchOperationItem={renderRightOperation()}/>
          <div className="tableWrapper">
            <WeaNewScroll height="100%">
              <CustomTable
                loading={loading}
                columns={[
                  ...columns,
                  {
                    title: "操作",
                    dataIndex: "operate",
                    render: (text, record) => {
                      return (
                        <React.Fragment>
                          <a href="javascript:void(0);"
                             onClick={() => {
                               window.open(
                                 "/spa/hrmSalary/static/index.html#/main/hrmSalary/generateDeclarationDetail?id=" +
                                 record.id
                               );
                             }}>
                            查看
                          </a>
                          {
                            showWithDrawBtn &&
                            <a
                              href="javascript:void(0);" style={{ marginLeft: 10 }}
                              onClick={() => {
                                Modal.confirm({
                                  title: getLabel(111, "信息确认"),
                                  content: getLabel(111, "确认撤回该条数据吗?"),
                                  onOk: () => this.withDrawTaxDeclaration(record.id)
                                });
                              }}
                            >
                              {getLabel(111, "撤回")}
                            </a>
                          }
                        </React.Fragment>
                      );
                    }
                  }
                ]}
                dataSource={dataSource}
                pagination={{
                  onChange: (value) => {
                    this.handleDataPageChange(value);
                  },
                  total: pageInfo.total,
                  showTotal: (total) => `共 ${total} 条`,
                  current: pageInfo.current,
                  showSizeChanger: true,
                  pageSizeOptions: ["10", "20", "50", "100"],
                  showQuickJumper: true,
                  pageSize: pageInfo.pageSize,
                  onShowSizeChange: (current, pageSize) => {
                    this.handleDataPageChange(current, pageSize);
                  }
                }}
              />
            </WeaNewScroll>
          </div>
        </WeaTop>
        {this.state.declarationModalVisible && (
          <GenerateModal
            onGenerate={this.handleSearch}
            visible={this.state.declarationModalVisible}
            onCancel={() => this.setState({ declarationModalVisible: false })}
          />
        )}
      </div>
    );
  }
}
