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

import * as API from "../apis/archive"; // 引入API接口文件
import { notNull } from "../util/validate";

const { TableStore } = WeaTableNew;

export class salaryFileStore {
  @observable adjForm = new WeaForm(); // 调薪form


  @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 userStatusList = [];
  @observable archiveStatusList = [];

  @observable importType = [];
  @observable previewColumns = [];
  @observable previewDataSource = [];
  @observable dataSource = [];
  @observable detailForm = {};
  @observable adjustSalaryItems = []; //薪资档案项
  @observable pageInfo = {}; // 分页数据
  @observable salaryArchiveTaxAgentForm = {};
  @observable salaryItemChangeForm = {};
  @observable taxAgentList = [];
  @observable salaryItemList = [];
  @observable singleSalaryItemList = [];
  @observable singleTaxAgentList = [];

  @observable currentId = "";
  @observable salaryIncreaseUrl = {}; //发起流程url地址 isShow:是否显示按钮，url：链接地址
  @observable editAgentVisible = false;

  @action("设置发起调薪地址")
  setSalaryIncreaseUrl = data => (this.salaryIncreaseUrl = data);
  @action("设置薪资档案项")
  setAdjustSalaryItems = data => (this.adjustSalaryItems = data);
  @action("调薪初始化form")
  initAdjForm = () => (this.adjForm = new WeaForm());
  // ** 设置导入参数 start **
  @action
  setPreviewDataSource = (previewDataSource) => {
    this.previewDataSource = previewDataSource;
  };
  // ** 设置导入参数 end **

  // 初始化操作
  @action
  doInit = (params) => {
    // this.getCondition();
    this.getTableDatas(params);
    this.getImportTypes();
    this.commonEnumList("archive", { enumClass: "com.engine.salary.enums.salaryarchive.ArchiveStatusEnum" });
    this.commonEnumList("user", { enumClass: "com.engine.salary.enums.UserStatusEnum" });
  };

