/*
 * Author: 黎永顺
 * name: 考勤数据
 * Description:
 * Date: 2023/2/24
 */
import React, { Component } from "react";
import { WeaLocaleProvider, WeaTable } from "ecCom";
import { Dropdown, Menu, message, Modal } from "antd";
import {
  deleteAttendance,
  getAttendanceFieldSettingList,
  getAttendanceList,
  getLedgerList,
  getSalaryCycleAndAttendCycle,
  importAttendQuoteData,
  returnToAttendanceFieldSettingDefault,
  saveAttendanceFieldSetting,
  saveAttendanceFieldSettingAsDefault
} from "../../../../apis/attendance";
import ImportModal from "./importDialog";
// import HeaderSet from "../../../../components/importModal/headerSet";
// import ImportFormOptions from "./importFormOptions";
import SelectItemModal from "../../../../components/selectItemsModal";
import moment from "moment";
import SelectItemsWrapper from "../../../../components/selectItemsModal/selectItemsWrapper";
import AttendanceRefrenceDataModal from "./attendanceRefrenceDataModal";
import AttendanceDataViewSlide from "./attendanceDataViewSlide";

const getLabel = WeaLocaleProvider.getLabel;

class AttendanceDataComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: {
        query: false,
        headset: false
      },
      dataSource: [],
      columns: [],
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      importData: { visible: false, params: {} },
      importFormPayload: {
        salaryYearMonth: moment().format("YYYY-MM"), salarySobList: [],
        salarySobId: "", salaryCycle: "", attendCycle: ""
      },
      fieldSetPayload: { visible: false, title: "", children: null },
      attendanceReferencePayload: { visible: false, title: "" },
      attendanceViewPayload: { visible: false, attendQuoteId: "", salaryYearMonth: "" }
    };
  }

  componentDidMount() {
    this.getAttendanceList();
  }

  getAttendanceList = (extraPayload) => {
    const { loading, pageInfo } = this.state;
    const module = { ...pageInfo, ...extraPayload };
    this.setState({ loading: { ...loading, query: true } });
    getAttendanceList(module).then(({ status, data }) => {
      this.setState({ loading: { ...loading, query: false } });
      if (status) {
        const { columns, list: dataSource, pageNum: current, pageSize, total } = data;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total },
          dataSource,
          columns: _.map(columns, item => {
            if (item.dataIndex === "salaryYearMonth") {
              return {
                ...item,
                render: (text) => <span>{moment(text).format("YYYY-MM")}</span>
              };
            }
            return { ...item };
          })
        });
      }
    }).catch(() => this.setState({ loading: { ...loading, query: false } }));
  };
  getLedgerList = (importData) => {
    const { importFormPayload } = this.state;
    getLedgerList().then(({ status, data }) => {
      if (status) {
        this.setState({
          importFormPayload: {
            ...importFormPayload, salarySobId: _.head(data).id,
            salarySobList: _.map(data, it => ({ key: it.id, showname: it.content }))
          }
        }, async () => {
          const { importFormPayload } = this.state;
          const { salaryYearMonth, salarySobId } = importFormPayload;
          const payload = { salaryYearMonthStr: salaryYearMonth, salarySobId };
          const { data } = await getSalaryCycleAndAttendCycle(payload);
          this.setState({
            importData: { ...importData, params: { salaryYearMonth, salarySobId } },
            importFormPayload: { ...importFormPayload, ...data }
          });
        });
      }
    });
  };
  handleChangeImportPayload = (key, value) => {
    const { importFormPayload, importData } = this.state;
    const { params } = importData;
    this.setState({
      importFormPayload: {
        ...importFormPayload,
        [key]: value
      },
      importData: { ...importData, params: { ...params, [key]: value } }
    }, () => {
      if (this.state.importFormPayload.salaryYearMonth && this.state.importFormPayload.salarySobId) {
        const payload = {
          salaryYearMonthStr: this.state.importFormPayload.salaryYearMonth,
          salarySobId: this.state.importFormPayload.salarySobId
        };
        getSalaryCycleAndAttendCycle(payload).then(({ status, data }) => {
          if (status) {
            this.setState({
              importFormPayload: {
                ...this.state.importFormPayload,
                ...data
              }
            });
          }
        });
      }
    });
  };
  handleDeleteAttendanceData = ({ id }) => {
    Modal.confirm({
      title: "信息确认",
      content: "确认要删除吗?",
      onOk: () => {
        deleteAttendance([id]).then(({ status, errormsg }) => {
          if (status) {
            message.success("删除成功");
            this.getAttendanceList();
          } else {
            message.error(errormsg || "删除失败");
          }
        });
      }
    });
  };
  handleViewAttendanceData = ({ id, attendCycle }) => {
    const { attendanceViewPayload } = this.state;
    this.setState({
      attendanceViewPayload: {
        ...attendanceViewPayload,
        visible: true, attendQuoteId: id,
        salaryYearMonth: attendCycle
      }
    });
  };
  handleImportAttendanceData = (importData) => this.getLedgerList(importData);
  handleFinish = (isFresh) => {
    const { importData } = this.state;
    this.setState({
      importData: { ...importData, visible: false, params: {} }
    }, () => isFresh && this.getAttendanceList());
  };
  /*
   * Author: 黎永顺
   * Description: 表头设置
   * Params:
   * Date: 2023/3/6
   */
  handleHeaderSettings = (params) => {
    const { fieldSetPayload, loading } = this.state;
    this.setState({ loading: { ...loading, headset: true } });
    getAttendanceFieldSettingList(params).then(({ status, data }) => {
      this.setState({ loading: { ...loading, headset: false } });
      if (status) {
        this.setState({
          fieldSetPayload: {
            ...fieldSetPayload,
            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({ loading: { ...loading, headset: false } }));
  };
  handleCloseSettings = () => {
    const { fieldSetPayload } = this.state;
    this.setState({
      fieldSetPayload: {
        ...fieldSetPayload,
        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: "IMPORT" }).then(({ status, errormsg }) => {
          if (status) {
            message.success("操作成功");
            this.handleHeaderSettings({ sourceType: "IMPORT" });
          } 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: "IMPORT" };
        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: "IMPORT" };
    saveAttendanceFieldSetting(payload).then(({ status, errormsg }) => {
      if (status) {
        message.success("保存成功");
        this.handleCloseSettings();
      } else {
        message.error(errormsg || "保存失败");
      }
    });
  };
  /*
   * Author: 黎永顺
   * Description: 考勤数据引用
   * Params:
   * Date: 2023/3/7
   */
  handleQuoteAttendanceData = (payload) => {
    const { attendanceReferencePayload } = this.state;
    this.setState({ attendanceReferencePayload: { ...attendanceReferencePayload, ...payload } });
  };
  handleCloseQuoteModal = (isRefresh) => {
    const { attendanceReferencePayload } = this.state;
    this.setState({ attendanceReferencePayload: { ...attendanceReferencePayload, visible: false } }, () => {
      isRefresh && this.getAttendanceList();
    });
  };

  render() {
    const {
      dataSource, columns, pageInfo, loading, importData, importFormPayload, fieldSetPayload,
      attendanceReferencePayload, attendanceViewPayload
    } = this.state;
    const { showOperateBtn, salaryYearMonth } = this.props;
    const pagination = {
      ...pageInfo,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ["10", "20", "50", "100"],
      onShowSizeChange: (current, pageSize) => {
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize }
        }, () => this.getAttendanceList({ salaryYearMonth: _.compact(salaryYearMonth) }));
      },
      onChange: current => {
        this.setState({
          pageInfo: { ...pageInfo, current }
        }, () => this.getAttendanceList({ salaryYearMonth: _.compact(salaryYearMonth) }));
      }
    };
    return (
      <React.Fragment>
        <WeaTable
          columns={[
            ...columns,
            {
              title: "操作",
              width: 120,
              dataIndex: "operate",
              render: (_, record) => {
                return (
                  <div className="linkWapper">
                    <a href="javascript: void(0);" onClick={() => this.handleViewAttendanceData(record)}>查看</a>
                    {showOperateBtn &&
                      <React.Fragment>
                        <a href="javascript: void(0);" style={{ marginRight: 10 }}
                           onClick={() => this.handleDeleteAttendanceData(record)}>删除</a>
                        <Dropdown
                          overlay={
                            <Menu>
                              <Menu.Item>
                                <a href="javascript:void(0);"
                                   onClick={() => this.props.onFilterLog("log", record.id)}>{getLabel(545781, "操作日志")}</a>
                              </Menu.Item>
                            </Menu>
                          }>
                          <a href="javascript:void(0)"><i className="icon-coms-more"/></a>
                        </Dropdown>
                      </React.Fragment>
                    }
                    {
                      !showOperateBtn &&
                      <a href="javascript:void(0)"
                         onClick={() => this.props.onFilterLog("log", record.id)}>{getLabel(545781, "操作日志")}</a>
                    }
                  </div>
                );
              }
            }
          ]}
          dataSource={dataSource} pagination={pagination} loading={loading.query}/>
        {/* 考勤引用导入 */}
        <ImportModal {...importData} importFormPayload={importFormPayload} onCancel={this.handleFinish}
                     onChangeImportForm={this.handleChangeImportPayload} onHeaderSettings={this.handleHeaderSettings}
                     loading={loading.headset} previewUrl="/api/bs/hrmsalary/attendQuote/preview"
                     importAttendQuoteData={importAttendQuoteData}
        />
        {/* 表头设置 */}
        <SelectItemModal {...fieldSetPayload}
                         onCancel={this.handleCloseSettings}
                         onSearchItemSet={this.handleSearchItemSet}
                         onShowOnlyChecked={this.handleShowOnlyChecked}
                         onMoreOpts={this.handleMoreOpts} onSave={this.handleSave}/>
        {/* 考勤数据引用 */}
        <AttendanceRefrenceDataModal {...attendanceReferencePayload} onCancel={this.handleCloseQuoteModal}/>
        {/* 考勤数据查看 */}
        <AttendanceDataViewSlide {...attendanceViewPayload} showOperateBtn={showOperateBtn}
                                 onClose={() => this.setState({
                                   attendanceViewPayload: {
                                     ...attendanceViewPayload,
                                     visible: false,
                                     attendQuoteId: ""
                                   }
                                 })}/>
      </React.Fragment>
    );
  }
}

export default AttendanceDataComp;
