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

import * as API from "../apis/mySalaryBenefits";

const { watermark } = WeaTools;
const { LogStore } = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;

export class MySalaryStore {
  @observable tableStore = new TableStore(); // new table
  @observable form = new WeaForm(); // nrew 一个form
  @observable pwdForm = new WeaForm(); // new 一个密码验证form
  @observable condition = []; // 存储后台得到的form数据
  @observable hasRight = false; // 判断用户是有权限查看当前页面： 没有权限渲染无权限页面，有权限渲染数据
  @observable showSearchAd = false; // 高级搜索面板显示
  @observable loading = true; // 数据加载状态
  @observable tabIndex = 0;  // tab选中坐标
  @observable params = {};  // 搜索条件

  // 工资单列表
  @observable myBillDataSource = [];
  @observable myBillTableStore = new TableStore();

  // 工资单详情
  @observable mySalaryBill = {};

  // 调薪记录
  @observable recordListColumns = [];
  @observable recordListDataSource = [];
  @observable recordListPageInfo = {};
  @observable myBillPageInfo = {};

  @action clear = () => {
    this.loading = true;
    this.hasRight = false;
  };
  @action clearLoading = () => {
    this.loading = false;
    this.hasRight = false;
  };
  @action setInitEmVerify = () => {
    this.loading = false;
    this.hasRight = true;
  };
  @action setMySalaryBill = (mySalaryBill) => {
    this.mySalaryBill = mySalaryBill;
  };
  @action init = async (isRoot = true, callback) => {
    this.clear();
    //1.check is need second verify
    if (window.doCheckSecondaryVerify4ec) {
      window.doCheckSecondaryVerify4ec({ mouldCode: "HRM", itemCode: "SALARY" }, (data) => this.getData({
        ...data,
        isRoot, callback
      }));
    } else {
      //4.loaddata
      this.getData({ status: "1", token: "", isRoot, callback });
    }
  };

  @action
  getData = async (params = {}) => {
    if (_.isEmpty(params)) return;
    const { status, isRoot, token, callback } = params;
    if (status == "1") {
      // Object.assign(this._reqParams, { token });
      // this.getFormData({ viewAttr: 1 });
      this.hasRight = true;
      isRoot && this.mySalaryBillList([moment().startOf("year").format("YYYY-MM"), moment().format("YYYY-MM")]);
      callback && callback();
    } else {
      this.hasRight = false;
    }
    this.loading = false;
  };

  @action
  initParams = () => {
    let month = moment().format("YYYY-MM");
    this.params = { startMonth: month, endMonth: month };
    return this.params;
  };

  @action
  setTabIndex = index => {
    this.tabIndex = index;
    this.getTableDatas(index);
  };

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

  // 获得高级搜索表单数据
  @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;
    const formParams = this.form.getFormParams() || {};
    params = params || formParams;
    switch (params) {
      case 0:
        // 工资单
        API.mySalaryBillList(param);
        break;
    }
    API.getTableDatas(params).then(action(res => {
      if (res.api_status) { // 接口请求成功/失败处理
        this.tableStore.getDatas(res.datas); // table 请求数据
        this.hasRight = res.hasRight;
      } else {
        message.error(res.errormsg || "接口调用失败！");
      }
      this.loading = false;
    }));
  };

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

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

  // 我的工资单列表
  @action
  mySalaryBillList = (salaryYearMonth = [], params = {}) => {
    this.loading = true;
    API.mySalaryBillList({ salaryYearMonth, ...params }).then(res => {
      if (res.status) {
        this.myBillDataSource = res.data.datas;
        this.myBillTableStore.getDatas(res.data.dataKey.datas);
        this.myBillPageInfo = res.data.pageInfo;
        this.loading = false;
      } else {
        message.error(res.errormsg || "获取失败");
        this.loading = false;
      }
    });
  };

  // 我的工资单详情
  @action
  getMySalaryBill = (salaryInfoId) => {
    const payload = Object.prototype.toString.call(salaryInfoId) === "[object Number]" ? { salaryInfoId } : { ...salaryInfoId };
    return new Promise((resolve, reject) => {
      API.mySalaryBill(payload).then(res => {
        if (res.status) {
          this.mySalaryBill = res.data;
          resolve(res.data);
          const { salaryTemplate } = res.data;
          const { salaryWatermark } = salaryTemplate;
          if (watermark && salaryWatermark) {
            const { wmSetting, watermarkStatus } = JSON.parse(salaryWatermark);
            if (!watermarkStatus) return;
            const {
              wmText,
              wmHeight: height,
              wmWidth: width,
              wmNoTransparent,
              wmRotate,
              wmImg,
              wmClassify
            } = wmSetting;
            if (wmClassify === "text") {
              watermark({
                text: wmText,
                width,
                height,
                src: "",
                rotate: `-${wmRotate || 15}`,
                alpha: wmNoTransparent / 100 || 0.15,
                interval: 2000,
                intervalCheck: true,
                clickCheck: true
              });
            } else {
              watermark({
                text: "",
                width,
                height,
                src: wmImg[0].imgSrc,
                rotate: `-${wmRotate || 15}`,
                alpha: wmNoTransparent / 100 || 0.15,
                interval: 2000,
                intervalCheck: true,
                clickCheck: true
              });
            }
          }
        } else {
          message.error(res.errormsg || "获取失败");
          reject("获取失败");
        }
      });
    });
  };

  @action initRecordData = async (callback) => {
    this.clear();
    //1.check is need second verify
    if (window.doCheckSecondaryVerify4ec) {
      window.doCheckSecondaryVerify4ec({ mouldCode: "HRM", itemCode: "SALARY" }, (data) => this.getRecordData({
        ...data, callback
      }));
    } else {
      this.getRecordData({ status: "1", token: "", callback });
    }
  };

  @action
  getRecordData = async (params = {}) => {
    if (_.isEmpty(params)) return;
    const { status, callback, token } = params;
    if (status == "1") {
      // Object.assign(this._reqParams, { token });
      // this.getFormData({ viewAttr: 1 });
      this.hasRight = true;
      !callback && this.getRecordList();
      callback && callback();
    } else {
      this.hasRight = false;
    }
    this.loading = false;
  };

  @action
  getRecordList = (params = {}) => {
    API.recordList(params).then(res => {
      if (res.status) {
        this.recordListColumns = res.data.columns;
        this.recordListDataSource = res.data.list ? res.data.list : [];
        this.recordListPageInfo = res.data;
      }
    });
  };

}
