import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import {
  WeaDatePicker,
  WeaFormItem,
  WeaHelpfulTip,
  WeaInput,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaSelect,
  WeaTools
} from "ecCom";
import { Button, Dropdown, Menu, message, Modal } from "antd";
import {
  autoAddAll,
  createAddUpDeduction,
  deleteAllAddUpDeduction,
  deleteSelectAddUpDeduction,
  editAddUpDeduction,
  getAddUpDeduction,
  getCumDeductSaCondition,
  importCumDeductParam
} from "../../../apis/cumDeduct";
import DataTables from "../dataTables";
import AddItems from "../addItems";
import ImportFormCom from "./components/importFormCom";
import TableRecord from "../components/tableRecord";
import { dataCollectCondition } from "./columns";
import { removePropertyCondition } from "../../../util/response";
import { convertToUrlString } from "../../../util/url";
import { getDomkes } from "../../../util";
import Layout from "../layout";
import moment from "moment";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject("taxAgentStore", "cumDeductStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      declareMonth: moment(new Date()).format("YYYY-MM"),
      taxAgentId: "",
      innerWidth: window.innerWidth,
      addAllLoading: false,
      saveLoading: false,
      slidePayload: {
        visible: false,
        title: "",
        children: null,
        data: {}
      },
      importPayload: {
        visible: false,
        importOpts: {
          declareMonth: moment(new Date()).format("YYYY-MM"),
          taxAgentId: ""
        },
        importFormComponent: null,
        templateLink: "/api/bs/hrmsalary/addUpDeduction/downloadTemplate",
        importResult: {},
        previewUrl: "/api/bs/hrmsalary/addUpDeduction/preview"
      },
      exportPayloadUrl: "",
      exportPayloadType: false,
      advanceCondition: null,
      targetid: ""
    };
    this.tableRef = null;
    this.addItemRef = null;
    this.tableRecordRef = null;
  }

  componentDidMount() {
    this.getAdvanceCondition();
  }

  /*
   * Author: 黎永顺
   * Description:一键累计
   * Params:
   * Date: 2023/2/17
   */
  autoAddAll = () => {
    const { declareMonth, taxAgentId } = this.state;
    this.setState({ addAllLoading: true });
    autoAddAll({ yearMonth: declareMonth, taxAgentIds: taxAgentId ? taxAgentId.split(",") : [] })
      .then(({ status, data, errormsg }) => {
        this.setState({ addAllLoading: false });
        if (status) {
          message.success(data || "操作成功");
          this.tableRef.getTableDate();
        } else {
          message.error(errormsg || "操作失败");
        }
      }).catch(() => this.setState({ addAllLoading: false }));
  };
  /*
   * Author: 黎永顺
   * Description: 高级搜素框-表单项
   * Params:
   * Date: 2023/2/20
   */
  getAdvanceCondition = () => {
    const { cumDeductStore: { form } } = this.props;
    getCumDeductSaCondition().then(({ status, data }) => {
      if (status) {
        this.setState({ advanceCondition: removePropertyCondition(data.condition) });
        form.initFormFields(removePropertyCondition(data.condition));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 一键清空
   * Params:
   * Date: 2023/2/20
   */
  deleteAllAddUpDeduction = () => {
    const { declareMonth, taxAgentId } = this.state;
    const payload = { declareMonth, taxAgentId };
    Modal.confirm({
      title: "信息确认",
      content: `确定清空税款所属期为${declareMonth}的所有累计专项附加扣除数据吗?若数据已参与核算，已参与核算的数据不会受影响，点击核算将会按当前列表最新数据重新核算。`,
      onOk: () => {
        deleteAllAddUpDeduction(payload).then(({ status, errormsg }) => {
          if (status) {
            message.success("删除成功");
            this.tableRef.getTableDate();
          } else {
            message.error(errormsg || "删除失败");
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 删除所选
   * Params:
   * Date: 2023/2/20
   */
  deleteSelectAddUpDeduction = (record = {}) => {
    const { declareMonth } = this.state;
    const { selectedRowKeys: ids } = this.tableRef.state;
    const { id, departmentName, username } = record;
    if (ids.length === 0 && !id) {
      message.warning("请选择表格数据");
      return;
    }
    const payload = { declareMonth, ids: !id ? ids : [id] };
    Modal.confirm({
      title: "信息确认",
      content: !id ? "确定删除所选数据吗?若数据已参与核算，已参与核算的数据不会受影响，点击核算将会按当前列表最新数据重新核算。" :
        `确定删除${departmentName}${username}（税款所属期:${declareMonth}）的累计专项附加扣除数据吗?若数据已参与核算，已参与核算的数据不会受影响，点击核算将会按当前列表最新数据重新核算。`,
      onOk: () => {
        deleteSelectAddUpDeduction(payload).then(({ status, errormsg }) => {
          if (status) {
            message.success("删除成功");
            this.tableRef.getTableDate();
            this.tableRef.handleClearRows();
          } else {
            message.error(errormsg || "删除失败");
          }
        });
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:数据采集-导出全部
   * Params:
   * Date: 2023/2/20
   */
  handleExportAll = () => {
    const { cumDeductStore: { form } } = this.props;
    const { declareMonth, taxAgentId, exportPayloadType } = this.state;
    this.setState({
      exportPayloadType: !exportPayloadType,
      exportPayloadUrl: `${window.location.origin}/api/bs/hrmsalary/addUpDeduction/export?ids=&declareMonth=${declareMonth}&taxAgentId=${taxAgentId}&${convertToUrlString(form.getFormParams())}`
    });
  };
  /*
   * Author: 黎永顺
   * Description:数据采集-导出选中
   * Params:
   * Date: 2023/2/20
   */
  handleExportSelect = () => {
    const { selectedRowKeys: ids } = this.tableRef.state;
    const { declareMonth, taxAgentId, exportPayloadType } = this.state;
    if (ids.length === 0) {
      message.warning("请选择需要导出的数据");
      return;
    }
    this.setState({
      exportPayloadType: !exportPayloadType,
      exportPayloadUrl: `${window.location.origin}/api/bs/hrmsalary/addUpDeduction/export?ids=${ids.join(",")}&declareMonth=${declareMonth}&taxAgentId=${taxAgentId}`
    });
  };
  /*
   * Author: 黎永顺
   * Description: 数据采集-信息保存
   * Params:
   * Date: 2023/2/20
   */
  handleSaveDeduction = (payload) => {
    const { slidePayload } = this.state;
    const { data } = slidePayload;
    const { id } = data;
    this.setState({ saveLoading: true });
    if (!_.isEmpty(data)) {
      editAddUpDeduction({ ...payload, id }).then(({ status, errormsg }) => {
        this.setState({ saveLoading: false });
        if (status) {
          message.success("编辑成功");
          this.handleCloseSlide();
          this.tableRef.getTableDate();
        } else {
          message.error(errormsg || "编辑失败");
        }
      });
    } else {
      createAddUpDeduction(payload).then(({ status, errormsg }) => {
        this.setState({ saveLoading: false });
        if (status) {
          message.success("新增成功");
          this.handleCloseSlide();
          this.tableRef.getTableDate();
        } else {
          message.error(errormsg || "新增失败");
        }
      });
    }
  };
  handleSaveData = () => {
    const { cumDeductStore: { addForm }, taxAgentStore: { taxAgentOption } } = this.props;
    addForm.validateForm().then(f => {
      if (f.isValid) {
        const payload = {
          ..._.reduce(getDomkes(dataCollectCondition), (pre, cur) => ({ ...pre, [cur]: "" }), {}),
          ...addForm.getFormParams(),
          taxAgentName: _.find(taxAgentOption, it => it.key === addForm.getFormParams().taxAgentId).showname
        };
        this.handleSaveDeduction(payload);
      } else {
        Modal.warning({
          title: "信息确认",
          content: "必要信息不完整，红色*为必填项！"
        });
      }
    });
  };
  handleResize = (innerWidth) => this.setState({ innerWidth });
  /*
   * Author: 黎永顺
   * Description:新增数据采集-累计专项附加扣除
   * Params: screenParams规则：日期必须放在数组最后一位，人员信息必须第一位
   * Date: 2023/2/20
   */
  handleAddData = (title = "新建", editId = {}) => {
    const { taxAgentStore, cumDeductStore: { addForm } } = this.props;
    const { slidePayload } = this.state;
    const { taxAgentOption } = taxAgentStore;
    const conditions = _.map(dataCollectCondition, (it, idx) => {
      if (idx === 0) {
        return {
          ...it, title: getLabel(82743, "基础信息"),
          items: _.map(it.items, o => {
            if (getKey(o) === "taxAgentId") {
              return {
                ...o, label: getLabel(o.lanId, o.label),
                options: taxAgentOption, viewAttr: _.isEmpty(editId) ? 3 : 1
              };
            }
            return {
              ...o, label: getLabel(o.lanId, o.label), viewAttr: _.isEmpty(editId) ? 3 : 1
            };
          })
        };
      } else if (idx === 1) {
        return {
          ...it, title: getLabel(83871, "数据采集"),
          items: _.map(it.items, o => ({
            ...o, label: getLabel(o.lanId, o.label)
          }))
        };
      }
    });
    addForm.initFormFields(conditions);
    this.setState({
      slidePayload: {
        ...slidePayload,
        visible: true,
        title,
        data: editId,
        children: title.length <= 2 ?
          <AddItems
            ref={(dom) => this.addItemRef = dom}
            taxAgentOption={taxAgentOption}
            form={addForm}
            editId={editId}
            condition={conditions}
          /> :
          <TableRecord
            ref={(dom) => this.tableRecordRef = dom}
            className="accumulated"
            taxAgentOption={taxAgentOption}
            url="/api/bs/hrmsalary/addUpDeduction/getDetailList"
            record={editId}
            screenParams={["accumulatedSpecialAdditionalDeductionId", "taxAgentId", "declareMonth"]}
          />
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description:列表操作
   * Params:
   * Date: 2023/2/20
   */
  handleTableOperate = ({ key }, record) => {
    const { id } = record;
    key === "handleAddData" ? getAddUpDeduction({ id }).then(({ status, data }) => {
      if (status) this[key]("编辑", data);
    }) : key === "log" ? this.setState({ targetid: id }) : this[key](record);
  };
  handleCloseSlide = () => {
    const { slidePayload } = this.state;
    this.setState({
      slidePayload: {
        ...slidePayload,
        visible: false,
        title: "",
        children: null,
        data: {}
      }
    });
    this.tableRecordRef && this.tableRecordRef.handleResetSelectKeys();
    this.handleDebounce = null;
    this.props.cumDeductStore.initAddForm();
  };
  /*
   * Author: 黎永顺
   * Description: 筛选组件
   * Params:
   * Date: 2023/2/17
   */
  getScreen = () => {
    const { taxAgentStore: { taxAgentOption } } = this.props;
    const { declareMonth, taxAgentId, innerWidth } = this.state;
    const items = [
      {
        com: DataCollectionDatePicker({
          label: "税款所属期",
          value: declareMonth,
          onChange: this.screenChange,
          key: "declareMonth"
        })
      },
      {
        com: DataCollectionSelect({
          label: "个税扣缴义务人",
          value: taxAgentId,
          onChange: this.screenChange,
          options: taxAgentOption,
          key: "taxAgentId", multiple: true
        })
      }
    ];
    return <WeaSearchGroup className="screenWrapper" showGroup needTigger={false} items={items}
                           col={innerWidth < 900 ? 1 : 2}/>;
  };
  screenChange = ({ key, value }) => {
    const { cumDeductStore: { form } } = this.props;
    this.setState({ [key]: value }, () => this.tableRef.getTableDate({ ...form.getFormParams(), current: 1 }));
  };
  handleAdSearch = () => {
    const { cumDeductStore: { form } } = this.props;
    this.tableRef.getTableDate({ ...form.getFormParams(), current: 1 });
  };
  /*
   * Author: 黎永顺
   * Description: 顶部操作按钮
   * Params:
   * Date: 2023/2/17
   */
  getTopBtns = () => {
    const { addAllLoading } = this.state;
    return [
      <Button type="primary" onClick={this.handleOpenImport}>导入</Button>,
      <Button type="ghost" onClick={() => this.handleAddData()}>新建</Button>,
      <Button type="ghost" loading={addAllLoading} onClick={this.autoAddAll}>一键累计</Button>,
      <Dropdown
        overlay={
          <Menu className="dropdownMenuWrapper" onClick={this.handleDataMenuClick}>
            <Menu.Item key="deleteSelectAddUpDeduction">批量删除</Menu.Item>
            <Menu.Item key="deleteAllAddUpDeduction">一键清空</Menu.Item>
            <Menu.Item key="handleExportSelect">导出选中</Menu.Item>
            <Menu.Item key="handleExportAll">导出全部</Menu.Item>
          </Menu>
        }
      >
        <Button type="ghost">更多</Button>
      </Dropdown>
    ];
  };
  handleDataMenuClick = ({ key: keyFunc }) => this[keyFunc]();
  /*
   * Author: 黎永顺
   * Description:详情页面-操作按钮
   * Params:
   * Date: 2023/2/20
   */
  getDetailOptBtns = () => {
    return [
      <Dropdown.Button onClick={this.handleExportAllDetail}
                       overlay={<Menu
                         onClick={this.handleExportSelectDetail}>
                         <Menu.Item key="1">导出选中</Menu.Item>
                       </Menu>}
                       type="primary">
        导出全部
      </Dropdown.Button>
    ];
  };
  /*
   * Author: 黎永顺
   * Description: 导出详情数据
   * Params:
   * Date: 2023/2/21
   */
  handleExportDetail = (url) => {
    if (!this.handleDebounce) {
      this.handleDebounce = _.debounce(() => {
        window.open(`${window.location.origin}/api/bs/hrmsalary/addUpDeduction/exportDetail${url}`, "_self");
        this.handleDebounce = null;
      }, 500);
    }
    this.handleDebounce();
  };
  handleExportSelectDetail = () => {
    const { selectedRowKeys: ids, recordPayload } = this.tableRecordRef.state;
    if (ids.length === 0) {
      message.warning("请选择需要导出的数据");
      return;
    }
    const exportParams = _.reduce(_.keys(_.omitBy(recordPayload, it => !it)), (pre, cur) => pre + `${pre && "&"}${cur}=${recordPayload[cur]}`, "");
    const payload = `?${exportParams}&ids=${ids.join(",")}`;
    this.handleExportDetail(payload);
  };
  handleExportAllDetail = () => {
    const { recordPayload } = this.tableRecordRef.state;
    const exportParams = _.reduce(_.keys(_.omitBy(recordPayload, it => !it)), (pre, cur) => pre + `${pre && "&"}${cur}=${recordPayload[cur]}`, "");
    const payload = `?${exportParams}&ids=`;
    this.handleExportDetail(payload);
  };
  /*
   * Author: 黎永顺
   * Description: 数据采集-导入相关
   * Params:
   * Date: 2023/2/20
   */
  handleOpenImport = () => {
    const { importPayload } = this.state;
    const { importOpts } = importPayload;
    const { taxAgentStore: { taxAgentOption } } = this.props;
    this.setState({
      importPayload: {
        ...importPayload,
        visible: true, step: 0,
        importResult: {}, slideDataSource: [],
        importFormComponent: <ImportFormCom {...importOpts} taxAgentOption={taxAgentOption}
                                            onChangeImportForm={this.handleChangeImportForm}/>
      }
    });
  };
  handleCloseImport = (doSearch = false) => {
    const { importPayload } = this.state;
    this.setState({
      importPayload: {
        ...importPayload, visible: false, importFormComponent: null, step: 0,
        importOpts: {
          declareMonth: moment(new Date()).format("YYYY-MM"),
          taxAgentId: ""
        }, importResult: {}, slideDataSource: []
      }
    }, () => doSearch && this.tableRef.getTableDate());
  };
  handleChangeImportForm = (key, value) => {
    const { importPayload } = this.state;
    const { importOpts } = importPayload;
    this.setState({
      importPayload: { ...importPayload, importOpts: { ...importOpts, [key]: value } }
    });
  };

  render() {
    const { taxAgentStore: { showOperateBtn }, cumDeductStore: { form } } = this.props;
    const {
      declareMonth, taxAgentId, slidePayload, saveLoading, exportPayloadUrl, advanceCondition,
      importPayload, exportPayloadType, targetid
    } = this.state;
    const tablePayload = { declareMonth: [declareMonth], taxAgentIds: taxAgentId ? taxAgentId.split(",") : [] };
    return (
      <Layout title="累计专项附加扣除" btns={this.getTopBtns()} leftComp={this.getScreen()}
              onResizeWindowInnerWidth={this.handleResize} slidePayload={slidePayload}
              onClose={this.handleCloseSlide} onSave={this.handleSaveData}
              slideLoading={saveLoading} exportPayloadUrl={exportPayloadUrl}
              exportPayloadType={exportPayloadType} logFunction="addupdeduction"
              form={form} condition={advanceCondition} onAdSearch={this.handleAdSearch}
              onCancel={this.handleCloseImport} onImportFile={importCumDeductParam}
              importPayload={importPayload} detailOptBtns={this.getDetailOptBtns()}
              targetid={targetid} onClearTargrtid={() => this.setState({ targetid: "" })}
      >
        <DataTables
          ref={dom => this.tableRef = dom}
          url="/api/bs/hrmsalary/addUpDeduction/list"
          payload={tablePayload}
          showOperateBtn={showOperateBtn}
          onTableOperate={this.handleTableOperate}
          onViewDetails={(record) => this.handleAddData("累计专项附加扣除记录", record)}
          form={form}
        />
      </Layout>
    );
  }
}

export default Index;

export const DataCollectionDatePicker = (props) => {
  const {
    value, label, onChange, format = "YYYY-MM", key, screen = true,
    tip = "提示：默认显示本年截至当前月所有员工申报的累计专项附加及其他扣除额",
    labelCol = 8, wrapperCol = 16
  } = props;
  return <WeaFormItem label={label} labelCol={{ span: labelCol }} wrapperCol={{ span: wrapperCol }}>
    <WeaDatePicker value={value} onChange={(val) => onChange({ key, value: val })} format={format}/>
    {
      screen &&
      <WeaHelpfulTip title={tip} width={200}/>
    }
  </WeaFormItem>;
};
export const DataCollectionSelect = (props) => {
  const {
    value, label, onChange, options, key, labelCol = 10,
    wrapperCol = 14, viewAttr = 2, multiple = false
  } = props;
  return <WeaFormItem label={label} labelCol={{ span: labelCol }} wrapperCol={{ span: wrapperCol }}>
    <WeaSelect value={value} onChange={(val) => onChange({ key, value: val })} options={options}
               viewAttr={viewAttr} multiple={multiple}/>
  </WeaFormItem>;
};

export const Input = (props) => {
  const { value, label } = props;
  return (<WeaFormItem label={label} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
    <WeaInput value={value} viewAttr={1}/>
  </WeaFormItem>);
};
export const DataCollectionDateRangePick = (props) => {
  const { range, label, onChange, format = "YYYY-MM", key } = props;
  const [value1 = "", value2 = ""] = range;
  return <WeaFormItem label={label} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
    <WeaDatePicker
      value={value1} onChange={(val) => onChange({ key, value: [val, value2] })} format={format}
      disabledDate={(current) => {
        return current && value2 && current.getTime() > new Date(value2).getTime();
      }}
    />
    <span className="to">至</span>
    <WeaDatePicker
      value={value2} onChange={(val) => onChange({ key, value: [value1, val] })} format={format}
      disabledDate={(current) => {
        return current && value1 && current.getTime() < new Date(value1).getTime();
      }}
    />
  </WeaFormItem>;
};
