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

import * as API from "../apis/payroll"; // 引入API接口文件
import { removePropertyCondition } from "../util/response";

const { TableStore } = WeaTableNew;

export class payrollStore {
  //工资单重构页面
  @observable payrollCopyForm = new WeaForm(); //模板复制form
  @action initPayrollCopyForm = () => this.payrollCopyForm = new WeaForm();
  @observable payrollTempForm = new WeaForm(); //新建编辑工资单模板form
  @action initPayrollTempForm = () => this.payrollTempForm = new WeaForm();
  @observable payrollTempFeedbackForm = new WeaForm(); //新建编辑工资单模板-工资单确认反馈设置form
  @action initPayrollTempFeedbackForm = () => this.payrollTempFeedbackForm = new WeaForm();
  @observable tmplDataSource = {}; //工资单模板数据
  @action setTmplDataSource = (v) => this.tmplDataSource = v;//设置工资单模板数据
  @observable hasBeenModify = false; //工资单模板数据-是否修改过
  @action setHasBeenModify = (v) => this.hasBeenModify = v;//设置工资单模板数据

  @observable payrollTempNormalForm = new WeaForm(); //新建编辑工资单模板-主题设置form
  @action initPayrollTempNormalForm = () => this.payrollTempNormalForm = new WeaForm();
  @observable salaryBillItemNameSetting = [
    {
      salaryTemplateId: "",
      salaryBillType: 0,
      itemShowNameSetting: []
    },
    {
      salaryTemplateId: "",
      salaryBillType: 1,
      itemShowNameSetting: []
    }
  ]; // 工资单模板薪资项目名称修改列表
  @action
  setSalaryBillItemNameSetting = salaryBillItemNameSetting => (this.salaryBillItemNameSetting = salaryBillItemNameSetting);


  @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 btnLoading = false; // 数据加载状态

  // **** 模板页面 ****
  @observable templateStore = new TableStore(); // 模板设置列表
  // 基础设置表单
  @observable templateBaseData = {}; // 基础信息表单数据
  @observable salarySobOptions = []; // 账套列表
  // 显示设置表单
  @observable salaryTemplateShowSet = {}; // 显示设置基础表单
  @observable replenishSalaryTemplateSalaryItemSet = []; // 补发工资单模版基础表单
  @observable salaryItemSet = []; // 显示设置薪资项

  @observable salaryBillItemNameSet = {}; // 工资单模板薪资项目名称修改列表

  // **** 工资单页面 ****
  @observable salarySendTableStore = new TableStore(); // 工资单列表
  @observable salarySendDataSource = [];
  @observable pageInfo = {};

  // **** 工资单详情页 ****
  @observable salarySendDetailBaseInfo = {}; // 工资单详情基础信息
  @observable salarySendDetailDataSource = []; // 详情列表DataSource
  @observable salarySendDetailTableStore = new TableStore(); // 详情列表store
  @observable detailListConditionForm = new WeaForm(); // 详情页搜索条件
  @observable salaryTableStore = new TableStore();//薪资查看详情页表格Store
  @observable detailListShowSearchAd = false; // 详情页是否展开搜索面板
  @observable detailListCondition = []; // 详情页搜索条件
  @observable salarySendDetailPageInfo = {};

  // **** 工资单发放页 ****
  @observable salaryGrantDataSource = [];
  @observable salaryGrantPageInfo = {};
  @observable salaryGrantTableStore = [];
  @observable grantListConditionForm = new WeaForm(); // 详情页搜索条件
  @observable grantListShowSearchAd = false; // 详情页是否展开搜索面板
  @observable grantListCondition = []; // 详情页搜索条件
  @observable canGrantDataSource = []; // 可以发送的列表
  @observable canGrantColumns = []; // 可以发送的列名
  @observable canGrantPageInfo = {}; // 可以发送列表分页对象
  @observable canWithdrawDataSource = []; // 可以撤回的列表
  @observable canWidthdrawColumns = []; // 可以撤回的列表列名
  @observable canWithdrawPageInfo = {}; // 可以撤回列表分页对象

  // **** 工资单模板 ****
  @observable templateTableColumns = []; // 工资单模板columns
  @observable templateTableDataSource = []; // 工资单模板dataSource
  @observable templateTablePageInfo = {
    current: 1, pageSize: 10, total: 0
  }; // 工资单模板pageInfo
  @observable templateTableSelectedRowKeys = []; // 工资单模板复选框

  @action
  setReplenishSalaryTemplateSalaryItemSet = replenishSalaryTemplateSalaryItemSet =>
    (this.replenishSalaryTemplateSalaryItemSet = replenishSalaryTemplateSalaryItemSet);

