/*
  * 薪酬统计分析-薪资明细
  * 列表模板设置
  * @Author:    黎永顺
  * @Date:      2024/11/7
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaLoadingGlobal, WeaLocaleProvider, WeaTools } from "ecCom";
import { tempCondition } from "./conditions";
import { getTaxAgentSelectList } from "../../../apis/taxAgent";
import * as API from "../../../apis/statistics";
import { downloadPageListTemplate } from "../../../apis/statistics";
import { Button, message } from "antd";
import { getSearchs } from "../../../util";

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

@inject("attendanceStore")
@observer
class SalaryDetailTempDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, conditions: []
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.getTempForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      this.setState({ loading: false, conditions: [] }, () => nextProps.attendanceStore.initTempForm());
    }
  }

  getTempForm = (props) => {
    getTaxAgentSelectList().then(({ status, data }) => {
      if (status) {
        const { id, template } = props;
        this.setState({
          conditions: _.map(tempCondition, item => ({
            ...item, items: _.map(item.items, o => {
              if (getKey(o) === "sharedType") {
                return {
                  ...o, label: getLabel(o.lanId, o.label), value: id ? String(template["sharedType"]) : "1",
                  options: [
                    { key: "1", showname: getLabel(111, "私有") },
                    { key: "0", showname: getLabel(111, "共享") }
                  ]
                };
              } else if (getKey(o) === "limitIds") {
                return {
                  ...o, label: getLabel(o.lanId, o.label), hide: !id || (id && template["sharedType"] === 1),
                  value: id ? template["limitIds"].join(",") : "",
                  options: _.map(data, o => ({ key: o.id, showname: o.content }))
                };
              } else if (getKey(o) === "fileId") {
                return {
                  ...o, label: getLabel(o.lanId, o.label), value: id ? template[getKey(o)] : "",
                  datas: id && template[getKey(o)] ? [
                    { fileid: template[getKey(o)], filename: template["fileName"], showDelete: true }
                  ] : [], labelExtra: getLabel(111, "下载示例"), labelType: "download"
                };
              }
              return { ...o, label: getLabel(o.lanId, o.label), value: id ? template[getKey(o)] : "" };
            })
          }))
        }, () => {
          const { attendanceStore: { tempForm } } = props;
          tempForm.initFormFields(this.state.conditions);
        });
      }
    });
  };
  save = () => {
    const { attendanceStore: { tempForm }, setting, id } = this.props;
    tempForm.validateForm().then(f => {
      if (f.isValid) {
        this.setState({ loading: true });
        const { limitIds, fileId, ...formVal } = tempForm.getFormParams();
        const payload = {
          page: "salary_details_report", setting, id, ...formVal,
          limitIds: !_.isEmpty(limitIds) ? limitIds.split(",") : []
        };
        API.savePageListTemplate(_.assign(payload, fileId ? { fileId } : {})).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(111, "操作成功！"));
            this.props.onCancel(this.props.onSuccess());
          } else {
            message.error(errormsg);
          }
        });
      } else {
        f.showErrors();
      }
    }).catch(() => this.setState({ loading: false }));
  };
  formFieldChange = (field) => {
    if (field === "download") {
      const { setting, heads } = this.props;
      WeaLoadingGlobal.start();
      const promise = downloadPageListTemplate({ setting, heads });
      return;
    }
    const key = Object.keys(field)[0], value = field[key].value;
    this.setState({
      conditions: _.map(this.state.conditions, item => ({
        ...item, items: _.map(item.items, o => {
          if (key === "sharedType" && getKey(o) === "limitIds") {
            return {
              ...o, hide: value !== "0", viewAttr: value === "0" ? 3 : 1,
              rules: value === "0" ? "required|string" : ""
            };
          } else if (key === "fileId" && getKey(o) === "fileId") {
            return {
              ...o, value, datas: value ? _.map(field[key].valueSpan, o => ({
                fileid: o.fileid, filename: o.filename, showDelete: true
              })) : []
            };
          }
          return { ...o };
        })
      }))
    }, () => {
      const { attendanceStore: { tempForm } } = this.props;
      tempForm.initFormFields(this.state.conditions);
    });
  };

  render() {
    const { loading, conditions } = this.state;
    const { attendanceStore: { tempForm } } = this.props;
    return (
      <WeaDialog
        {...this.props} style={{ width: 480, height: 127 }} initLoadCss title={getLabel(111, "模板保存")}
        buttons={[<Button type="primary" onClick={this.save} loading={loading}>{getLabel(537558, "保存")}</Button>]}>
        <div
          className="form-dialog-layout tempDialog">{getSearchs(tempForm, conditions, 1, false, this.formFieldChange)}</div>
      </WeaDialog>
    );
  }
}

export default SalaryDetailTempDialog;
