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

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

const { TableStore } = WeaTableNew;

export class SalaryItemStore {
  @observable salarySetform = new WeaForm(); //同步薪资账套form
  @observable itemsForm = new WeaForm(); //自定义薪资项目form
  @action initItemsForm = () => this.itemsForm = new WeaForm();


  @observable tableStore = new TableStore(); // new table
  @observable sysListTableStore = new TableStore();
  @observable form = new WeaForm(); // nrew 一个form
  @observable condition = []; // 存储后台得到的form数据
  @observable hasRight = true; // 判断用户是有权限查看当前页面： 没有权限渲染无权限页面，有权限渲染数据
  @observable showSearchAd = false; // 高级搜索面板显示
  @observable loading = true; // 数据加载状态
  @observable saveLoading = false; // 数据保存状态
  @observable systemItemVisible = false;
  @observable deleteTableStore = new TableStore(); // 批量删除
  @observable deleteItemVisible = false;  // 删除Modal
  @observable editSlideVisible = false; // 新建修改设置
  @observable request = {
    name: "",
    useDefault: 0,
    hideDefault: 0,
    useInEmployeeSalary: 0,
    systemType: 0,
    roundingMode: "1",
    pattern: "2",
    valueType: 1,
    dataType: "number",
    description: "",
    sharedType: "0",
    taxAgentIds: "",
    defaultValue: ""
  };

  @observable tableDataSource = []; // 主列表
  @observable tableColumns = []; // 主列表列
  @observable pageInfo = {}; // 分页数据

  // 可以删除的项目
  @observable canDeleteList = [];

  // ** 公式 **
  // 类型列表
  @observable searchGroup = [];
  // 字段列表
  @observable searchFields = [];
  // 公式详情
  @observable formulaDetail = {};

  // Modal
  @observable modalLoading = true;

  // 设置字段列表
  @action
  setSearchFields = (searchFields) => {
    this.searchFields = searchFields;
  };


  @action
  initRequest = () => this.request = {
    name: "",
    useDefault: 0,
    hideDefault: 0,
    useInEmployeeSalary: 0,
    systemType: 0,
    roundingMode: "1",
    pattern: "2",
    valueType: "1",
    dataType: "number",
    description: "",
    sharedType: "0",
    taxAgentIds: "",
    defaultValue: ""
  };

  @action
  setRequest = request => this.request = request;

  @action
  setEditSlideVisible = editSlideVisible => this.editSlideVisible = editSlideVisible;

  @action
  setDeleteItemVisible = deleteItemVisible => this.deleteItemVisible = deleteItemVisible;

  @action
  setSystemItemVisible = systemItemVisible => {
    this.systemItemVisible = systemItemVisible;
    this.sysListTableStore = new TableStore();
  };

  // 存储分页以及关键字信息
  @action
  setPageInfo = (pageInfo) => this.pageInfo = { ...this.pageInfo, ...pageInfo };

  // 渲染table数据
  @action
  getTableDatas = (params) => {
    this.loading = true;
    return new Promise((resolve, reject) => {
      API.getItemList({ ...params, ...this.pageInfo }).then(action(res => {
        this.loading = false;
        if (res.status) { // 接口请求成功/失败处理
          this.tableDataSource = res.data.list;
          this.tableColumns = res.data.columns;
          resolve(res.data);
        } else {
          message.error(res.errormsg || "接口调用失败！");
          reject();
        }
      })).catch(() => this.loading = false);
    }).catch(() => this.loading = false);
  };

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

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

  // 薪资项目-系统薪资项目列表
  @action
  formulaDatasourceList = () => {
    return API.formulaDatasourceList();
  };

  // 薪资项目-系统薪资项目列表
  @action
  getSysItemList = (params) => {
    API.getSysItemList(params).then(res => {
      if (res.status) { // 接口请求成功/失败处理
        this.sysListTableStore.getDatas(res.data.datas); // table 请求数据
      } else {
        message.error(res.errormsg || "接口调用失败！");
      }
    });
  };

  //薪资项目-添加系统薪资项目
  @action
  saveSysItem = () => {
    let ids = toJS(this.sysListTableStore.selectedRowKeys);
    if (ids.length == 0) {
      message.warning("未选择任何条目");
      return;
    }
    this.saveLoading = true;
    API.saveSysItem(ids).then(res => {
      this.saveLoading = false;
      if (res.status) {
        this.setSystemItemVisible(false);
        this.getTableDatas({});
        message.success("添加成功");
      } else {
        message.error(res.errormsg || "添加失败");
      }
    });
  };

  //薪资项目-薪资项目详情
  @action
  getItemForm = (id) => {
    return new Promise((resolve, reject) => {
      API.getItemForm({ id }).then(res => {
        if (res.status) {
          let data = res.data;
          Object.keys(data).map(key => {
            if (!_.isNil(data[key])) {
              data[key] = data[key].toString();
            }
          });
          this.setRequest(data);
          resolve();
        } else {
          message.error(res.errormsg || "获取失败");
          reject(res);
        }
      });
    });
  };