  @action
  setGrantListShowSearchAd = grantListShowSearchAd =>
    (this.grantListShowSearchAd = grantListShowSearchAd);

  //  详情页是否展开搜索面板
  @action
  setDetailListShowSearchAd = detailListShowSearchAd =>
    (this.detailListShowSearchAd = detailListShowSearchAd);

  // 基础信息表单数据
  @action
  setTemplateBaseData = templateBaseData => (this.templateBaseData = templateBaseData);

  // 显示设置基础表单
  @action
  setSalaryTemplateShowSet = salaryTemplateShowSet =>
    (this.salaryTemplateShowSet = salaryTemplateShowSet);

  @action
  setSalaryItemSet = salaryItemSet => (this.salaryItemSet = salaryItemSet);
  @action
  setSalaryBillItemNameSet = salaryBillItemNameSet => (this.salaryBillItemNameSet = salaryBillItemNameSet);

  @action("工资单模板分页信息修改")
  setTemplateTablePageInfo = (pageInfo, callback) => {
    this.templateTablePageInfo = { ...this.templateTablePageInfo, ...pageInfo };
    callback && callback();
  };
  @action("工资单模板复选框选择")
  setTemplateTableSelectedRowKeys = (selectedRowKeys) => this.templateTableSelectedRowKeys = selectedRowKeys;

  // 初始化操作
  @action
  doInit = () => {
    // this.getCondition();
    // this.getTableDatas();
  };

