import { action, observable, toJS } from "mobx";
import { message } from "antd";
import { WeaForm, WeaTableNew } from "comsMobx";
import { removePropertyCondition } from "../util/response";

import * as API from "../apis/welfareArchive"; // 引入API接口文件

const { TableStore } = WeaTableNew;

export class ArchivesStore {
  @observable logForm = new WeaForm(); // 社保福利档案重构-日志查询条件log
  @observable welfareForm = new WeaForm(); // 社保福利档案重构-列表查询form
  @observable welfareProfileForm = new WeaForm(); // 社保福利档案重构-员工薪资档案form
  @action initWelfareProfileForm = () => {
    this.hasBeenModify = false;
    this.welfareProfileForm = new WeaForm();
  };
  @observable hasBeenModify = false; //社保福利档案-员工薪资档数据-是否修改过
  @action setHasBeenModify = (v) => this.hasBeenModify = v;//设置社保福利档案-员工薪资档数据


  @observable tableStore = new TableStore(
    //     {dataHandle: (datas) => {
    //     return dataSource;
    // }}
  );
  @observable form = new WeaForm(); // nrew 一个form
  @observable condition = []; // 存储后台得到的form数据
  @observable hasRight = true; // 判断用户是有权限查看当前页面： 没有权限渲染无权限页面，有权限渲染数据
  @observable showSearchAd = false; // 高级搜索面板显示
  @observable loading = true; // 数据加载状态

  @observable dataSource = [];

  // Slide 表单
  @observable baseFormData = {};
  @observable socialSecurityForm = {}; // 社保表单
  @observable accumulationFundForm = {}; // 公积金表单
  @observable otherForm = {}; // 其他福利表单

  // 基数表单
  @observable socialSecurityPaymentForm = {}; // 社保表单
  @observable accumulationFundPaymentForm = {}; // 公积金表单
  @observable otherPaymentForm = {}; // 其他福利表单
  @observable pageInfo = {};

  // 导入预览
  @observable previewCurDataList = {};
  @observable previewCurDataColumns = [];
  @observable previewCurDataDataSource = [];
  @observable importResult = {};

  @action
  initImportParams = () => {
    this.previewCurDataList = {};
    this.previewCurDataColumns = [];
    this.previewCurDataDataSource = [];
    this.importResult = {};
  };


  // ** 设置导入参数 start **
  @action
  setPreviewCurDataColumns = (previewCurDataColumns) => {
    this.previewCurDataColumns = previewCurDataColumns;
  };

  @action
  setPreviewCurDataDataSource = (previewCurDataDataSource) => {
    this.previewCurDataDataSource = previewCurDataDataSource;
  };

  @action
  setImportResult = (importResult) => {
    this.importResult = importResult;
  };
  // ** 设置导入参数 end **

  // 社保表单
  @action
  setSocialSecurityForm = socialSecurityForm => this.socialSecurityForm = socialSecurityForm;

  // 公积金表单
  @action
  setAccumulationFundForm = accumulationFundForm => this.accumulationFundForm = accumulationFundForm;

  // 其他福利表单
  @action
  setOtherForm = otherForm => this.otherForm = otherForm;

  // 社保表单
  @action
  setSocialSecurityPaymentForm = socialSecurityPaymentForm => this.socialSecurityPaymentForm = socialSecurityPaymentForm;

  // 公积金表单
  @action
  setAccumulationFundPaymentForm = accumulationFundPaymentForm => this.accumulationFundPaymentForm = accumulationFundPaymentForm;

  // 其他福利基数表单
  @action
  setOtherPaymentForm = otherPaymentForm => this.otherPaymentForm = otherPaymentForm;
  // 初始化操作
  @action
  doInit = () => {
    this.getCondition();
    // this.getTableDatas();
  };

  // 获得高级搜索表单数据
  @action
  getCondition = () => {
    API.getCondition().then(action(res => {
      if (res.status) { // 接口请求成功/失败处理
        let condition = removePropertyCondition(res.data.condition);
        this.condition = condition;
        this.form.initFormFields(condition); // 渲染高级搜索form表单
      } else {
        message.error(res.msg || "接口调用失败！");
      }
    }));
  };

