/*
 * Author: 黎永顺
 * name: 考勤数据引用
 * Description:
 * Date: 2023/3/1
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog } from "ecCom";
import { Button, message } from "antd";
import { reFrenceConditions } from "../columns";
import { getSearchs } from "../../../../util";
import {
  checkOperation,
  getAttendanceFieldSettingList,
  getLedgerList,
  returnToAttendanceFieldSettingDefault,
  saveAttendanceFieldSetting,
  saveAttendanceFieldSettingAsDefault,
  syncAttendanceRefer
} from "../../../../apis/attendance";
import SelectItemModal from "../../../../components/selectItemsModal";
import SelectItemsWrapper from "../../../../components/selectItemsModal/selectItemsWrapper";
import "./index.less";

@inject("attendanceStore")
@observer
class AttendanceRefrenceDataModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      headerSetLoading: false,
      condition: [],
      headerSetPayload: { visible: false, title: "", children: null }
    };
  }

  componentDidMount() {
    this.getLedgerList();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.handleResetForm();
  }

  getLedgerList = () => {
    const { attendanceStore: { refenceform } } = this.props;
    getLedgerList().then(({ status, data }) => {
      if (status) {
        this.setState({
          condition: _.map(reFrenceConditions, (item) => {
            const { items } = item;
            return {
              ...item,
              items: _.map(items, child => {
                const { domkey } = child;
                if (domkey[0] === "salarySobIds") {
                  return { ...child, options: _.map(data, it => ({ key: it.id, showname: it.content })) };
                }
                return { ...child };
              })
            };
          })
        }, () => refenceform.initFormFields(this.state.condition));
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 同步考勤数据
   * Params:
   * Date: 2023/3/1
   */
  handleSubmitFields = () => {
    const { attendanceStore: { refenceform }, onCancel } = this.props;
    refenceform.validateForm().then(f => {
      if (f.isValid) {
        const payload = refenceform.getFormParams();
        const checkPayload = {
          salaryYearMonthStr: payload.salaryYearMonth,
          salarySobIds: payload.salarySobIds.split(",")
        };
        this.setState({ loading: true });
        checkOperation(checkPayload).then(({ status, errormsg: errormessage }) => {
          if (status) {
            syncAttendanceRefer({ ...payload, salarySobIds: payload.salarySobIds.split(",") })
              .then(({ status, errormsg }) => {
                this.setState({ loading: false });
                if (status) {
                  message.success("同步成功");
                  onCancel(true);
                } else {
                  message.error(errormsg || "同步失败");
                }
              }).catch(() => this.setState({ loading: false }));
          } else {
            this.setState({ loading: false });
            message.error(errormessage);
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };
  handleResetForm = () => {
    const { attendanceStore: { refenceform } } = this.props;
    refenceform.resetForm();
  };
  /*
   * Author: 黎永顺
   * Description: 表头设置
   * Params:
   * Date: 2023/3/8
   */
  handleHeaderSetting = () => {
    const { headerSetPayload } = this.state;
    this.setState({ headerSetLoading: true });
    getAttendanceFieldSettingList({ sourceType: "QUOTE" }).then(({ status, data }) => {
      this.setState({ headerSetLoading: false });
      if (status) {
        this.setState({
          headerSetPayload: {
            ...headerSetPayload,
            visible: true, title: "引用考勤字段设置",
            children: <SelectItemsWrapper
              ref={dom => this.setItemRef = dom}
              dataSource={data}
              onSelectGroupAll={this.handleSelectGroupAll}
              onSelectItem={this.handleSelectItem}
            />
          }
        }, () => this.setItemRef && this.setItemRef.initSelectItem());
      }
    }).catch(() => this.setState({ headerSetLoading: false }));
  };
  handleCloseSettings = () => {
    const { headerSetPayload } = this.state;
    this.setState({
      headerSetPayload: {
        ...headerSetPayload,
        visible: false, title: "", children: null
      }
    });
  };
  handleSearchItemSet = (val) => this.setItemRef.handleSearchItemSet(val);
  handleShowOnlyChecked = (checked) => this.setItemRef.handleShowOnlyChecked(checked);
  handleSelectGroupAll = (groupId, checked) => this.setItemRef.handleSelectGroupAll(groupId, checked);
  handleSelectItem = (id, checked) => this.setItemRef.handleSelectItem(id, checked);
  handleMoreOpts = (key) => {
    switch (key) {
      case "recovery":
        returnToAttendanceFieldSettingDefault({ sourceType: "QUOTE" }).then(({ status, errormsg }) => {
          if (status) {
            message.success("操作成功");
            this.handleHeaderSetting({ sourceType: "QUOTE" });
          } else {
            message.error(errormsg || "操作失败");
          }
        });
        break;
      case "setting":
        const { state, props } = this.setItemRef;
        let currentSettingFields = [];
        const { selectItem } = state, { dataSource } = props;
        _.forEach(dataSource, item => {
          currentSettingFields = _.map([...currentSettingFields, ...item.items], child => {
            return {
              id: child.id,
              checked: selectItem.includes(child.id)
            };
          });
        });
        const payload = { currentSettingFields, sourceType: "QUOTE" };
        saveAttendanceFieldSettingAsDefault(payload).then(({ status, errormsg }) => {
          if (status) {
            message.success("操作成功");
          } else {
            message.error(errormsg || "操作失败");
          }
        });
        break;
      default:
        break;
    }
  };
  handleSave = () => {
    const { state, props } = this.setItemRef;
    let currentSettingFields = [];
    const { selectItem } = state, { dataSource } = props;
    _.forEach(dataSource, item => {
      currentSettingFields = _.map([...currentSettingFields, ...item.items], child => {
        return {
          id: child.id,
          checked: selectItem.includes(child.id)
        };
      });
    });
    const payload = { currentSettingFields, sourceType: "QUOTE" };
    saveAttendanceFieldSetting(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success("保存成功");
        this.handleCloseSettings();
      } else {
        message.error(errormsg || "保存失败");
      }
    });
  };

  render() {
    const { condition, loading, headerSetLoading, headerSetPayload } = this.state;
    const { attendanceStore: { refenceform } } = this.props;
    const buttons = [
      <Button type="primary" onClick={this.handleSubmitFields} loading={loading}>同步</Button>,
      <Button type="ghost" onClick={this.handleHeaderSetting} loading={headerSetLoading}>表头设置</Button>
    ];
    return (
      <WeaDialog {...this.props} style={{ width: 535, height: 174 }} buttons={buttons} initLoadCss>
        <div className="form-dialog-layout">
          {getSearchs(refenceform, condition, 1, false, null, "", "multiple_select")}
        </div>
        {/* 表头设置 */}
        <SelectItemModal {...headerSetPayload}
                         onCancel={this.handleCloseSettings}
                         onSearchItemSet={this.handleSearchItemSet}
                         onShowOnlyChecked={this.handleShowOnlyChecked}
                         onMoreOpts={this.handleMoreOpts} onSave={this.handleSave}
        />
      </WeaDialog>
    );
  }
}

export default AttendanceRefrenceDataModal;
