/*
 * Author: 黎永顺
 * name: 薪资核算-自定义导出
 * Description:
 * Date: 2023/9/18
 */

import React, { Component } from "react";
import { Button, Col, message, Row } from "antd";
import { inject, observer } from "mobx-react";
import { WeaCheckbox, WeaDialog, WeaLocaleProvider, WeaSearchGroup, WeaSelect } from "ecCom";
import ExpTempManagementDialog from "../expTempManagementDialog";
import {
  customCacheExportField,
  getExportField,
  getExportTemplateForm,
  getExportTemplateList
} from "../../../../../apis/calculate";
import { convertToUrlString } from "../../../../../util/url";
import "./index.less";
import TempDialog from "../expFieldsSetDialog/tempDialog";

const { getLabel } = WeaLocaleProvider;

@inject("calculateStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemsCheckeds: [], showOnlyChecked: false, tempMangeDialog: { visible: false, salaryAcctRecordId: "" },
      tempDialog: { visible: false, salaryAcctRecordId: "", id: "", salaryItemIds: [] },
      tempOptions: [
        { key: "NULL", showname: "" },
        { key: "system", selected: true, showname: getLabel(111, "系统模板") }
      ]
    };
  }

  async componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      this.setState({
        itemsCheckeds: !_.isEmpty(nextProps.checkItems) ? nextProps.checkItems : []
      }, () => this.getExportTemplateList(nextProps));
    } else {
      this.setState({
        tempOptions: [
          { key: "NULL", showname: "" },
          { key: "system", selected: true, showname: getLabel(111, "系统模板") }
        ]
      });
    }
  }

  getExportTemplateList = (props) => {
    const { salaryAcctRecordId } = props;
    getExportTemplateList({ salaryAcctRecordId }).then(({ status, data }) => {
      if (status) {
        const { pageInfo: { list } } = data;
        this.setState({
          tempOptions: [
            ...this.state.tempOptions, ..._.map(list, o => ({ key: String(o.id), showname: o.templateName }))
          ]
        });
      }
    });
  };

  customExportClick = () => {
    const { calculateStore: { ECSearchForm }, salaryAcctRecordId } = this.props;
    const { itemsCheckeds } = this.state;
    customCacheExportField({ salaryItems: _.map(itemsCheckeds, it => it.toString()) }).then(({ status, errorMsg }) => {
      if (status) {
        const { consolidatedTaxation = "0", ...extra } = ECSearchForm.getFormParams();
        const payload = { ...extra, consolidatedTaxation: consolidatedTaxation === "0" ? "" : consolidatedTaxation };
        window.open(
          `/api/bs/hrmsalary/salaryacct/acctresult/exportWithCustomFields?salaryAcctRecordId=${salaryAcctRecordId}&ids=&${convertToUrlString(payload)}&salaryItemIds=${itemsCheckeds.join(",")}`
        );
      } else {
        message.error(errorMsg);
      }
    });
  };
  handleShowOnlyChecked = (showOnlyChecked) => this.setState({ showOnlyChecked: !!Number(showOnlyChecked) });
  handleSelectGroupAll = (groupId, checked) => {
    const { itemsCheckeds } = this.state;
    const { itemsByGroup } = this.props;
    _.map(itemsByGroup, item => {
      if (item.salarySobItemGroupId === groupId) {
        if (!!Number(checked)) {
          this.setState({
            itemsCheckeds: [...itemsCheckeds, ..._.map(item.salaryItems, child => child.salaryItemId)]
          });
        } else {
          this.setState({
            itemsCheckeds: _.differenceWith(itemsCheckeds, _.map(item.salaryItems, child => child.salaryItemId), _.isEqual)
          });
        }
      }
    });
  };
  handleChangeExpTemp = async (id) => {
    switch (id) {
      case "system":
        const { salaryAcctRecordId } = this.props;
        const { data: { checkItems: checkeds } } = await getExportField({ salaryAcctRecordId });
        this.setState({ itemsCheckeds: checkeds });
        break;
      case "NULL":
        this.setState({ itemsCheckeds: [] });
        break;
      default:
        const { data: { checkItems } } = await getExportTemplateForm({ id });
        this.setState({ itemsCheckeds: _.map(checkItems, o => parseInt(o)) });
        break;
    }
  };

  render() {
    const { showOnlyChecked, itemsCheckeds, tempMangeDialog, tempDialog, tempOptions } = this.state;
    const { itemsByGroup, salaryAcctRecordId } = this.props;
    let dataSource = _.map(itemsByGroup, item => {
      return {
        ...item,
        salaryItems: _.map(item.salaryItems, child => {
          return { ...child, checked: itemsCheckeds.includes(child.salaryItemId) };
        })
      };
    });
    if (showOnlyChecked) {
      dataSource = _.map(dataSource, item => {
        return { ...item, salaryItems: _.filter(item.salaryItems, it => !!it.checked) };
      });
    }
    const titleComp = <div className="setHeaderWrapper">
      <span>{getLabel(111, "选择字段")}</span>
      <WeaSelect options={tempOptions} style={{ width: 200 }}
                 onChange={this.handleChangeExpTemp}/>
    </div>;
    return (
      <WeaDialog
        {...this.props} hasScroll initLoadCss className="customEpDialogLayout"
        scalable title={titleComp}
        style={{
          width: 700,
          height: 606.6,
          minHeight: 200,
          minWidth: 380,
          maxHeight: "70%",
          maxWidth: "90%",
          overflow: "hidden",
          transform: "translate(0px, 0px)"
        }}
        buttons={[
          <Button type="primary" onClick={this.customExportClick}>{getLabel(17416, "导出")}</Button>,
          <Button type="primary" onClick={() => this.setState({
            tempDialog: { visible: true, salaryAcctRecordId, id: "", salaryItemIds: itemsCheckeds },
            tempOptions: [
              { key: "NULL", showname: "" },
              { key: "system", selected: true, showname: getLabel(111, "系统模板") }
            ]
          })}>{getLabel(111, "存为模板")}</Button>,
          <Button type="primary"
                  onClick={() => this.setState({
                    tempMangeDialog: { visible: true, salaryAcctRecordId },
                    tempOptions: [
                      { key: "NULL", showname: "" },
                      { key: "system", selected: true, showname: getLabel(111, "系统模板") }
                    ]
                  })}>{getLabel(111, "模板管理")}</Button>,
          <Button type="ghost" onClick={this.props.onCancel}>{getLabel(31129, "取消")}</Button>
        ]}
        bottomLeft={<WeaCheckbox content={getLabel(543378, "只显示已选中字段")}
                                 onChange={this.handleShowOnlyChecked}/>}
      >
        {
          _.map(dataSource, item => {
            const { salarySobItemGroupName, salaryItems, salarySobItemGroupId } = item;
            const value = _.every(salaryItems, it => !!it.checked) ? "1" : "0";
            return <WeaSearchGroup showGroup needTigger
                                   title={<WeaCheckbox content={salarySobItemGroupName} value={value}
                                                       onChange={(val) => this.handleSelectGroupAll(salarySobItemGroupId, val)}/>}>
              <Row gutter={16}>
                {
                  !_.isEmpty(salaryItems) ?
                    _.map(salaryItems, it => {
                      const { salaryItemId, salaryItemName, checked } = it;
                      return <Col span={8} style={{ marginBottom: 16 }}>
                        <WeaCheckbox content={salaryItemName} value={checked ? "1" : "0"}
                                     onChange={() => this.setState({ itemsCheckeds: _.xorWith(itemsCheckeds, [salaryItemId], _.isEqual) })}/>
                      </Col>;
                    }) : <Col span={24} style={{
                      minHeight: 20,
                      padding: "5%",
                      textAlign: "center"
                    }}>{getLabel(83553, "暂无数据")}</Col>
                }
              </Row>
            </WeaSearchGroup>;
          })
        }
        <ExpTempManagementDialog {...tempMangeDialog}
                                 onCancel={() => this.setState({
                                   tempMangeDialog: { ...tempMangeDialog, visible: false }
                                 }, () => this.getExportTemplateList(this.props))}
        />
        {/*模板保存*/}
        <TempDialog {...tempDialog} onCancel={() => this.setState({
          tempDialog: { ...tempDialog, visible: false }
        }, () => this.getExportTemplateList(this.props))}/>
      </WeaDialog>
    );
  }
}

export default Index;
