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

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

const { TableStore } = WeaTableNew;

export class LedgerStore {
  //重构薪资账套
  @observable copyForm = new WeaForm(); // 复制form
  @observable categoryForm = new WeaForm(); // 新增分类form
  @observable searchForm = new WeaForm(); // 查询form
  @observable AARForm = new WeaForm(); // 核算审批规则form
  @observable AARClassifyForm = new WeaForm(); // 核算审批规则分类编辑form

  @action initAARForm = (v) => this.AARForm = new WeaForm();//重置核算审批规则form
  @action initAARClassifyForm = (v) => this.AARClassifyForm = 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 = false; // 数据加载状态
  @observable saveLoading = false; // 数据保存loading状态
  @observable salarySobId = "";
  @observable includeType = 1; // 0：排除、1：包含
  @observable userTableStore = {};
  @observable addUserModalVisible = false;
  @observable
  itemGroups = [
    {
      id: "default",
      name: "未分类",
      items: []
    }
  ];
  @observable salaryItemTableStore = new TableStore();
  @observable empBrowserList = [];
  @observable empFields = [];
  @observable excludeIds = [];

  @observable addCategoryVisible = false; // 薪资项目-添加分类Modal
  @observable ruleOptionList = []; // 第四步规则可选项目列表
  @observable sobItemRuleDataSource = []; // 第四步规则列表
  @observable ledgerRuleList = [];
  @observable baseInfoRequest = {};
  @observable userSelectedList = [];

  // ** 薪资项目 **
  // 添加薪资项目
  @observable addSalaryItemColumns = [];
  @observable addSalaryItemDataSource = [];
  @observable addSalaryItemPageInfo = {}; // 分页信息

  @action
  initSlideData = () => {
    this.salarySobId = "";
    this.includeType = 1;
    this.userTableStore = {};
    this.addUserModalVisible = false;
    this.itemGroups = [
      {
        id: "default",
        name: "未分类",
        items: []
      }
    ];
    this.empBrowserList = [];
    this.empFields = [];
    this.excludeIds = [];
    this.ruleOptionList = [];
    this.sobItemRuleDataSource = []; // 第四步规则列表
    this.ledgerRuleList = [];
    this.baseInfoRequest = {};
    this.userSelectedList = [];
  };
  @observable columns = [];
  @observable pageObj = {}; //列表数据
  @observable dataSource = []; //列表数据

  @action setColumns = columns => (this.columns = columns);

  @action setPageObj = pageObj => (this.pageObj = pageObj);

  @action setDataSource = dataSource => (this.dataSource = dataSource);

  // 设置员工字段
  @action setEmpFields = empFields => (this.empFields = empFields);

  @action
  setUserSelectedList = userSelectedList =>
    (this.userSelectedList = userSelectedList);

  @action
  setBaseInfoRequest = baseInfoRequest =>
    (this.baseInfoRequest = baseInfoRequest);

  @action
  setSobItemRuleDataSource = sobItemRuleDataSource =>
    (this.sobItemRuleDataSource = sobItemRuleDataSource);

  @action
  setAddCategoryVisible = addCategoryVisible =>
    (this.addCategoryVisible = addCategoryVisible);

  @action setExcludeIds = excludeIds => (this.excludeIds = excludeIds);

  @action
  addExcludeIds = id => {
    let excludeIds = [...this.excludeIds];
    excludeIds.push(id);
    this.excludeIds = excludeIds;
  };

  @action
  addEmpFields = fieldId => {
    let sortedIndex = 1;
    if (this.empFields.length > 0) {
      let lastSortedIndex = this.empFields[this.empFields.length - 1]
        .sortedIndex;
      sortedIndex = parseInt(lastSortedIndex) + 1;
    }
    let item = {
      id: sortedIndex,
      fieldId,
      sortedIndex,
      canDelete: true
    };
    let result = [...this.empFields];
    result.push(item);
    this.empFields = result;
    this.userSelectedList = this.empFields.map(item => {
      item = { ...item };
      item.key = item.fieldId;
      if (!item.showname || item.showname == "") {
        this.empBrowserList.map(bitem => {
          if (bitem.key == item.fieldId) {
            item.showname = bitem.showname;
          }
        });
      }
      return item;
    });
  };

  @action
  setItemGroups = itemGroups => {
    itemGroups = itemGroups ? [...itemGroups] : [];
    itemGroups &&
    itemGroups.map(item => {
      if (item.items) {
        item.items &&
        item.items.map(i => {
          i.key = i.id;
        });
      }
    });
    this.itemGroups = itemGroups;
  };

