/*
 * Author: 黎永顺
 * name: 人员信息报送-查看详情
 * Description:
 * Date: 2023/8/11
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import { WeaDatePicker, WeaLocaleProvider, WeaSelect, WeaTab, WeaTop } from "ecCom";
import { Button, Dropdown, Menu, message, Modal, Spin } from "antd";
import BaseInfo from "./components/baseInfo";
import EmployeeDeclareDetailSchemaEditDialog from "./components/employeeDeclareDetailSchemaEditDialog";
import EmployeeDeclareDetailSchemaImportDialog from "./components/employeeDeclareDetailImportDialog";
import DeductionListConfirmDialog from "./components/deductionListConfirmDialog";
import { commonEnumList } from "../../apis/payrollFiles";
import {
  employeedeclareDeclare,
  employeedeclareExport,
  employeedeclareGetRate,
  employeedeclareList,
  employeedeclareList4Add,
  employeedeclareList4Update,
  employeedeclareRefresh,
  employeeDelete,
  employeeInvalid,
  getDeclareFeedback
} from "../../apis/declare";
import { advanceConditions, submitStatus } from "./constants";
import moment from "moment";
import { getSearchs } from "../../util";
import { getQueryString } from "../../util/url";
import "./index.less";

const { getLabel } = WeaLocaleProvider;
const API = {
  list: employeedeclareList,
  list4Add: employeedeclareList4Add,
  list4Update: employeedeclareList4Update
};

@inject("taxAgentStore", "employeeDeclareStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "list", showSearchAd: false, declareStatus: "ALL",
      taxCycle: new Date(), pageInfo: { current: 1, pageSize: 10, total: 0 },
      loading: { query: false, refresh: false, feedback: false, declare: false, exportLoading: false },
      declareEditDialog: { visible: false, id: "", title: "" },
      confirmationDialog: { visible: false, payload: {} },
      declareStatusList: [], employmentStatusList: [],
      employmentTypeList: [], adConditons: [],
      selectedRowKeys: [], exportPayload: {}
    };
    this.baseInfoRef = null;
    this.importRef = null;
    this.timer = null;
  }

  componentDidMount() {
    document.title = getLabel(544289, "人员信息报送");
    window.addEventListener("message", this.handleReceive, false);
    this.initEmployeeDeclare().then(r => {
    });
  }

  initEmployeeDeclare = async () => {
    const { employeeDeclareStore: { advanceForm } } = this.props;
    const [declareStatusList, employmentStatusList, employmentTypeList] = await Promise.all([this.commonEnumList("DeclareStatusEnum"), this.commonEnumList("EmploymentStatusEnum"), this.commonEnumList("EmploymentTypeEnum")]);
    if (declareStatusList.status && employmentStatusList.status && employmentTypeList.status) {
      this.setState({
        declareStatusList: declareStatusList.data,
        employmentStatusList: employmentStatusList.data,
        employmentTypeList: employmentTypeList.data,
        adConditons: _.map(advanceConditions, it => {
          return {
            ...it,
            items: _.map(it.items, child => {
              if (child.domkey[0] === "employmentStatus") {
                return {
                  ...child,
                  options: _.map(employmentStatusList.data, it => ({
                    key: it.enum,
                    showname: getLabel(it.labelId, it.defaultLabel)
                  }))
                };
              } else if (child.domkey[0] === "employmentType") {
                return {
                  ...child,
                  options: _.map(employmentTypeList.data, it => ({
                    key: it.enum,
                    showname: getLabel(it.labelId, it.defaultLabel)
                  }))
                };
              }
              if (child.conditionType === "SELECT" && child.domkey[0] !== "employmentStatus" && child.domkey[0] !== "employmentType") {
                return {
                  ...child,
                  options: [
                    { key: "ON", showname: getLabel(538048, "是") },
                    { key: "OFF", showname: getLabel(111, "否") }
                  ]
                };
              }
              return { ...child };
            })
          };
        })
      }, () => {
        advanceForm.initFormFields(this.state.adConditons);
      });
    }
  };

  componentWillUnmount() {
    this.setState({ exportPayload: {} });
    window.removeEventListener("message", this.handleReceive, false);
  }

  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.queryEmployeeList();
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = params;
        this.setState({ pageInfo: { ...this.state.pageInfo, current, pageSize } }, () => this.queryEmployeeList());
      } else if (id === "EDIT") {
        this.setState({
          declareEditDialog: {
            ...this.state.declareEditDialog,
            visible: true, id: params.id, title: params.employeeName
          }
        });
      } else if (id === "DELETE") {
        this.handleDeleteDeclare([params.id]);
      } else if (id === "VOID") {
        this.handleVoidDeclare(params.id);
      } else if (id === "ROWSELECT") {
        const { selectedRowKeys } = params;
        this.setState({ selectedRowKeys });
      }
    }
  };
  postMessageToChild = (payload = {}) => {
    const i18n = {
      "总计": getLabel(523, "总计"), "编辑": getLabel(501169, "编辑"),
      "操作": getLabel(30585, "操作"), "删除": getLabel(535052, "删除"),
      "共": getLabel(83698, "共"), "条": getLabel(18256, "条"),
      "加载中": getLabel(83698, "加载中")
      // "作废": getLabel(111, "作废")
    };
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  commonEnumList = (key) => {
    const payload = { enumClass: `com.engine.salary.enums.employeedeclare.${key}` };
    return commonEnumList(payload);
  };
  /*
   * Author: 黎永顺
   * Description: 报送列表查询
   * Params:
   * Date: 2023/8/14
   */
  queryEmployeeList = () => {
    const { employeeDeclareStore: { advanceForm: form } } = this.props;
    const { pageInfo, declareStatus, taxCycle, selectedKey, selectedRowKeys, confirmationDialog } = this.state;
    const { departmentIds, positionIds, ...formParams } = form.getFormParams();
    const payload = {
      ...formParams, ...pageInfo,
      declareStatus,
      taxAgentId: getQueryString("id"),
      taxCycle: moment(taxCycle).startOf("month").format("YYYY-MM-DD"),
      departmentIds: departmentIds ? departmentIds.split(",") : [],
      positionIds: positionIds ? positionIds.split(",") : []
    };
    this.setState({ exportPayload: payload, loading: { ...this.state.loading, query: true } });
    API[selectedKey](payload).then(({ status, data }) => {
      this.setState({ loading: { ...this.state.loading, query: false } });
      if (status) {
        const { pageInfo: result } = data;
        const { columns, list: dataSource, pageNum: current, pageSize, total } = result;
        this.baseInfoRef.getEmployeeDeclareInfo();
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total },
          confirmationDialog: { ...confirmationDialog, payload }
        }, () => {
          const payload = {
            dataSource, selectedRowKeys, selectedKey,
            pageInfo: this.state.pageInfo,
            columns: _.map(columns, it => {
              if (it.dataIndex === "employeeName" || it.dataIndex === "subCompanyName") {
                return { ...it, width: 150, fixed: "left" };
              }
              if (it.dataIndex === "declareStatusDesc") {
                return { ...it, width: 150, fixed: "right" };
              }
              return { ...it, width: 150 };
            })
          };
          this.postMessageToChild(payload);
        });
      }
    }).then(() => this.setState({ loading: { ...this.state.loading, query: false } }));
  };
  /*
   * Author: 黎永顺
   * Description: 刷新数据
   * Params:
   * Date: 2023/8/14
   */
  employeedeclareRefresh = () => {
    const payload = {
      taxAgentId: getQueryString("id"),
      taxCycle: moment(this.state.taxCycle).startOf("month").format("YYYY-MM-DD")
    };
    this.setState({ loading: { ...this.state.loading, refresh: true } });
    employeedeclareRefresh(payload).then(async ({ status, data, errormsg }) => {
      if (status) {
        message.destroy();
        message.loading(getLabel(111, "刷新中..."), 0);
        this.timer = setInterval(async () => {
          const { status: resStatus, data: result } = await employeedeclareGetRate({ index: data });
          const { status: rateStatus, finish, msg } = result;
          if (resStatus && rateStatus) {
            if (finish) {
              this.setState({ loading: { ...this.state.loading, refresh: false } });
              clearInterval(this.timer);
              message.destroy();
              message.success(getLabel(111, "刷新成功！"));
              this.queryEmployeeList();
            }
          } else {
            this.setState({ loading: { ...this.state.loading, refresh: false } });
            clearInterval(this.timer);
            message.destroy();
            message.warning(msg || getLabel(111, "刷新失败！"));
            this.queryEmployeeList();
          }
        }, 1000);
      } else {
        this.setState({ loading: { ...this.state.loading, refresh: false } });
        clearInterval(this.timer);
        message.destroy();
        message.error(errormsg);
      }
    }).catch(() => {
      clearInterval(this.timer);
      message.destroy();
      this.setState({ loading: { ...this.state.loading, refresh: false } });
    });
  };
  /*
   * Author: 黎永顺
   * Description:获取报送结果反馈
   * Params:
   * Date: 2023/8/15
   */
  getDeclareFeedback = () => {
    const payload = {
      taxAgentId: getQueryString("id"),
      taxCycle: moment(this.state.taxCycle).startOf("month").format("YYYY-MM-DD")
    };
    this.setState({ loading: { ...this.state.loading, feedback: true } });
    getDeclareFeedback(payload).then(async ({ status, data, errormsg }) => {
      if (status) {
        message.destroy();
        message.loading(getLabel(111, "获取报送中..."), 0);
        this.timer = setInterval(async () => {
          const { status: resStatus, data: result } = await employeedeclareGetRate({ index: data });
          const { status: rateStatus, finish, msg } = result;
          if (resStatus && rateStatus) {
            if (finish) {
              this.setState({ loading: { ...this.state.loading, feedback: false } });
              clearInterval(this.timer);
              message.destroy();
              message.success(getLabel(111, "获取报送结果成功！"));
              this.queryEmployeeList();
            }
          } else {
            this.setState({ loading: { ...this.state.loading, feedback: false } });
            clearInterval(this.timer);
            message.destroy();
            message.warning(msg || getLabel(111, "获取失败！"));
            this.queryEmployeeList();
          }
        }, 1000);
      } else {
        this.setState({ loading: { ...this.state.loading, feedback: false } });
        clearInterval(this.timer);
        message.destroy();
        message.error(errormsg);
      }
    }).catch(() => {
      clearInterval(this.timer);
      message.destroy();
      this.setState({ loading: { ...this.state.loading, feedback: false } });
    });
  };
  /*
   * Author: 黎永顺
   * Description:作废个税申报人员信息
   * Params:
   * Date: 2024/4/16
   */
  handleVoidDeclare = (id) => {
    const { selectedRowKeys } = this.state;
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(111, "确认作废吗？"),
      onOk: () => {
        employeeInvalid({ id }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(111, "作废成功！"));
            this.queryEmployeeList();
          } else {
            message.error(errormsg || getLabel(111, "作废失败！"));
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 删除个税申报人员信息
   * Params:
   * Date: 2023/8/15
   */
  handleDeleteDeclare = (paylaod) => {
    const { selectedRowKeys } = this.state;
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(543548, "确认删除吗？"),
      onOk: () => {
        employeeDelete(paylaod).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(502230, "删除成功！"));
            this.setState({
              selectedRowKeys: _.xorWith(selectedRowKeys, paylaod, _.isEqual)
            });
            this.queryEmployeeList();
          } else {
            message.error(errormsg || getLabel(20462, "删除失败！"));
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 全部报送
   * Params:
   * Date: 2023/8/15
   */
  employeedeclareDeclare = () => {
    const payload = {
      taxAgentId: getQueryString("id"),
      taxCycle: moment(this.state.taxCycle).startOf("month").format("YYYY-MM-DD")
    };
    this.setState({ loading: { ...this.state.loading, declare: true } });
    employeedeclareDeclare(payload).then(async ({ status, data, errormsg }) => {
      if (status) {
        message.destroy();
        message.loading(getLabel(111, "报送中..."), 0);
        this.timer = setInterval(async () => {
          const { status: resStatus, data: result } = await employeedeclareGetRate({ index: data });
          const { status: rateStatus, finish, msg } = result;
          if (resStatus && rateStatus) {
            if (finish) {
              this.setState({ loading: { ...this.state.loading, declare: false } });
              clearInterval(this.timer);
              message.destroy();
              message.success(getLabel(111, "全部报送成功！"));
              this.queryEmployeeList();
            }
          } else {
            this.setState({ loading: { ...this.state.loading, declare: false } });
            clearInterval(this.timer);
            message.destroy();
            message.warning(msg || getLabel(111, "报送失败！"));
            this.queryEmployeeList();
          }
        }, 1000);
      } else {
        this.setState({ loading: { ...this.state.loading, declare: false } });
        clearInterval(this.timer);
        message.destroy();
        message.error(errormsg);
      }
    }).catch(() => {
      clearInterval(this.timer);
      message.destroy();
      this.setState({ loading: { ...this.state.loading, declare: false } });
    });
  };
  handleAdd = () => {
    this.setState({
      declareEditDialog: {
        ...this.state.declareEditDialog,
        visible: true
      }
    });
  };
  handleMenuClick = ({ key }) => {
    const { selectedRowKeys, confirmationDialog } = this.state;
    switch (key) {
      case "1":
        if (_.isEmpty(selectedRowKeys)) {
          message.warning(getLabel(111, "请先选择需要删除的人员！"));
          return;
        }
        this.handleDeleteDeclare(selectedRowKeys);
        break;
      case"5":
        this.setState({ confirmationDialog: { ...confirmationDialog, visible: true } });
        break;
      default:
        break;
    }
  };
  handleEmployeedeclareExport = async ({ key }) => {
    const { selectedRowKeys, exportPayload } = this.state;
    if (key === "selected" && _.isEmpty(selectedRowKeys)) {
      message.warning(getLabel(111, "请先选择需要导出的人员！"));
      return;
    }
    this.setState({ loading: { ...this.state.loading, exportLoading: true } });
    const promise = await employeedeclareExport(_.omit({
      ...exportPayload,
      ids: selectedRowKeys
    }, ["current", "total", "pageSize"]));
    this.setState({ loading: { ...this.state.loading, exportLoading: false } });
  };
  handleEmployeedeclare = ({ key }) => {
    switch (key) {
      case "import":
        const tmplateExpPayload = {
          exportData: "false", taxAgentId: getQueryString("id"),
          taxCycle: moment(this.state.taxCycle).startOf("month").format("YYYY-MM-DD")
        };
        this.importRef.handleImportEmployeeDeclare(tmplateExpPayload);
        break;
      default:
        break;
    }
  };

  render() {
    const {
      selectedKey, showSearchAd, declareStatus, declareStatusList, taxCycle, declareEditDialog, loading,
      pageInfo, adConditons, employmentTypeList, employmentStatusList, confirmationDialog
    } = this.state;
    const { taxAgentStore: { showOperateBtn }, employeeDeclareStore: { advanceForm: form, declareForm } } = this.props;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1">{getLabel(32136, "批量删除")}</Menu.Item>
        {/*<Menu.Item key="2">{getLabel(111, "批量编辑")}</Menu.Item>*/}
        {/*<Menu.Item key="3">{getLabel(81272, "导出全部")}</Menu.Item>*/}
        {/*<Menu.Item key="4">{getLabel(543715, "导出所选")}</Menu.Item>*/}
        <Menu.Item key="5">{getLabel(111, "扣除名单确认")}</Menu.Item>
      </Menu>
    );
    const buttons = [
      <div className="taxPeriod-div">
        <span className="title">{getLabel(542240, "税款所属期")}：</span>
        <WeaDatePicker arrow type="month" className="pickerDateCustom flex a-center" value={taxCycle}
                       onChange={val => this.setState({
                         taxCycle: val, pageInfo: { ...pageInfo, current: 1 },
                         selectedRowKeys: []
                       }, () => this.queryEmployeeList())}/>
      </div>,
      <Button type="primary" onClick={this.employeedeclareDeclare}
              loading={loading.declare}>{getLabel(111, "全部报送")}</Button>,
      <Button type="ghost" onClick={this.getDeclareFeedback}
              loading={loading.feedback}>{getLabel(111, "获取报送结果")}</Button>,
      <Button type="ghost" onClick={this.employeedeclareRefresh}
              loading={loading.refresh}>{getLabel(111, "刷新数据")}</Button>,
      <Dropdown overlay={menu}>
        <Button type="ghost" icon="ellipsis" className="moreBtn"/>
      </Dropdown>,
      <DeductionListConfirmDialog {...confirmationDialog} year={moment(taxCycle).format("YYYY")}
                                  onCancel={() => this.setState({
                                    confirmationDialog: { ...confirmationDialog, visible: false }
                                  })}/>
    ];
    const topTab = [
      { title: getLabel(332, "全部"), viewcondition: "list" },
      { title: getLabel(111, "本月新增"), viewcondition: "list4Add" },
      { title: getLabel(111, "本月信息变动"), viewcondition: "list4Update" }
    ];
    const tabBtns = [
      <Dropdown.Button
        onClick={this.handleAdd}
        overlay={
          <Menu onClick={this.handleEmployeedeclare}>
            <Menu.Item key="import">{getLabel(32935, "导入")}</Menu.Item>
          </Menu>
        }
        type="primary">{getLabel(1421, "新增")}</Dropdown.Button>,
      <Dropdown.Button
        onClick={() => this.handleEmployeedeclareExport({ key: "all" })}
        loading={loading.exportLoading}
        overlay={
          <Menu onClick={this.handleEmployeedeclareExport}>
            <Menu.Item key="selected">{getLabel(543715, "导出所选")}</Menu.Item>
          </Menu>
        }
        type="primary">{getLabel(17416, "导出全部")}</Dropdown.Button>,
      // <Button type="ghost" onClick={this.handleEmployeedeclareExport}
      //         loading={loading.exportLoading}>{getLabel(17416, "导出")}</Button>,
      <WeaSelect
        value={declareStatus}
        style={{ width: 150 }}
        options={[
          ..._.map(submitStatus, it => ({ ...it, showname: getLabel(it.lanId, it.showname) })),
          ..._.map(declareStatusList, it => ({
            key: it.enum,
            showname: getLabel(it.labelId, it.defaultLabel)
          }))
        ]}
        onChange={declareStatus => this.setState({
          declareStatus,
          pageInfo: {
            ...pageInfo,
            current: 1
          }
        }, () => this.queryEmployeeList())}
      />
    ];
    // !showOperateBtn && tabBtns.shift();
    selectedKey !== "list" && tabBtns.shift();
    selectedKey !== "list" && tabBtns.shift();
    return (
      <WeaTop
        title={getLabel(544289, "人员信息报送")} iconBgcolor="#F14A2D"
        icon={<i className="icon-coms-fa"/>} className="declareWrapper"
        buttons={buttons}
        // buttons={showOperateBtn ? buttons : []}
      >
        <div style={{ height: "100%", background: "#f6f6f6" }} className="flex flex-rollback">
          {/*基础信息*/}
          <BaseInfo
            ref={dom => this.baseInfoRef = dom}
            taxCycle={moment(taxCycle).startOf("month").format("YYYY-MM-DD")}
          />
          {/*列表数据*/}
          <div className="listview-com-layout flex-1 flex flex-rollback">
            <WeaTab
              datas={topTab} keyParam="viewcondition" showSearchAd={showSearchAd}
              selectedKey={selectedKey} searchType={["base", "advanced"]}
              setShowSearchAd={bool => this.setState({ showSearchAd: bool })}
              advanceHeight={300} searchsAd={getSearchs(form, toJS(adConditons), 2)}
              buttons={tabBtns} searchsBaseValue={form.getFormParams().keyword}
              onSearchChange={(v) => form.updateFields({ keyword: v })}
              onChange={key => this.setState({
                selectedKey: key,
                pageInfo: { ...pageInfo, current: 1 }
              }, () => this.queryEmployeeList())}
              onAdReset={() => form.resetForm()}
              onSearch={() => this.setState({
                pageInfo: { ...pageInfo, current: 1 }
              }, () => this.queryEmployeeList())}
              onAdSearch={() => this.setState({
                pageInfo: {
                  ...pageInfo,
                  current: 1
                }
              }, () => this.queryEmployeeList())}
            />
            <div className="flex-1">
              <Spin spinning={loading.query}>
                <iframe
                  style={{ border: 0, width: "100%", height: "100%" }}
                  // src="http://localhost:7607/#/employeeDeclareTable"
                  src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/employeeDeclareTable"
                  id="atdTable"
                />
              </Spin>
              {/*新增编辑报送信息*/}
              <EmployeeDeclareDetailSchemaEditDialog
                {...declareEditDialog}
                taxCycle={moment(taxCycle).startOf("month").format("YYYY-MM-DD")}
                employmentStatusList={employmentStatusList}
                employmentTypeList={employmentTypeList}
                onClose={(isFresh) => {
                  this.setState({
                    declareEditDialog: {
                      ...declareEditDialog,
                      visible: false, id: "", title: ""
                    }
                  }, () => {
                    declareForm.resetForm();
                    isFresh === "true" && this.queryEmployeeList();
                  });
                }}
              />
              {/*人员信息报送导入*/}
              <EmployeeDeclareDetailSchemaImportDialog ref={dom => this.importRef = dom}
                                                       onSuccess={this.queryEmployeeList}/>
            </div>
          </div>
        </div>
      </WeaTop>
    );
  }
}

export default Index;