import { action, observable } from "mobx";
import { message } from "antd";
import { WeaForm, WeaTableNew } from "comsMobx";

import * as API from "../apis/calculate";
import { toDecimal_n } from "../util";

const { TableStore } = WeaTableNew;

export class calculateStore {
  @observable PCSearchForm = new WeaForm(); //人员确认-form
  @observable ECSearchForm = new WeaForm(); //薪资核算-form
  @observable otherConditions = []; //薪资核算-其他查询条件
  @observable calculateForm = new WeaForm(); //薪资核算重构-核算form
  @observable batchUpdateForm = new WeaForm(); //批量更新薪资项目-批量更新form
  @action initBatchUpdateForm = () => this.batchUpdateForm = new WeaForm();
  @observable tempForm = new WeaForm(); //导出模板设置-模板form
  @action initTempForm = () => this.tempForm = new WeaForm();

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

  // ** 薪资核算列表 **
  @observable salaryListDataSource = [];
  @observable salaryListColumns = [];
  @observable calculateBaseForm = {};
  @observable salaryListPageInfo = {};

  // ** 核算信息页 ***
  // 核算人员
  @observable acctemployeeListDataSource = []; // dataSource
  @observable acctemployeeListColumns = []; // 列
  @observable acctemployeeListPageInfo = {}; // 分页信息
  // 环比上期减少人员
  @observable reducedemployeeListDataSource = []; // dataSource
  @observable reducedemployeeListColumns = []; // 列
  @observable reducedemployeeListPageInfo = {}; // 分页信息
  // 薪资周期、考勤周期
  @observable baseSalarySobCycle = {};

  // *** 薪资核算 ***
  // 核算结果--列表
  @observable acctResultListDateSource = []; // dataSource
  @observable acctResultListColumns = [];  // 列
  @observable acctresultDetailForm = {}; // 编辑薪资表单数据
  @observable acctResultListTableStore = new TableStore();
  @observable acctResultListPageInfo = {}; // 分页信息
  // 导入
  @observable importFieldData = {}; // 表头选择列表
  @observable acctResultImportPreview = {}; // 核算结果预览
  @observable previewAcctResultList = {}; //预览数据
  @observable previewAcctResultColumns = []; // 预览列表
  @observable previewAcctResultDataSource = []; // 预览DataSource
  @observable importAcctResult = {}; // 导入结果

  //*** 线下比对 ***
  @observable comparisonResultPageInfo = [];// 线下对比列表pageInfo
  @observable comparisonResultTableStore = new TableStore(); // tableStore
  @observable comparisonPreviewColumns = []; // 线下对比预览列表
  @observable comparisonPreviewDataSource = []; // 线下对比列表数据
  @observable comparisonImportAcctResult = {}; // 导入结果
  @observable comparisonResultColumns = []; // 表头

  // ** 核算进度 **
  @observable calculateProgress = 0;

  // ** 列表说明数据 **
  @observable columnDescList = {};


  //  ** 薪资核算-其他条件查询 **
  @action
  setOtherConditions = (otherConditions) => this.otherConditions = otherConditions;
  //  ** 薪资核算重构-初始化核算form **
  @action
  initCalcForm = () => this.calculateForm = new WeaForm();

  //  ** 设置导入参数 **
  @action
  setPreviewAcctResultColumns = (previewAcctResultColumns) => {
    this.previewAcctResultColumns = previewAcctResultColumns;
  };

  @action
  setPreviewAcctResultDataSource = previewAcctResultDataSource => {
    this.previewAcctResultDataSource = previewAcctResultDataSource;
  };

  @action
  setImportAcctResult = importAcctResult => {
    this.importAcctResult = importAcctResult;
  };

  @action
  setComparisonPreviewColumns = comparisonPreviewColumns => {
    this.comparisonPreviewColumns = comparisonPreviewColumns;
  };

  @action
  setComparisonPreviewDataSource = comparisonPreviewDataSource => {
    this.comparisonPreviewDataSource = comparisonPreviewDataSource;
  };

  @action
  setComparisonImportAcctResult = comparisonImportAcctResult => {
    this.comparisonImportAcctResult = comparisonImportAcctResult;
  };


  // 编辑薪资表单数据
  @action
  setAcctresultDetailForm = (acctresultDetailForm) => {
    this.acctresultDetailForm = acctresultDetailForm;
  };
  // 初始化操作
  @action
  doInit = () => {
    this.getCondition();
    this.getTableDatas();
  };

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