  @action
  addItemGroup = name => {
    if (!name || name == "" || name.trim() == "") {
      message.warning("分类名称不能为空");
      return;
    }
    let itemGroups = [...this.itemGroups];
    let flag = false;
    itemGroups.map(item => {
      if (item.name == name) {
        flag = true;
      }
    });
    if (flag) {
      message.warning("分类已存在");
      return;
    }
    let item = { name, items: [], id: new Date().getTime().toString().substring(0, 13) };
    itemGroups.unshift(item);
    this.setItemGroups(itemGroups);
    this.addCategoryVisible = false;
  };

  @action
  addItemsToGroup = (title, list) => {
    let itemGroups = [...this.itemGroups];
    itemGroups.map(item => {
      if (item.name == title) {
        item.items = item.items ? item.items.concat(list) : list;
      }
    });

    this.setItemGroups(itemGroups);
  };

  @action
  addCategoryList = item => {
    let list = [...this.categoryList];
    list.push(item);
    this.categoryList = list;
  };

  @action
  removeCategoryList = item => {
    let list = [...this.categoryList];
    list.filter(i => item.name != i.name);
    this.categoryList = list;
  };

  @action
  setAddUserModalVisible = addUserModalVisible =>
    (this.addUserModalVisible = addUserModalVisible);

  @action
  setUserTableStore = userTableStore => (this.userTableStore = userTableStore);

  @action setIncludeType = includeType => (this.includeType = includeType);

  @action setSalarySobId = salarySobId => (this.salarySobId = salarySobId);

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