  // 获得高级搜索表单数据
  @action
  getCondition = () => {
    API.getCondition().then(
      action(res => {
        if (res.api_status) {
          // 接口请求成功/失败处理
          let condition = removePropertyCondition(res.condition);
          this.form.initFormFields(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
  getPayrollTemplateList = (params = {}) => {
    this.loading = true;
    API.getPayrollTemplateList({ ...this.templateTablePageInfo, ...params }).then(res => {
      if (res.status) {
        this.templateTableColumns = res.data.columns;
        this.templateTableDataSource = res.data.list;
        this.setTemplateTablePageInfo({
          current: res.data.pageNum,
          pageSize: res.data.pageSize,
          total: res.data.total
        });
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.loading = false;
    });
  };

  // 工资单模板-获取工资单模板基础设置表单
  @action
  getPayrollBaseForm = (id = "") => {
    let params = { id };
    return new Promise((resolve, reject) => {
      API.getPayrollBaseForm(params).then(res => {
        if (res.status) {
          let response = res.data.salaryTemplateBaseSet;
          let templateBaseData = response.data;
          templateBaseData.salarySob =
            templateBaseData.salarySob != undefined
              ? templateBaseData.salarySob + ""
              : null;
          this.templateBaseData = templateBaseData; // 基础信息表单数据

          this.salarySobOptions = response.salarySobOptions
            ? response.salarySobOptions.map(item => {
              let result = {};
              result.showname = item.name;
              result.key = item.id + "";
              result.selected = false;
              return result;
            })
            : [];
          resolve({
            replenishRuleSetOption: res.data.replenishRuleSetOption,
            templateBaseData: this.templateBaseData,
            salarySobOptions: this.salarySobOptions
          });
        } else {
          message.errro(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 工资单模板-获取工资单模板显示设置表单
  @action
  getPayrollShowForm = (id = "") => {
    const params = { id };
    const salaryTemplateShowSetStorage = window.localStorage.getItem("salary-showset") || "{}";
    API.getPayrollShowForm(params).then(res => {
      if (res.status) {
        if (id !== "") {
          this.salaryItemSet = res.data.salaryTemplateSalaryItemSet;
          this.replenishSalaryTemplateSalaryItemSet = res.data.replenishSalaryTemplateSalaryItemSet;
        }
        this.salaryBillItemNameSet = res.data.salaryBillItemNameSet;
        this.salaryTemplateShowSet = { ...res.data.salaryTemplateShowSet.data, ...JSON.parse(salaryTemplateShowSetStorage) };
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 工资单模板-获取薪资项目设置
  @action
  getPayrollItemList = (salarySobId = "") => {
    let params = {
      salarySobId
    };
    API.getPayrollItemList(params).then(res => {
      if (res.status) {
        this.salaryItemSet = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 初始化显示设置表单
  @action
  initShowSettingForm = (id = "") => {
    this.getPayrollShowForm(id);
    if (id === "") {
      this.getPayrollItemList(this.templateBaseData.salarySob);
    }
  };

  // 拼装保存参数
  convertParams = () => {
    let params = { ...this.templateBaseData, ...this.salaryTemplateShowSet };
    params.replenishRule = (!params.replenishRule || params.reissueRule === "0") ? "ALL" : params.replenishRule;
    params.salarySobId = params.salarySob;
    params.emailStatus = params.emailStatus ? params.emailStatus : false;
    params.msgStatus = params.msgStatus ? params.msgStatus : false;
    params.salaryItemNullStatus = params.salaryItemNullStatus
      ? params.salaryItemNullStatus
      : false;
    params.salaryItemZeroStatus = params.salaryItemZeroStatus
      ? params.salaryItemZeroStatus
      : false;
    params.salaryItemSetting = toJS(this.salaryItemSet);
    params.replenishSalaryItemSetting = toJS(this.replenishSalaryTemplateSalaryItemSet);
    params.salaryBillItemNameSetting = toJS(this.salaryBillItemNameSetting);
    return params;
  };

  // 工资单模板-新建工资单模板
  @action
  fetchSavePayroll = () => {
    return new Promise((resolve, reject) => {
      const params = this.convertParams();
      API.savePayroll(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          this.getPayrollTemplateList();
          this.setSalaryBillItemNameSetting(_.map(this.salaryBillItemNameSetting, it => {
            return { ...it, salaryTemplateId: "", itemShowNameSetting: [] };
          }));
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      }).catch(() => reject());
    });
  };

  // 工资单模板-更新工资单模板
  @action
  fetchUpdatePayroll = id => {
    return new Promise((resolve, reject) => {
      let params = this.convertParams();
      params.id = id;
      API.updatePayroll(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          this.getPayrollTemplateList();
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };

  //工资单-获取薪资账套下拉列表
  @action
  getPayrollTemplateLedgerList = () => {
    return new Promise((resolve, reject) => {
      API.getPayrollTemplateLedgerList().then(res => {
        if (res.status) {
          this.payrollTemplateLedgerList = res.data.map(item => {
            let result = {};
            result.showname = item.content;
            result.selected = false;
            result.key = item.id;
            return result;
          });
          resolve(this.payrollTemplateLedgerList);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 工资单模板-工资单模板默认使用
  @action
  changePayrollDefaultUse(id = "") {
    if (id == "") {
      message.warning("id必填");
      return;
    }
    let params = {
      id
    };
    return new Promise((resolve, reject) => {
      API.changePayrollDefaultUse(params).then(res => {
        if (res.status) {
          message.success("设置成功");
          resolve();
        } else {
          message.success(res.errormsg || "设置失败");
          reject();
        }
      });
    });
  }

  // 工资单模板-复制工资单模板
  @action
  duplicatePayroll = (id, name) => {
    let params = {
      id,
      name
    };
    return new Promise((resolve, reject) => {
      API.duplicatePayroll(params).then(res => {
        if (res.status) {
          message.success("复制成功");
          this.getPayrollTemplateList();
          resolve();
        } else {
          message.error(res.errormsg || "复制失败");
          reject();
        }
      });
    });
  };

  // 工资单模板-删除工资单模板
  @action
  deletePayroll = ids => {
    API.deletePayroll(ids).then(res => {
      if (res.status) {
        message.success("删除成功");
        this.setTemplateTableSelectedRowKeys([]);
        this.getPayrollTemplateList();
      } else {
        message.error(res.errormsg || "删除失败");
      }
    });
  };

  // 工资单-工资单发放列表
  @action
  getPayrollList = (parmas = { salaryYearMonth: [] }) => {
    this.loading = true;
    API.getPayrollList(parmas).then(res => {
      if (res.status) {
        this.salarySendDataSource = res.data.datas;
        this.salarySendTableStore.getDatas(res.data.dataKey.datas);
        this.pageInfo = res.data.pageInfo;
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.loading = false;
    });
  };

  // 工资单发放-工资单发放基本信息
  @action
  getPayrollInfo = id => {
    API.getPayrollInfo({ id }).then(res => {
      if (res.status) {
        this.salarySendDetailBaseInfo = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 工资单发放-工资单发放信息列表
  @action
  getInfoList = (params = {}) => {
    let form = this.grantListConditionForm.getFormParams();
    params = {
      ...form, ...params,
      departmentIds: form.departmentIds ? form.departmentIds.split(",") : [],
      subCompanyIds: form.subCompanyIds ? form.subCompanyIds.split(",") : []
    };
    this.loading = true;
    API.getInfoList(params).then(res => {
      this.loading = false;
      if (res.status) {
        this.salaryGrantTableStore = res.data.columns;
        this.salaryGrantDataSource = res.data.list;
        this.salaryGrantPageInfo = {
          total: res.data.total,
          pageNum: res.data.pageNum
        };
        this.getPayrollInfo(params.salarySendId);
      } else {
        message.error(res.errormsg || "获取失败");
      }
    }).catch(() => this.loading = false);
  };

  // 工资单-工资单发放详情列表
  @action
  getPayrollDetailList = params => {
    let form = this.detailListConditionForm.getFormParams() || {};
    params = { ...form, ...params };
    API.getPayrollDetailList(params).then(res => {
      if (res.status) {
        this.salarySendDetailTableStore.getDatas(res.data.dataKey.datas);
        this.salarySendDetailDataSource = res.data.datas;
        this.salarySendDetailPageInfo = res.data.pageInfo;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

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

  // 工资单发放-导出-工资单发放详情列表
  @action
  exportDetailList = (params = {}) => {
    API.exportDetailList(params);
  };
  // 工资单发放-导出-工资单发放列表

  @action
  exportPayroll = (params = {}) => {
    API.exportPayroll(params);
  };

  // 工资单-获取工资单发放高级搜索
  @action
  getPaySa = (params = {}) => {
    API.getPaySa(params).then(res => {
      if (res.status) {
        let condition = removePropertyCondition(res.data.condition);
        this.grantListCondition = condition;
        this.grantListConditionForm.initFormFields(condition);
      } else {
        message.error(res.errormsg || "接口调用失败");
      }
    });
  };

  // 工资单发放-工资单批量发放信息列表
  @action
  batchSendInfoList = (params = {}) => {
    API.batchSendInfoList(params).then(res => {
      if (res.status) {
        this.canGrantDataSource = res.data.list;
        this.canGrantColumns = res.data.columns;
        this.canGrantPageInfo = {
          total: res.data.total,
          pageNum: res.data.pageNum
        };
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 工资单发放-工资单批量撤回信息列表
  @action
  batchWithdrawInfoList = (params = {}) => {
    API.batchWithdrawInfoList(params).then(res => {
      if (res.status) {
        let datas = res.data.list || [];
        datas.map(item => {
          item.key = item.id;
        });
        this.canWithdrawDataSource = datas;
        this.canWidthdrawColumns = res.data.columns;
        this.canWithdrawPageInfo = {
          total: res.data.total,
          pageNum: res.data.pageNum
        };
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  //工资单-工资单发放
  @action
  grantPayroll = (params = {}) => {
    return new Promise((resolve, reject) => {
      // message.destroy();
      // message.loading("正在发放中...", 0);
      this.btnLoading = true;
      // WeaLoadingGlobal.start();
      API.grantPayroll(params).then(res => {
        this.btnLoading = false;
        // WeaLoadingGlobal.end();
        // WeaLoadingGlobal.destroy();
        // message.destroy();
        if (res.status) {
          // message.success("发送成功");
          resolve();
        } else {
          message.error(res.errormsg || "发送失败");
          reject();
        }
      }).catch(() => {
        this.btnLoading = false;
        // WeaLoadingGlobal.end();
        // WeaLoadingGlobal.destroy();
      });
    });
  };

  // 工资单-工资单撤回
  @action
  withdrawPayroll = (params = {}) => {
    return new Promise((resolve, reject) => {
      message.destroy();
      message.loading("正在撤回中...", 0);
      this.btnLoading = true;
      WeaLoadingGlobal.start();
      API.withdrawPayroll(params).then(res => {
        this.btnLoading = false;
        WeaLoadingGlobal.end();
        WeaLoadingGlobal.destroy();
        message.destroy();
        if (res.status) {
          message.success("撤回成功");
          resolve();
        } else {
          message.error(res.errormsg || "撤回失败");
          reject();
        }
      }).catch(() => {
        this.btnLoading = false;
        WeaLoadingGlobal.end();
        WeaLoadingGlobal.destroy();
      });
    });
  };
  // 工资单-工资单撤回
  @action
  getSendBtnStatus = (params = {}) => {
    return new Promise((resolve, reject) => {
      API.getSendBtnStatus(params).then(res => {
        if (res.status) {
          resolve(res.data);
        } else {
          reject();
        }
      });
    });
  };
  // 工资单-流程发起
  @action
  grantProxy = (params = {}) => {
    return new Promise((resolve, reject) => {
      API.grantProxy(params).then(res => {
        if (res.status) {
          resolve(res.data);
        } else {
          reject();
        }
      });
    });
  };
}