  // 渲染table数据
  @action
  getTableDatas = (params = {}) => {
    this.loading = true;
    const formParams = this.form.getFormParams() || {};
    params = { ...formParams, ...params };
    API.getTable(params).then(action(res => {
      if (res.status) { // 接口请求成功/失败处理
        this.dataSource = res.data.datas.map(item => {
          item = { ...item };
          item.key = item.employeeId;
          return item;
        });
        // this.columns = res.data.columns;
        this.tableStore.getDatas(res.data.dataKey.datas);
        this.pageInfo = res.data.pageInfo;
      } else {
        message.error(res.msg || "接口调用失败！");
      }
      this.loading = false;
    }));
  };

  @action
  setShowSearchAd = bool => this.showSearchAd = bool;

  // 高级搜索 - 搜索
  @action doSearch = () => {
    this.getTableDatas();
    this.showSearchAd = false;
  };

  // 查询档案基本信息表单
  @action
  getBaseForm = (employeeId, welfareTypeEnum = "", paymentOrganization = "") => {
    API.getBaseForm({ employeeId, welfareTypeEnum, paymentOrganization }).then(action(res => {
      if (res.status) {
        if (welfareTypeEnum == "") {
          this.baseFormData = res.data.data;
        } else if (welfareTypeEnum == "SOCIAL_SECURITY") {
          this.socialSecurityForm = res.data;
        } else if (welfareTypeEnum == "ACCUMULATION_FUND") {
          this.accumulationFundForm = res.data;
        } else if (welfareTypeEnum == "OTHER") {
          this.otherForm = res.data;
        }
        // if(res.data && res.data.data && res.data.data.id) {
        //   this.getPaymentForm(employeeId, welfareTypeEnum, res.data.data.id)
        // }
      } else {
        message.error(res.errormsg || "获取失败");
      }
    }));
  };

  // 查询档案缴纳基数表单
  @action
  getPaymentForm = (employeeId, welfareTypeEnum, schemeId, paymentOrganization = "", isChange = false) => {
    API.getPaymentForm({ employeeId, welfareTypeEnum, schemeId, paymentOrganization }).then(res => {
      if (res.status) {
        let obj = {};
        const { items } = res.data;
        const [baseList] = items;
        if (!_.isEmpty(baseList.items)) {
          _.map(baseList.items, item => {
            obj = {
              ...obj,
              [item["domkey"][0]]: ""
            };
          });
        }
        if (welfareTypeEnum === "SOCIAL_SECURITY") {
          this.socialSecurityPaymentForm = res.data.data ? {
            ...res.data,
            data: { ...obj, ...res.data.data }
          } : { ...res.data, data: obj };
          if (isChange) {
            const socialSecurityPaymentData = toJS(this.socialSecurityPaymentForm).data;
            const socialSecurityPaymentItems = toJS(this.socialSecurityPaymentForm).items[0].items;
            const tmpV = socialSecurityPaymentItems.reduce((pre, cur) => {
              const { domkey, max, min } = cur;
              const minNum = !_.isNil(min) ? Number(min) : 0, maxNum = !_.isNil(max) ? Number(max) : 0;
              const val = socialSecurityPaymentData[domkey[0]];
              return Object.assign(pre, { [domkey[0]]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val });
            }, {});
            this.setSocialSecurityPaymentForm({
              ...toJS(this.socialSecurityPaymentForm),
              data: { ...socialSecurityPaymentData, ...tmpV }
            });
          }
        } else if (welfareTypeEnum === "ACCUMULATION_FUND") {
          this.accumulationFundPaymentForm = res.data.data ? {
            ...res.data,
            data: { ...obj, ...res.data.data }
          } : { ...res.data, data: obj };
          if (isChange) {
            const accumulationFundPaymentData = toJS(this.accumulationFundPaymentForm).data;
            const accumulationFundPaymentItems = toJS(this.accumulationFundPaymentForm).items[0].items;
            const tmpV = accumulationFundPaymentItems.reduce((pre, cur) => {
              const { domkey, max, min } = cur;
              const minNum = !_.isNil(min) ? Number(min) : 0, maxNum = !_.isNil(max) ? Number(max) : 0;
              const val = accumulationFundPaymentData[domkey[0]];
              return Object.assign(pre, { [domkey[0]]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val });
            }, {});
            this.setAccumulationFundPaymentForm({
              ...toJS(this.accumulationFundPaymentForm),
              data: { ...accumulationFundPaymentData, ...tmpV }
            });
          }
        } else if (welfareTypeEnum === "OTHER") {
          this.otherPaymentForm = res.data.data ? { ...res.data, data: { ...obj, ...res.data.data } } : {
            ...res.data,
            data: obj
          };
          if (isChange) {
            const otherPaymentData = toJS(this.otherPaymentForm).data;
            const otherPaymentItems = toJS(this.otherPaymentForm).items[0].items;
            const tmpV = otherPaymentItems.reduce((pre, cur) => {
              const { domkey, max, min } = cur;
              const minNum = !_.isNil(min) ? Number(min) : 0, maxNum = !_.isNil(max) ? Number(max) : 0;
              const val = otherPaymentData[domkey[0]];
              return Object.assign(pre, { [domkey[0]]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val });
            }, {});
            this.setOtherPaymentForm({
              ...toJS(this.otherPaymentForm),
              data: { ...otherPaymentData, ...tmpV }
            });
          }
        }
      }
    });
  };