    this.setBaseInfoRequest({
      name: "",
      taxableItems: "1",
      salaryCycleType: "3",
      salaryCycleFromDay: "1",
      taxCycleType: "3",
      attendCycleType: "3",
      attendCycleFromDay: "1",
      socialSecurityCycleType: "3",
      description: ""
    });
  };

  @action
  initBaseInfoRequest = () => {
    this.setBaseInfoRequest({
      name: "",
      taxableItems: "1",
      salaryCycleType: "3",
      salaryCycleFromDay: "1",
      taxCycleType: "3",
      attendCycleType: "3",
      attendCycleFromDay: "1",
      socialSecurityCycleType: "3",
      description: ""
    });
  };

  // 获得高级搜索表单数据
  @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.errormsg || "接口调用失败！");
        }
      })
    );
  };

  // 渲染table数据
  @action
  getTableDatas = params => {
    this.loading = true;
    API.getLedgerList(params).then(
      action(({ status, data, errormsg }) => {
        this.loading = false;
        if (status) {
          // 接口请求成功/失败处理
          const { columns, list, total, pageNum: current, pageSize } = data;
          this.setColumns(columns);
          this.setDataSource(list);
          this.setPageObj({
            total,
            current,
            pageSize
          });
        } else {
          this.setDataSource([]);
          this.setPageObj({
            ...this.pageObj,
            total: 0
          });
          message.error(errormsg || "接口调用失败！");
        }
      })
    );
  };

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

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

  // 复制
  @action
  doCopy = params => {
    return new Promise((resolve, reject) => {
      API.duplicateLedger({ ...params }).then(res => {
        if (res.status) {
          message.success("复制成功");
          this.getTableDatas({});
          resolve();
        } else {
          message.error(res.errormsg || "复制失败");
          reject();
        }
      });
    });
  };

  //启用/禁用薪资帐套
  @action
  changeLedgerStatus = (id, disable) => {
    API.changeLedgerStatus({ id, disable }).then(res => {
      if (res.status) {
        this.getTableDatas({});
        message.success("修改成功");
      } else {
        message.error(res.errormsg || "修改失败");
      }
    });
  };

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

    if (!notNull(params.taxableItems)) {
      message.warning("薪资类型不能为空");
      return false;
    }

    if (!notNull(params.salaryCycleType)) {
      message.warning("薪资周期不能为空");
      return false;
    }

    if (!notNull(params.salaryCycleFromDay)) {
      message.warning("薪资周期不能为空");
      return false;
    }

    if (!notNull(params.taxCycleType)) {
      message.warning("税款所属期不能为空");
      return false;
    }

    if (!notNull(params.attendCycleType)) {
      message.warning("考勤周期不能为空");
      return false;
    }

    if (!notNull(params.attendCycleFromDay)) {
      message.warning("考勤周期不能为空");
      return false;
    }

    if (!notNull(params.socialSecurityCycleType)) {
      message.warning("福利台账月份不能为空");
      return false;
    }

    return true;
  }

  //保存薪资帐套基本信息
  @action
  saveLedgerBasic = params => {
    return new Promise((resolve, reject) => {
      if (!this.validateBaseFrom(params)) {
        reject("保存失败");
      }
      this.saveLoading = true;
      API.saveLedgerBasic(params).then(res => {
        this.saveLoading = false;
        if (res.status) {
          this.salarySobId = res.data;
          resolve();
          this.getTableDatas({});
          message.success("保存成功");
        } else {
          reject(res.errormsg || "保存失败");
          message.error(res.errormsg || "保存失败");
        }
      });
    });
  };

  //删除薪资帐套
  @action
  deleteLedger = params => {
    API.deleteLedger(params).then(res => {
      if (res.status) {
        message.success("删除成功");
        this.getTableDatas({});
      } else {
        message.error(res.errormsg || "删除失败");
      }
    });
  };

  validateLedgerPersonRange(params) {
    if (!notNull(params.includeType)) {
      message.warning("对象类型不能为空");
      return false;
    }

    if (!notNull(params.targetParams)) {
      message.warning("对象类型不能为空");
      return false;
    }

    if (!notNull(params.employeeStatus)) {
      message.warning("选择员工状态不能为空");
      return false;
    }

    if (_.every(params.targetParams, it => !notNull(it.targetId))) {
      message.warning("对象类型不能为空");
      return false;
    }
    return true;
  }

  //保存薪资帐套人员范围
  @action
  saveLedgerPersonRange = params => {
    if (!this.validateLedgerPersonRange(params)) {
      return;
    }
    API.saveLedgerPersonRange(params).then(res => {
      if (res.status) {
        if (this.includeType == 1) {
          this.getLedgerPersonRangeInclude({ salarySobId: this.salarySobId });
        } else {
          this.getLedgerPersonRangeExclude({ salarySobId: this.salarySobId });
        }
        this.addUserModalVisible = false;
        message.success("添加成功");
      } else {
        message.error(res.errormsg || "添加失败");
      }
    });
  };

  //薪资帐套人员范围（包含）列表
  getLedgerPersonRangeInclude = params => {
    this.loading = true;
    API.getLedgerPersonRangeInclude(params).then(res => {
      this.loading = false;
      if (res.status) {
        this.setUserTableStore(res.data);
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  //薪资帐套人员范围（排除）列表
  getLedgerPersonRangeExclude = params => {
    this.loading = true;
    API.getLedgerPersonRangeExclude(params).then(res => {
      this.loading = false;
      if (res.status) {
        this.setUserTableStore(res.data);
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  //删除薪资帐套人员范围
  deleteLedgerPersonRange = params => {
    API.deleteLedgerPersonRange(params).then(res => {
      if (res.status) {
        if (this.includeType == 1) {
          this.getLedgerPersonRangeInclude({ salarySobId: this.salarySobId });
        } else {
          this.getLedgerPersonRangeExclude({ salarySobId: this.salarySobId });
        }
        message.success("删除成功");
      } else {
        message.error(res.errormsg || "删除失败");
      }
    });
  };

  // 薪资项目可选列表
  @action
  listSalaryItem = (searchValue = "", current = 1) => {
    let excludeIds = [];
    this.itemGroups &&
    this.itemGroups.map(item => {
      item.items &&
      item.items.map(i => {
        excludeIds.push(i.salaryItemId);
      });
    });
    this.loading = true;
    API.listSalaryItem({ name: searchValue, excludeIds, current }).then(res => {
      if (res.status) {
        if (res.data.list) {
          this.addSalaryItemDataSource = res.data.list.map(item => {
            item = { ...item };
            item.key = item.id;
            return item;
          });
        } else {
          this.addSalaryItemDataSource = [];
        }

        this.addSalaryItemColumns = res.data.columns;
        this.addSalaryItemPageInfo = res.data;
        // this.salaryItemTableStore.getDatas(res.data.datas);
      } else {
        message.error(res.errormsg || "获取数据失败");
      }
      this.loading = false;
    });
  };

  @action
  empFieldList = () => {
    API.empFieldList().then(res => {
      if (res.status) {
        this.empBrowserList = res.data.map(item => {
          return { showname: item.name, key: item.id, selected: false };
        });
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  @action
  saveLedgerItem = () => {
    let itemGroups = [...this.itemGroups];
    itemGroups = itemGroups
      .map(item => {
        let result = { ...item };
        if (result.items) {
          result.items = result.items.map((i, index) => ({
            canDelete: i.canDelete,
            salaryItemId: i.salaryItemId,
            sortedIndex: index + 1,
            formulaId: i.formulaId,
            itemHide: i.itemHide || "0"
          }));
          return result;
        }
      })
      .filter(item => item);

    let params = {
      salarySobId: this.salarySobId,
      empFields: _.map(this.userSelectedList, (it, idx) => ({ ...it, sortedIndex: idx })),
      itemGroups: itemGroups.filter(item => item.id != "default"),
      items: itemGroups.filter(item => item.id == "default")[0].items
    };
    return new Promise((resolve, reject) => {
      this.saveLoading = true;
      API.saveLedgerItem(params).then(res => {
        this.saveLoading = false;
        if (res.status) {
          resolve();
          message.success("保存成功");
        } else {
          reject();
          message.error(res.errormsg || "保存失败");
        }
      });
    });
  };

  // 调薪计薪规则可选的薪资项目列表
  @action
  listSalarySobItem = () => {
    let params = {
      salarySobId: this.salarySobId,
      excludeSalaryItemIds: this.sobItemRuleDataSource.map(
        item => item.salaryItemId
      )
    };
    return new Promise((resolve, reject) => {
      API.listSalarySobItem(params).then(res => {
        if (res.status) {
          this.ruleOptionList = res.data.map(item => {
            return {
              key: item.salaryItemId.toString(),
              showname: item.salaryItemName,
              selected: false
            };
          });
          resolve();
        } else {
          reject();
          message.error(res.errormsg || "获取失败");
        }
      });
    });
  };

  // 调薪计薪规则保存
  @action
  saveAdjustmentRule = () => {
    let params = {
      salarySobId: this.salarySobId,
      ruleParams: this.sobItemRuleDataSource
    };
    return new Promise((resolve, reject) => {
      this.saveLoading = true;
      API.saveAdjustmentRule(params).then(res => {
        this.saveLoading = false;
        if (res.status) {
          resolve();
          message.success("保存成功");
        } else {
          reject();
          message.error(res.errormsg || "获取失败");
        }
      });
    });
  };

  @action
  listAdjustmentRule = () => {
    let params = {
      salarySobId: this.salarySobId
    };
    API.listAdjustmentRule(params).then(res => {
      if (res.status) {
        this.sobItemRuleDataSource = res.data;
      }
    });
  };

  // 保存薪资帐套校验规则
  @action
  saveLedgerRule = params => {
    params.salarySobId = this.salarySobId;
    API.saveLedgerRule(params).then(res => {
      if (res.status) {
        this.getLedgerRuleList();
        message.success("保存成功");
      } else {
        message.error(res.errormsg || "保存失败");
      }
    });
  };

  //薪资帐套校验规则列表
  @action
  getLedgerRuleList = (name = "") => {
    let params = {
      salarySobId: this.salarySobId,
      name
    };
    API.getLedgerRuleList(params).then(res => {
      if (res.status) {
        this.ledgerRuleList = res.data;
      } else {
        message.error(res.errormsg || "获取数据失败");
      }
    });
  };

  //删除薪资帐套校验规则
  @action
  deleteLedgerRule = ids => {
    API.deleteLedgerRule(ids).then(res => {
      if (res.status) {
        message.success("删除成功");
        this.getLedgerRuleList();
      } else {
        message.error(res.errormsg || "删除失败");
      }
    });
  };

  // 获取基本信息
  @action
  getLedgerBasicForm = () => {
    API.getLedgerBasicForm({ id: this.salarySobId }).then(res => {
      if (res.status) {
        let basicForm = res.data.basicForm;
        Object.keys(basicForm).map(key => {
          if (basicForm[key] || typeof basicForm[key] === "boolean") {
            basicForm[key] = basicForm[key].toString();
          }
        });
        this.baseInfoRequest = basicForm;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  //薪资帐套薪资项目详情
  @action
  getLedgerItemForm = () => {
    API.getLedgerItemForm({ salarySobId: this.salarySobId }).then(res => {
      if (res.status) {
        this.empFields = res.data.empFields;
        let itemGroups = res.data.itemGroups;
        let defaultItems = {
          id: "default",
          name: "未分类",
          items: res.data.items
        };
        itemGroups.push(defaultItems);
        this.setItemGroups(itemGroups);
        API.empFieldList().then(ires => {
          if (res.status) {
            this.empBrowserList = ires.data.map(item => {
              return { showname: item.name, key: item.id, selected: false };
            });
            this.userSelectedList = this.empFields.map(item => {
              item = { ...item };
              item.key = item.fieldId;
              this.empBrowserList.map(bitem => {
                if (bitem.key == item.fieldId) {
                  item.showname = bitem.showname;
                }
              });
              return item;
            });
          } else {
            message.error(res.errormsg || "获取失败");
          }
        });
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };
}