  // 渲染table数据
  @action
  getTableDatas = (params) => {
    this.loading = true;
    const formParams = this.form.getFormParams() || {};
    params = params || formParams;
    API.getTableDatas(params).then(action(res => {
      if (res.api_status) { // 接口请求成功/失败处理
        this.tableStore.getDatas(res.datas); // table 请求数据
        this.hasRight = res.hasRight;
      } else {
        message.error(res.msg || "接口调用失败！");
      }
      this.loading = false;
    }));
  };

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

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

  // 薪资记录--薪资核算列表
  @action
  getSalaryAcctList = (params = {}) => {
    this.loading = true;
    API.getSalaryAcctList(params).then(res => {
      if (res.status) {
        this.salaryListDataSource = res.data.list;
        this.salaryListColumns = res.data.columns;
        this.salaryListPageInfo = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.loading = false;
    });
  };

  // 薪资记录--保存薪资核算的基本信息
  @action
  saveBasic = (params = {}) => {
    return new Promise((resolve, reject) => {
      API.saveBasic(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve(res.data);
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });

  };

  // 薪资记录--薪资核算详情
  @action
  salaryacctGetForm = (id) => {
    return new Promise((resolve, reject) => {
      API.salaryacctGetForm({ id }).then(res => {
        if (res.status) {
          this.calculateBaseForm = res.data;
          resolve(res.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 核算人员--薪资核算人员确认列表
  @action
  acctemployeeList = (params) => {
    const { departmentIds = "", positionIds = "", ...extraParams } = params || {};
    params = {
      ...extraParams,
      departmentIds: departmentIds ? departmentIds.split(",") : undefined,
      positionIds: positionIds ? positionIds.split(",") : undefined
    };
    for (let key in params) {
      if (params[key] === "") {
        delete params[key];
      }
    }
    API.acctemployeeList(params).then((res) => {
      if (res.status) {
        this.acctemployeeListDataSource = res.data.list ? res.data.list : [];
        this.acctemployeeListColumns = res.data.columns;
        this.acctemployeeListPageInfo = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 核算人员--检查薪资核算人员的个税扣缴义务人
  @action
  checkTaxAgent = (id = "") => {
    API.checkTaxAgent({ salaryAcctRecordId: id }).then(res => {
      if (res.status) {

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

  // 核算人员--薪资核算环比上期减少人员列表
  @action
  reducedemployeeList = (params) => {
    this.loading = true;
    const { departmentIds = "", positionIds = "", ...extraParams } = params || {};
    params = {
      ...extraParams,
      departmentIds: departmentIds ? departmentIds.split(",") : undefined,
      positionIds: positionIds ? positionIds.split(",") : undefined
    };
    for (let key in params) {
      if (params[key] === "") {
        delete params[key];
      }
    }
    API.reducedemployeeList(params).then(res => {
      if (res.status) {
        this.reducedemployeeListDataSource = res.data.list ? res.data.list : [];
        this.reducedemployeeListColumns = res.data.columns;
        this.reducedemployeeListPageInfo = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.loading = false;
    });
  };


  // 薪资记录--获取薪资核算的薪资周期、考勤周期等
  @action
  getSalarySobCycle = (id = "") => {
    API.getSalarySobCycle({ salaryAcctRecordId: id }).then(res => {
      if (res.status) {
        this.baseSalarySobCycle = res.data;
        this.getColumnDesc({ salaryAcctRecordId: id });
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 核算人员--添加薪资核算人员
  @action
  saveAcctemployee = (salaryAcctRecordId, employeeIds) => {
    return new Promise((resolve, reject) => {
      API.saveAcctemployee({ salaryAcctRecordId, employeeIds }).then(res => {
        if (res.status) {
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };


  // 核算人员--导出环比减少人员
  @action
  exportReducedEmployee = (id) => {
    API.exportReducedEmployee(id);
  };

  // 核算人员--导出人员范围
  @action
  exportAcctEmployee = (id) => {
    API.exportAcctEmployee(id);
  };

  // 核算人员--删除薪资核算人员
  @action
  deleteAcctemployee = (salaryAcctRecordId, ids) => {
    return new Promise((resolve, reject) => {
      API.deleteAcctemployee({ salaryAcctRecordId, ids }).then(res => {
        if (res.status) {
          message.success("删除成功");
          resolve();
        } else {
          message.error(res.errormsg || "删除失败");
          reject();
        }
      });
    });
  };

  // 核算结果--列表
  @action
  acctResultList = (params = {}) => {
    this.loading = true;
    const { departmentIds = "", positionIds = "", consolidatedTaxation = "0", ...extraParams } = params || {};
    params = {
      ...extraParams,
      departmentIds: departmentIds ? departmentIds.split(",") : undefined,
      positionIds: positionIds ? positionIds.split(",") : undefined,
      consolidatedTaxation: consolidatedTaxation === "0" ? null : "1"
    };
    for (let key in params) {
      if (params[key] === "") {
        delete params[key];
      }
    }
    return new Promise((resolve, reject) => {
      API.acctResultList({ ...params }).then(res => {
        if (res.status) {
          let list = res.data.pageInfo.list ? res.data.pageInfo.list : [];
          list.map(item => {
            item.key = item.id;
          });
          this.acctResultListDateSource = list;
          this.acctResultListPageInfo = res.data.pageInfo;
          this.acctResultListColumns = res.data.columns;
          resolve(res.data.columns);
          this.getColumnDesc({ salaryAcctRecordId: params.salaryAcctRecordId });
        } else {
          message.error(res.errormsg || "");
          reject();
        }
        this.loading = false;
      });
    });
  };

  @action
  getColumnDesc = (params) => {
    API.getColumnDesc(params).then(res => {
      if (res.status) {
        this.columnDescList = res.data;
      } else {
        message.error(res.errormsg);
      }
    });
  };

  // 核算结果--薪资核算
  @action
  acctresultAccounting = (params) => {
    return new Promise((resolve, reject) => {
      API.acctresultAccounting(params).then(res => {
        if (res.status) {
          resolve();
        } else {
          message.error(res.errormsg || "核算失败");
          reject();
        }
      });
    });

  };

  // 线下比对-列表
  @action
  comparisonresultList = (salaryAcctRecordId, params = {}) => {
    API.comparisonresultList({ salaryAcctRecordId, ...params }).then(res => {
      if (res.status) {
        this.comparisonresultListDataSource = res.data.list ? res.data.list : [];
        this.comparisonresultListColumns = res.data.columns;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 核算人员--刷新薪资核算人员的个税扣缴义务人
  @action
  refreshTaxAgent = (salaryAcctRecordId) => {
    return new Promise((resolve, reject) => {
      API.refreshTaxAgent({ salaryAcctRecordId }).then(res => {
        if (res.status) {
          message.success("刷新成功");
          resolve();
        } else {
          message.error(res.errormsg || "刷新失败");
          reject();
        }
      });
    });
  };

  // 薪资核算-编辑表单
  @action
  acctresultDetail = (id) => {
    API.acctresultDetail({ id }).then(res => {
      if (res.status) {
        this.acctresultDetailForm = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 薪资记录--删除薪资核算记录
  @action
  deleteSalaryacct = (ids) => {
    return new Promise((resolve, reject) => {
      API.deleteSalaryacct(ids).then(res => {
        if (res.status) {
          message.success("删除成功");
          resolve();
        } else {
          message.error(res.errormsg || "删除失败");
          reject();
        }
      });
    });
  };

  // 薪资记录--归档薪资核算记录
  @action
  fileSalaryAcct = (id) => {
    return new Promise((resolve, reject) => {
      API.fileSalaryAcct({ id }).then(res => {
        if (res.status) {
          resolve();
        } else {
          message.error(res.errormsg || "归档失败");
          reject(res);
        }
      });
    });
  };

  // 薪资记录-重新核算
  @action
  reAccounting = (salaryAcctRecordId) => {
    return new Promise((resolve, reject) => {
      API.reAccounting({ salaryAcctRecordId }).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };
  // 薪资记录-回算
  @action
  backCalculate = (salaryAcctRecordId) => {
    return new Promise((resolve, reject) => {
      API.backCalculate({ salaryAcctRecordId }).then(res => {
        if (res.status) {
          message.success("回算成功");
          resolve();
        } else {
          message.error(res.errormsg || "回算失败");
          reject();
        }
      });
    });
  };

  // 薪资结果-编辑表单保存
  @action
  saveAcctResult = (recordId) => {
    const itemsByGroupItems = _.reduce(this.acctresultDetailForm.itemsByGroup, (pre, cur) => {
      return [
        ...pre,
        ..._.map(cur.salaryItems, it => {
          return {
            salaryItemId: it.salaryItemId,
            resultValue: (it.dataType === "number" && !!it.resultValue) ? toDecimal_n(it.resultValue, it.pattern || 2) : it.resultValue
          };
        })
      ];
    }, []);

    const issuedAndReissueItems = this.acctresultDetailForm.issuedAndReissueItems.map(item => {
      let record = {};
      record.salaryItemId = item.salaryItemId;
      record.resultValue = (item.dataType === "number" && !!item.resultValue) ? toDecimal_n(item.resultValue, item.pattern || 2) : item.resultValue;
      return record;
    });

    let items = itemsByGroupItems.concat(issuedAndReissueItems);
    let params = {
      salaryAcctEmpId: recordId,
      items
    };
    return new Promise((resolve, reject) => {
      API.saveAcctResult(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });

  };

  // 获取导入字段设置
  @action
  getImportField = (salaryAcctRecordId) => {
    return new Promise((resolve, reject) => {
      API.getImportField({ salaryAcctRecordId }).then(res => {
        if (res.status) {
          this.importFieldData = res.data;
          resolve(res.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });

  };

  // 下载薪资导入核算模板
  @action
  getImportTemplate = (salaryItemIds, salaryAcctRecordId) => {
    API.getImportTemplate(salaryItemIds, salaryAcctRecordId);
  };

  // 核算结果-导入预览
  @action
  fetchPreviewAcctResult = (params) => {
    API.previewAcctResult(params).then((res) => {
      if (res.status) {
        this.previewAcctResultList = res.data;
        this.previewAcctResultColumns = res.data.headers.map((item, index) => {
          let column = {};
          column.title = item;
          column.dataIndex = "" + index;
          column.key = index + "";
          return column;
        });

        this.previewAcctResultDataSource = res.data.list.map((item) => {
          let data = {};
          item.map((i, index) => {
            data[index + ""] = i;
          });
          return data;
        });
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 核算结果-导入
  @action
  fetchImportAcctResult = (params) => {
    API.importAcctResult(params).then(res => {
      if (res.status) {
        this.importAcctResult = res.data;
      } else {
        message.error(res.errormsg || "导入失败");
      }
    });
  };

  // 核算结果-导出全部
  @action
  exportAll = (salaryAcctRecordId, ids = "") => {
    API.exportAcctResult(salaryAcctRecordId, ids);
  };

  // 线下对比-列表
  @action
  fetchComparisonResultList = (params) => {
    this.loading = true;
    API.comparisonResultList(params).then(res => {
      if (res.status) {
        this.comparisonResultPageInfo = res.data;
        this.comparisonResultColumns = res.data.columns;
        // this.comparisonResultTableStore.getDatas(res.data.dataKey.datas)
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.loading = false;
    });
  };

  // 线下对比-导入模板
  @action
  exportImportTemplate = (salaryAcctRecordId) => {
    API.exportImportTemplate(salaryAcctRecordId);
  };

  // 线下对比--导入预览
  @action
  previewComparisonResult = (params) => {
    API.previewComparisonResult(params).then(res => {
      if (res.status) {
        this.comparisonPreviewColumns = res.data.headers.map((item, index) => {
          let column = {};
          column.title = item;
          column.dataIndex = "" + index;
          column.key = index + "";
          return column;
        });

        this.comparisonPreviewDataSource = res.data.list.map((item) => {
          let data = {};
          item.map((i, index) => {
            data[index + ""] = i;
          });
          return data;
        });
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 线下对比-导入
  @action
  importComparisonExcelAcctResult = (params) => {
    API.importComparisonExcelAcctResult(params).then(res => {
      if (res.status) {
        this.comparisonImportAcctResult = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 线下对比-导出
  @action
  exportComparisonResult = (salaryAcctRecordId) => {
    API.exportComparisonResult(salaryAcctRecordId);
  };

  // 核算进度条
  @action
  getCalculateProgress = (id) => {
    return new Promise((resolve, reject) => {
      API.getCalculateProgress(id).then(res => {
        if (res.status) {
          let progress = 0;
          try {
            progress = Number(res.data.progress) * 100;
          } catch (err) {
          }
          resolve(res.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  @action("更新薪资核算结果的锁定状态")
  updateLockStatus = (params) => {
    return API.updateLockStatus(params);
  };
}