  // 发起调薪地址
  @action
  salaryAdjustmentInfo = () => {
    API.salaryAdjustmentInfo().then(({ status, data }) => {
      if (status) {
        this.setSalaryIncreaseUrl(data);
      }
    });
  };
  // 获取导入类型
  @action
  getImportTypes = () => {
    API.getImportTypes().then(res => {
      if (res.status) {
        this.importType = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  @action("获取档案和人员状态类型")
  commonEnumList = (type, params) => {
    API.commonEnumList(params).then(res => {
      if (res.status) {
        const data = _.map(res.data, it => ({
          key: String(it.value),
          showname: it.defaultLabel
        }));
        type === "archive" ? this.archiveStatusList = [{
          key: "",
          showname: ""
        }, ...data] : this.userStatusList = [...data];
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 获得高级搜索表单数据
  @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数据1
  @action
  getTableDatas = (params) => {
    this.loading = true;
    const formParams = this.form.getFormParams() || {};
    const { departmentIds = "", positionIds = "", subcompanyIds = "", ...extraParams } = params || {};
    params = {
      ...formParams, ...extraParams,
      departmentIds: departmentIds ? departmentIds.split(",") : "",
      positionIds: positionIds ? positionIds.split(",") : "",
      subcompanyIds: subcompanyIds ? subcompanyIds.split(",") : ""
    };
    API.getArchiveList(params).then(action(res => {
      if (res.status) { // 接口请求成功/失败处理
        this.tableStore.getDatas(res.data.dataKey.datas); // table 请求数据
        this.dataSource = res.data.pageInfo.list.map(item => {
          item.key = item.id;
          return item;
        });
        this.pageInfo = res.data.pageInfo;
      } else {
        message.error(res.errormsg || "接口调用失败！");
      }
      this.loading = false;
    }));
  };

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

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

  // 导入预览
  @action
  importPreview = (params) => {
    API.importPreview(params).then(res => {
      if (res.status) {
        let headers = res.data.headers;
        this.previewColumns = headers.map((item, index) => {
          return {
            key: index,
            title: item,
            dataIndex: index
          };
        });

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

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

  // 导入档案
  @action
  importSalaryArchive = (params, tableParams) => {
    return new Promise((resolve, reject) => {
      API.importSalaryArchive(params).then(res => {
        if (res.status) {
          // message.success("导入成功")
          this.getTableDatas({ ...tableParams });
          resolve(res.data);
        } else {
          message.error(res.errormsg || "接口异常");
          reject();
        }
      });
    });

  };

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

  // 获取详情
  @action
  getArchiveForm = (salaryArchiveId) => {
    return new Promise((resolve, reject) => {
      API.getArchiveForm({ salaryArchiveId }).then(res => {
        if (res.status) {
          this.detailForm = res.data;
          this.setAdjustSalaryItems(res.data.adjustSalaryItems || []);
          resolve(res.data.paySet.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 个税义务人表单
  valideTaxAgentForm(params) {
    if (!notNull(params.effectiveTime)) {
      message.warning("生效日期不能为空");
      return false;
    }

    if (!notNull(params.adjustReason)) {
      message.warning("调整原因不能为空");
      return false;
    }

    if (!notNull(params.taxAgentId)) {
      message.warning("调整后个税义务人不能为空");
      return false;
    }
    return true;
  }

  // 薪资档案-保存个税扣缴义务人调整
  @action
  saveTaxAgent = (params) => {
    if (!this.valideTaxAgentForm(params)) {
      return;
    }
    return new Promise((resolve, reject) => {
      API.saveTaxAgent(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });

  };

  // 调整-义务扣缴人-调整表单
  @action
  getTaxAgentForm = (salaryArchiveId) => {
    return new Promise((resolve, reject) => {
      API.getTaxAgentForm({ salaryArchiveId }).then(res => {
        if (res.status) {
          this.salaryArchiveTaxAgentForm = res.data.salaryArchiveTaxAgentForm;
          resolve();
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  convertForm = (resData) => {
    let salaryItemChangeForm = {};
    salaryItemChangeForm.adjustReasonList = resData.salaryArchiveItemForm.adjustReasonList.map(item => {
      item = { ...item };
      item.key = item.id;
      item.showname = item.content;
      item.selected = false;
      return item;
    });

    salaryItemChangeForm.salaryItemList = resData.salaryArchiveItemDetail.salaryItemList.map(item => {
      item = { ...item };
      item.key = item.id;
      item.showname = item.content;
      item.selected = false;
      return item;
    });

    salaryItemChangeForm.columns = resData.salaryArchiveItemDetail.columns.map(item => {
      let result = {};
      result.title = item;
      if (item == "薪资项目") {
        result.dataIndex = "salaryItem";
        result.key = "salaryItem";
      }
      if (item == "调整前") {
        result.dataIndex = "salaryBefore";
        result.key = "salaryBefore";
      }
      if (item == "调整后") {
        result.dataIndex = "adjustAfter";
        result.key = "adjustAfter";
      }
      return result;
    });

    salaryItemChangeForm.dataSource = resData.salaryArchiveItemDetail.list.map((item, index) => {
      item = { ...item };
      item.key = (index + 1).toString();
      return item;
    });

    let effectiveTime = resData.salaryArchiveItemForm.effectiveTime;
    if (effectiveTime) {
      salaryItemChangeForm.effectiveTime = moment(new Date(effectiveTime)).format("YYYY-MM-DD");
    }

    salaryItemChangeForm.description = resData.salaryArchiveItemForm.description;
    salaryItemChangeForm.adjustReason = resData.salaryArchiveItemForm.adjustReason;
    salaryItemChangeForm.canOperator = resData.canOperator;
    return salaryItemChangeForm;
  };

  // 薪资档案-获取薪资项目调整表单
  @action
  getSalaryItemForm = (id) => {
    return new Promise((resolve, reject) => {
      API.getSalaryItemForm({ salaryArchiveItemId: id }).then(res => {
        if (res.status) {
          this.salaryItemChangeForm = this.convertForm(res.data);
          resolve();
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 调整记录 个税义务人调整列表
  @action
  adjustRecordTaxAgentList = (params) => {
    API.adjustRecordTaxAgentList(params).then(res => {
      if (res.status) {
        this.taxAgentList = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 调整记录 薪资项目调整记录
  @action
  adjustRecordSalaryItemList = (params) => {
    API.adjustRecordSalaryItemList(params).then(res => {
      if (res.status) {
        this.salaryItemList = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // slide 薪资项目列表
  @action
  fetchSingleSalaryItemList = (params) => {
    API.singleSalaryItemList(params).then(res => {
      if (res.status) {
        this.singleSalaryItemList = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // slide 个税义务人列表
  @action
  fetchSingleTaxAgentList = (params) => {
    API.singleTaxAgentList(params).then(res => {
      if (res.status) {
        this.singleTaxAgentList = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 设置当前查看的数据id
  @action
  setCurrentId = (id) => this.currentId = id;

  // 设置编辑个税义务人修改表modal
  @action
  setEditAgentVisible = editAgentVisible => this.editAgentVisible = editAgentVisible;

  // 通过个税义务人编辑进入列表
  @action
  getTaxAgentFormByTaxAgentId = (id) => {
    return new Promise((resolve, reject) => {
      API.getTaxAgentFormBySalaryArchiveTaxAgentId({ salaryArchiveTaxAgentId: id }).then(res => {
        if (res.status) {
          let form = res.data.salaryArchiveTaxAgentForm;
          form.effectiveTime = moment(new Date(form.effectiveTime)).format("YYYY-MM-DD");
          this.salaryArchiveTaxAgentForm = form;
          resolve(form);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  validateSaveSalaryForm = (params) => {
    if (!notNull(params.salaryArchiveId)) {
      message.error("档案id不能为空");
      return false;
    }

    if (!notNull(params.effectiveTime)) {
      message.warning("生效日期不能为空");
      return false;
    }

    if (!notNull(params.adjustReason)) {
      message.warning("调整原因不能为空");
      return false;
    }

    if (!params.salaryArchiveItems || params.salaryArchiveItems.length == 0) {
      message.warning("调整明细不能为空");
      return false;
    }

    for (let i = 0; i < params.salaryArchiveItems.length; i++) {
      if (!notNull(params.salaryArchiveItems[i].salaryItemId)) {
        message.error("薪资项目不能为空");
        return false;
      }
      if (!notNull(params.salaryArchiveItems[i].adjustValue)) {
        message.error("调整后不能为空");
        return false;
      }
    }

    return true;
  };

  // 保存调薪
  @action
  saveSalaryItem = (params) => {
    return new Promise((resolve, reject) => {
      if (!this.validateSaveSalaryForm(params)) {
        reject("校验失败");
        return;
      }
      API.saveSalaryItem(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };
  @action("编辑调薪")
  editSingleSalaryItem = (params) => {
    return new Promise((resolve, reject) => {
      if (!this.validateSaveSalaryForm(params)) {
        reject("校验失败");
        return;
      }
      API.editSingleSalaryItem(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };

  // 调整=薪资项目调整-获取调整前的值
  @action
  getSalaryItemAdjustBeforeValue = (params) => {
    return new Promise((resolve, reject) => {
      API.getSalaryItemAdjustBeforeValue(params).then(res => {
        if (res.status) {
          resolve(res.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject(res.errormsg);
        }
      });
    });
  };

  // 调整-薪资项目-编辑获取表单
  @action
  getSalaryItemFormByItemId = (id) => {
    return new Promise((resolve, reject) => {
      API.getSingleSalaryItemInfo({ id: id }).then(res => {
        if (res.status) {
          this.salaryItemChangeForm = this.convertForm(res.data);
          resolve(this.salaryItemChangeForm);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  @action("停薪")
  stopSalary = (payEndDateStr) => {
    const payload = {
      payEndDateStr,
      salaryArchiveId: this.currentId
    };
    return new Promise((resolve, reject) => {
      API.stopSalary(payload).then(res => {
        if (res.status) {
          message.success("操作成功");
          resolve(res);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };
}
