import React from "react";
import { inject, observer } from "mobx-react";
import { Button, DatePicker, message, Modal, Tag } from "antd";
import { WeaLocaleProvider, WeaNewScroll, WeaTop } from "ecCom";
import CustomTab from "../../components/customTab";
import CustomTable from "../../components/customTable";
import GenerateModal from "./generateModal";
import { getDeclareList, taxdeclarationDelete, taxdeclarationUpdateIcon } 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" });
    });
  };
  taxdeclarationDelete = (taxDeclarationId) => {
    taxdeclarationDelete([taxDeclarationId]).then(({ status, errormsg }) => {
      if (status) {
        message.success(getLabel(502230, "删除成功"));
        this.getDeclareList();
      } else {
        message.error(errormsg || getLabel(20462, "删除失败"));
      }
    });
  };
  // 日期区间改变事件
  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());
  };
  handleUpdateicon = (record) => {
    const { id: taxDeclareRecordId } = record;
    taxdeclarationUpdateIcon({ taxDeclareRecordId }).then(({ status, errormsg }) => {
      this.getDeclareList();
      if (status) {
        message.success(getLabel(502230, "删除成功！"));
      } else {
        message.error(errormsg || getLabel(20462, "删除失败！"));
      }
    });
  };

  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 });
              }}>
              {getLabel(111, "生成申报表")}
            </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={[
                  ..._.map(columns, it => {
                    if (it.dataIndex === "taxDeclareStatusDesc") {
                      return {
                        ...it,
                        render: (text, record) => {
                          return (<div className="declare-status-box">
                            {text}
                            {
                              record.displayIcon &&
                              <span title={getLabel(111, "该个税申报表对应的核算数据被重新核算")} className="icon-span">
                                <Tag closable onClose={() => this.handleUpdateicon(record)}>
                                  <i className="icon-coms02-Warning-01"/>
                                </Tag>
                              </span>
                            }
                          </div>);
                        }
                      };
                    }
                    return { ...it };
                  }),
                  {
                    title: "操作",
                    dataIndex: "operate",
                    render: (text, record) => {
                      return (
                        <React.Fragment>
                          <a
                            href={`${window.ecologyContentPath || ""}/spa/hrmSalary/static/index.html#/main/hrmSalary/declareDetail?id=${record.id}`}
                            target="_blank"
                          >
                            {getLabel(83110, "查看详情")}
                          </a>
                          {
                            showWithDrawBtn &&
                            <a
                              href="javascript:void(0);" style={{ marginLeft: 10 }}
                              onClick={() => {
                                Modal.confirm({
                                  title: getLabel(131329, "信息确认"),
                                  content: getLabel(388758, "确认要删除吗?"),
                                  onOk: () => this.taxdeclarationDelete(record.id)
                                });
                              }}
                            >
                              {getLabel(535052, "删除")}
                            </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>
    );
  }
}
