import React from "react";
import { inject, observer } from "mobx-react";
import { Button, DatePicker, Dropdown, Menu, message, Modal } from "antd";
import { WeaLocaleProvider, WeaNewScroll, WeaSelect, WeaTop } from "ecCom";
import { renderNoright } from "../../../util";
import Accountdialog from "./components/accountDialog";
import AbnormalDrawer from "./components/abnormalDrawer";
import moment from "moment";
import _ from "lodash";
import ProgressModal from "../../../components/progressModal";
import { getCalculateProgress } from "../../../apis/calculate";
import "./index.less";
import UnifiedTable from "../../../components/UnifiedTable";

const { getLabel } = WeaLocaleProvider;
const MonthPicker = DatePicker.MonthPicker;

@inject("standingBookStore", "taxAgentStore")
@observer
export default class StandingBook extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      selectedKey: "0",
      tableParams: {
        startTime: moment(new Date()).subtract(1, 'year').startOf("year").format("YYYY-MM"),
        endTime: moment(new Date()).endOf("year").format("YYYY-MM"),
        paymentOrganization: ""
      },
      current: 1,
      dialogProps: {
        title: "",
        visible: false,
        options: [],
        isAdmin: false
      },
      drawerProps: {
        title: "",
        visible: false
      },
      tableData: {
        list: [],
        columns: [],
        total: 0
      },
      dbnormalTableData: {
        list: [],
        total: 0
      },
      adminData: {
        isDefaultOpen: false,
        isAdminEnable: false,
        isChief: false,
        isOpenDevolution: false
      },
      progressVisible: false,
      progress: 0
    };
    this.payload = {};
    this.pageInfo = { current: 1, pageSize: 10 };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    const { current, dialogProps } = this.state;
    const {
      taxAgentStore: { getPermission, fetchTaxAgentOption },
      standingBookStore: { getAdminTaxAgentList }
    } = this.props;
    getPermission().then(({ status, data }) => {
      if (status) {
        this.setState({ adminData: data });
        if (data.isOpenDevolution) {
          getAdminTaxAgentList().then((data) => {
            let taxAgentList = data.map(item => {
              let result = {};
              result.showname = item.name;
              result.key = item.id + "";
              result.selected = false;
              return result;
            });
            this.setState({
              dialogProps: {
                ...dialogProps,
                options: taxAgentList,
                isAdmin: true
              }
            });
          });
        } else {
          fetchTaxAgentOption().then(({ data }) => {
            let taxAgentList = data.map(item => {
              let result = {};
              result.showname = item.content;
              result.key = item.id + "";
              result.selected = false;
              return result;
            });
            this.setState({
              dialogProps: {
                ...dialogProps,
                options: taxAgentList
              }
            });
          });
        }
        this.getCommonList({ ...this.state.tableParams, current });
      }
    });
  };

  getCommonList = (payload = {}) => {
    const { getCommonList } = this.props.standingBookStore;
    getCommonList({ ...payload }).then(({ list, columns, total, pageNum }) => {
      columns = _.map(columns, (it) => {
        if (it.dataIndex === "billMonth") {
          it = {
            ...it,
            render: (text, r) => {
              const { billMonth, creator } = r;
              return (
                <a
                  href="javascript:void(0);"
                  className="linkTo"
                  onClick={() => this.handleGoDetail(billMonth, "detail", r.paymentOrganizationId, creator)}>
                  {text}
                </a>
              );
            }
          };
        }
        return { ...it };
      });
      if (!this.state.adminData.isDefaultOpen || (this.state.adminData.isDefaultOpen && this.state.adminData.isAdminEnable)) {
        columns = [
          ...columns,
          {
            title: "操作",
            dataIndex: "operate",
            width: 150,
            key: "operate",
            render: (text, r) => {
              const { billStatus, billMonth, creator } = r;
              return (
                <React.Fragment>
                  {billStatus === "0" && (
                    <a
                      href="javascript:void(0);"
                      style={{ marginRight: 10 }}
                      onClick={() => this.handleGoDetail(billMonth, "", r.paymentOrganizationId, creator)}>
                      核算
                    </a>
                  )}
                  {billStatus === "0" && (
                    <a
                      href="javascript:void(0);"
                      style={{ marginRight: 10 }}
                      onClick={() => this.handleOperate({
                        key: "archive",
                        billMonth,
                        paymentOrganizationId: r.paymentOrganizationId,
                        creator
                      })}>
                      归档
                    </a>
                  )}
                  {billStatus === "1" && (
                    <a
                      href="javascript:void(0);"
                      style={{ marginRight: 10 }}
                      onClick={() => this.handleOperate({
                        key: "view",
                        billMonth,
                        paymentOrganizationId: r.paymentOrganizationId,
                        creator
                      })}>
                      查看
                    </a>
                  )}
                  {billStatus === "1" && (
                    <a
                      href="javascript:void(0);"
                      onClick={() => this.socialSecurityBenefitsRecalculate({ id: r.id })}>
                      重新核算
                    </a>
                  )}
                  {billStatus === "0" && (
                    <Dropdown
                      overlay={
                        <Menu
                          onClick={({ key }) =>
                            this.handleOperate({
                              key,
                              billMonth,
                              paymentOrganizationId: r.paymentOrganizationId,
                              creator
                            })
                          }>
                          <Menu.Item key="delete">删除</Menu.Item>
                        </Menu>
                      }>
                      <i className="icon-coms-more" style={{ marginLeft: 10 }}/>
                    </Dropdown>
                  )}
                </React.Fragment>
              );
            }
          }
        ];
      }
      this.setState({
        tableData: {
          list,
          columns,
          total
        },
        current: pageNum
      });
    });
  };

  socialSecurityBenefitsRecalculate = (params) => {
    const { socialSecurityBenefitsRecalculate } = this.props.standingBookStore;
    socialSecurityBenefitsRecalculate(params).then(() => {
      message.success("重新核算成功");
      this.init();
    }).catch(err => {
      message.error(err);
    });
  };

  // 异常详情列表
  inspectList = (payload) => {
    const { inspectList } = this.props.standingBookStore;
    this.payload = payload;
    inspectList({ ...payload }).then(({ list, total }) => {
      this.setState({
        dbnormalTableData: {
          list,
          total
        }
      });
    });
  };

  // 异常详情分页回调
  handlePageChange(value) {
    const { inspectList } = this.props.standingBookStore;
    inspectList({ ...this.payload, current: value }).then(({ list, total }) => {
      this.setState({
        dbnormalTableData: {
          list,
          total
        }
      });
    });
  }

  handleGoDetail = (billMonth, detail, paymentOrganization, creator) => {
    if (detail) {
      window.open(
        `/spa/hrmSalary/static/index.html#/main/hrmSalary/socialSecurityBenefits/standingBookDetail?type=${detail}&billMonth=${billMonth}&paymentOrganization=${paymentOrganization}&creator=${creator}`
      );
    } else {
      window.open(
        `/spa/hrmSalary/static/index.html#/main/hrmSalary/socialSecurityBenefits/standingBookDetail?billMonth=${billMonth}&paymentOrganization=${paymentOrganization}&creator=${creator}`
      );
    }
  };
  handleOperate = (payload) => {
    const { siaccountFile, siaccountDelete, deleteLoading } =
      this.props.standingBookStore;
    const { key, billMonth, paymentOrganizationId, creator } = payload;
    switch (key) {
      case "archive":
        Modal.confirm({
          title: "确认信息",
          content: "确认要归档吗？",
          onOk: () => {
            siaccountFile({ billMonth, paymentOrganization: paymentOrganizationId }).then((res) => {
              const { current } = this.state;
              this.getCommonList({ ...this.state.tableParams, current });
            });
          },
          onCancel: () => {
          }
        });
        break;
      case "detail":
        this.inspectList({ billMonth });
        this.setState({
          drawerProps: {
            ...this.state.drawerProps,
            title: "核算异常",
            visible: true
          }
        });
        break;
      case "delete":
        Modal.confirm({
          title: "确认信息",
          content: "确认删除本条数据吗？",
          confirmLoading: deleteLoading,
          onOk: () => {
            siaccountDelete({ billMonth, paymentOrganization: paymentOrganizationId }).then(() => {
              message.success("删除成功");
              this.getCommonList({
                ...this.state.tableParams,
                current: this.state.current
              });
            });
          },
          onCancel: () => {
          }
        });
        break;
      case "view":
        this.handleGoDetail(billMonth, "detail", paymentOrganizationId, creator);
        break;
      default:
        break;
    }
  };
  handleOk = async (formVal) => {
    const { save } = this.props.standingBookStore;
    const { billMonth, ...extra } = formVal;
    const payload = {
      billMonth: moment(billMonth).format("YYYY-MM"),
      ...extra
    };
    const { data: saveData } = await save(payload);
    this.setState({
      progressVisible: true
    }, () => {
      this.timer = setInterval(() => {
        getCalculateProgress(moment(billMonth).format("YYYY-MM")).then(({ status, data }) => {
          if (status) {
            if (!data.status) {
              clearInterval(this.timer);
              this.setState({
                progressVisible: false,
                progress: 0
              });
              message.error(data.message);
              return;
            }
            if (this.state.progress !== 100) {
              this.setState({
                progress: (Number(data.progress).toFixed(2)) * 100
              });
            } else {
              clearInterval(this.timer);
              this.setState({
                progressVisible: false,
                progress: 0
              }, () => {
                message.success("核算成功");
                this.handleClose();
                this.getCommonList({
                  ...this.state.tableParams,
                  current: this.state.current
                });
                this.handleGoDetail(moment(billMonth).format("YYYY-MM"), "", extra.paymentOrganization ? extra.paymentOrganization : "", saveData);
              });
            }
          } else {
            clearInterval(this.timer);
            this.setState({
              progressVisible: false,
              progress: 0
            });
          }
        }).catch(() => {
          clearInterval(this.timer);
          this.setState({
            progressVisible: false,
            progress: 0
          });
        });
      }, 600);
    });
  };

  handleClose = () => {
    this.setState({
      dialogProps: {
        ...this.state.dialogProps,
        title: "",
        visible: false
      }
    });
  };

  handleChangeMonth = (type, val) => {
    this.setState({
      tableParams: {
        ...this.state.tableParams,
        [type]: val && moment(val).format("YYYY-MM")
      }
    });
    this.getCommonList({
      ...this.state.tableParams,
      [type]: val && moment(val).format("YYYY-MM"),
      current: this.state.current
    });
  };

  handleShowSizeChange(pageInfo) {
    this.getCommonList({
      ...this.state.tableParams,
      ...pageInfo
    });
  }

  render() {
    const { standingBookStore, taxAgentStore: { showOperateBtn } } = this.props;
    const {
      inspectLoading,
      loading,
      hasRight,
      tableStore
    } = standingBookStore;
    const { list, columns, total } = this.state.tableData;
    const { startTime, endTime, paymentOrganization } = this.state.tableParams;
    const { dialogProps, drawerProps } = this.state;
    const abnormalColumns = _.map(
      _.filter(tableStore.columns, (it) => it.hide && it.hide === "false"),
      (item) => ({ ...item, width: item.oldWidth })
    );
    if (!hasRight && !loading) return renderNoright();
    const rightBtns = [
      // 右键菜单
      <Button
        type="primary"
        onClick={() => {
          this.setState({
            dialogProps: {
              ...this.state.dialogProps,
              title: "核算",
              visible: true
            }
          });
        }}>
        核算
      </Button>
    ];
    const pagination = {
      ...this.pageInfo,
      total: total,
      showTotal: (total) => `共 ${total} 条`,
      pageSizeOptions: ["10", "20", "50", "100"],
      showSizeChanger: true,
      showQuickJumper: true,
      onShowSizeChange: (current, pageSize) => {
        this.pageInfo = { ...this.pageInfo, current, pageSize };
        this.handleShowSizeChange(this.pageInfo);
      },
      onChange: (current) => {
        this.pageInfo = { ...this.pageInfo, current };
        this.handleShowSizeChange(this.pageInfo);
      }
    };

    return (
      <div className="standingbookWrapper">
        <WeaTop title="社保福利台账" icon={<i className="icon-coms-fa"/>}
                iconBgcolor="#F14A2D" buttons={showOperateBtn ? rightBtns : []}
        >
          <div className="filterWrapper">
            <div className="billDateWrapper">
              <div>账单月份：</div>
              <MonthPicker value={startTime} format="YYYY-MM"
                           disabledDate={current => (current && endTime && current.getTime() > new Date(endTime).getTime())}
                           onChange={(val) => this.handleChangeMonth("startTime", val)}
              />
              <span className="to">至</span>
              <MonthPicker value={endTime} format="YYYY-MM"
                           disabledDate={current => (current && startTime && current.getTime() < new Date(startTime).getTime())}
                           onChange={(val) => this.handleChangeMonth("endTime", val)}
              />
            </div>
            <div className="billDateWrapper">
              <span className="to">{getLabel(537996, "个税扣缴义务人")}：</span>
              <WeaSelect value={paymentOrganization} options={dialogProps.options} style={{ width: 200 }}
                         onChange={val => this.setState({
                           tableParams: { ...this.state.tableParams, paymentOrganization: val }
                         }, () => {
                           this.getCommonList({ ...this.state.tableParams, ...this.pageInfo });
                         })}
              />
            </div>
          </div>
          <div className="tableWrapper">
            <WeaNewScroll height="100%">
              <UnifiedTable
                loading={loading}
                columns={_.filter(columns, (it) => it.dataIndex !== "id").map(item => {
                  if (item.dataIndex !== "operate" && item.dataIndex !== "billStatus") {
                    return {
                      ...item,
                      width: 150,
                      render: (text) => {
                        return <span className="ellipsis" title={text}>{text}</span>;
                      }
                    };
                  }
                  if (item.dataIndex === "billStatus") {
                    return {
                      ...item,
                      render: (_, record) => {
                        return <span
                          className="ellipsis">{record.billStatus === "1" ? getLabel(18800, "已归档") : getLabel(17999, "未归档")}</span>;
                      }
                    };
                  }
                  return { ...item };
                })}
                dataSource={list}
                pagination={pagination}
                xWidth={columns.length * 120}
              />
            </WeaNewScroll>
          </div>
          <Accountdialog {...dialogProps} onCancel={() => this.handleClose()} onOk={this.handleOk} loading={loading}/>
          {/*核算进度条*/}
          {
            this.state.progressVisible &&
            <ProgressModal
              visible={this.state.progressVisible}
              onCancel={() => {
                this.setState({ progressVisible: false, progress: 0 });
              }}
              progress={this.state.progress}
            />
          }
          {drawerProps.visible && (
            <AbnormalDrawer
              {...drawerProps}
              onClose={() => {
                this.setState({
                  drawerProps: {
                    ...this.state.drawerProps,
                    title: "",
                    visible: false
                  }
                });
              }}
              columns={abnormalColumns}
              dataSource={this.state.dbnormalTableData.list}
              total={this.state.dbnormalTableData.total}
              onPageChange={(value) => {
                this.handlePageChange(value);
              }}
              // onOk={this.handleOk}
              loading={inspectLoading}
            />
          )}
        </WeaTop>
      </div>
    );
  }
}