  // 保存表单
  @action
  save = (welfareType, paymentOrganization) => {
    let baseForm = "";
    let paymentForm = "";
    if (welfareType === "SOCIAL_SECURITY") {
      baseForm = JSON.stringify({ ...this.socialSecurityForm.data, paymentOrganization });
      if (this.socialSecurityForm.data.socialSchemeId) {
        const socialSecurityPaymentData = toJS(this.socialSecurityPaymentForm).data;
        const socialSecurityPaymentItems = toJS(this.socialSecurityPaymentForm).items[0].items;
        const payload = socialSecurityPaymentItems.reduce((pre, cur) => {
          const { domkey } = cur;
          return Object.assign(pre, { [domkey[0]]: socialSecurityPaymentData[domkey[0]] ? socialSecurityPaymentData[domkey[0]].toString() : "0" });
        }, {});
        paymentForm = JSON.stringify(payload);
      }
    } else if (welfareType === "ACCUMULATION_FUND") {
      baseForm = JSON.stringify({ ...this.accumulationFundForm.data, paymentOrganization });
      if (this.accumulationFundForm.data.fundSchemeId) {
        const accumulationFundPaymentData = toJS(this.accumulationFundPaymentForm).data;
        const accumulationFundPaymentItems = toJS(this.accumulationFundPaymentForm).items[0].items;
        const payload = accumulationFundPaymentItems.reduce((pre, cur) => {
          const { domkey } = cur;
          return Object.assign(pre, { [domkey[0]]: accumulationFundPaymentData[domkey[0]] ? accumulationFundPaymentData[domkey[0]].toString() : "0" });
        }, {});
        paymentForm = JSON.stringify(payload);
      }
    } else if (welfareType === "OTHER") {
      baseForm = JSON.stringify({ ...this.otherForm.data, paymentOrganization });
      if (this.otherForm.data.otherSchemeId) {
        const otherPaymentData = toJS(this.otherPaymentForm).data;
        const otherPaymentItems = toJS(this.otherPaymentForm).items[0].items;
        const payload = otherPaymentItems.reduce((pre, cur) => {
          const { domkey } = cur;
          return Object.assign(pre, { [domkey[0]]: otherPaymentData[domkey[0]] ? otherPaymentData[domkey[0]].toString() : "0" });
        }, {});
        paymentForm = JSON.stringify(payload);
      }
    }
    return new Promise((resolve, reject) => {
      API.save({ welfareType, baseForm, paymentForm }).then(res => {
        if (res.status) {
          message.success("保存成功", 1);
          resolve();
          // this.getTableDatas()
        } else {
          message.error(res.errormsg || "保存失败", 1);
          reject();
        }
      });
    });
  };

  // 导入模板下载
  @action
  exportTempateDownload = (params = {}) => {
    API.exportCurData(params);
  };

  // 导入预览
  @action
  previewCurData = (params) => {
    API.previewCurData(params).then(res => {
      if (res.status) {
        this.previewCurDataList = res.data;
        this.previewCurDataColumns = res.data.headers.map((item, index) => {
          let column = {};
          column.title = item;
          column.dataIndex = "" + index;
          column.key = index + "";
          return column;
        });

        this.previewCurDataDataSource = res.data.list.map((item) => {
          let data = {};
          item.map((i, index) => {
            data[index + ""] = i;
          });
          return data;
        });

      } else {
        message.error(res.errormsg || "获取失败", 1);
      }
    });
  };

  // 导入
  @action
  importBatch = (params) => {
    return new Promise((resolve, reject) => {
      API.importBatch(params).then(res => {
        if (res.status) {
          this.importResult = res.data;
          resolve(res);
        } else {
          message.error(res.errormsg || "导入失败", 1);
          reject();
        }
      });
    });

  };

  // 导出档案
  @action
  exportArchives = (ids = "") => {
    API.exportArchives(ids);
  };
}