  // 对象值转string
  convertToString(data) {
    Object.keys(data).map(k => {
      if (typeof (data[k]) == "number") {
        data[k] = data[k].toString();
      }
    });
    return data;
  }

  //薪资项目-批量删除列表
  @action
  deleteItemList = (params) => {
    API.deleteItemList(params).then(res => {
      if (res.status) {
        this.deleteTableStore.getDatas(res.data.datas);
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  //薪资项目-批量删除薪资项目
  @action
  deleteItem = (ids) => {
    if (ids.length == 0) {
      message.warning("未选择任何条目");
      return;
    }
    this.deleteItemRequest(ids);
  };

  @action
  deleteItemRequest = (ids) => {
    return new Promise((resolve, reject) => {
      API.deleteItem(ids).then(res => {
        if (res.status) {
          this.deleteItemVisible = false;
          message.success("删除成功");
          resolve();
        } else {
          message.error(res.errormsg || "删除失败");
          reject();
        }
      });
    });
  };

  validateForm(params) {
    if (!notNull(params.name)) {
      message.warning("名称不能为空");
      return false;
    }

    if (!notNull(params.dataType)) {
      message.warning("字段类型不能为空");
      return false;
    }

    if (!notNull(params.roundingMode)) {
      message.warning("舍入规则不能为空");
      return false;
    }

    if (!notNull(params.pattern)) {
      message.warning("保留小数位不能为空");
      return false;
    }

    if (!notNull(params.valueType)) {
      message.warning("取值方式不能为空");
      return false;
    }

    if ((params.valueType == 2 || params.valueType == 3) && !notNull(params.formulaId)) {
      message.warning("公式不能为空");
      return false;
    }

    if (params.sharedType == 1 && !notNull(params.taxAgentIds)) {
      message.warning("可见性范围不能为空");
      return false;
    }
    return true;
  }

  //薪资项目-新增薪资项目
  @action
  saveItem = (params, continueFlag) => {
    return new Promise((resolve, reject) => {
      const { valueType, formulaId, originFormulaContent, originSqlContent, ...extra } = params;
      let payload = { ...extra, valueType };
      if (valueType === "1") {
        payload = {
          ...payload,
          formulaContent: "",
          formulaId: "",
          originSqlContent: "",
          originFormulaContent: ""
        };
      } else if (valueType === "2") {
        payload = {
          ...payload,
          formulaContent: originFormulaContent ? originFormulaContent : "",
          formulaId: originFormulaContent ? formulaId : "",
          originSqlContent: "",
          originFormulaContent
        };
      } else if (valueType === "3") {
        payload = {
          ...payload,
          formulaContent: originSqlContent ? originSqlContent : "",
          formulaId: originSqlContent ? formulaId : "",
          originFormulaContent: "",
          originSqlContent
        };
      }
      if (!this.validateForm(payload)) return;
      API.saveItem(params).then(res => {
        if (res.status) {
          if (!continueFlag) {
            this.editSlideVisible = false;
          }
          ((!params.id && continueFlag) || !continueFlag) && this.initRequest();
          message.success("保存成功");
          resolve();
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });
  };

  // 获取公式变量类型
  @action
  salaryAcctImportTemplateParam = (params = {}) => {
    API.formualSearchGroup(params).then(res => {
      if (res.status) {
        this.searchGroup = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 获取公式变量字段
  @action
  formualSearchField = (sourceId, params = {}) => {
    API.formualSearchField({ sourceId, ...params }).then(res => {
      if (res.status) {
        this.searchFields = res.data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  // 保存公式
  @action
  saveFormual = (params) => {
    return new Promise((resolve, reject) => {
      API.saveFormual(params).then(res => {
        if (res.status) {
          message.success("保存成功");
          resolve(res.data);
        } else {
          message.error(res.errormsg || "保存失败");
          reject();
        }
      });
    });

  };

  // 根据id获取formual
  @action
  detailFormual = (params) => {
    return new Promise((resolve, reject) => {
      API.detailFormual(params).then(res => {
        if (res.status) {
          this.formulaDetail = res.data;
          resolve(res.data);
        } else {
          message.error(res.errormsg || "获取失败");
          reject();
        }
      });
    });
  };

  // 获取可以删除的列表
  @action
  listCanDelete = (params = {}) => {
    this.modalLoading = true;
    API.listCanDelete(params).then(res => {
      if (res.status) {
        let data = res.data;
        if (res.data.list && res.data.list.length > 0) {
          data.list = res.data.list.map(item => {
            item = { ...item };
            item.key = item.id;
            return item;
          });
        }
        this.canDeleteList = data;
      } else {
        message.error(res.errormsg || "获取失败");
      }
      this.modalLoading = false;
    });
  };
}
