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

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

const { TableStore } = WeaTableNew;

export class ProgrammeStore {
  //lys-表单初始化(方案查询表单)
  @observable planSearchForm = new WeaForm();
  @observable planForm = new WeaForm(); //方案-新增编辑Form
  @action initPlanForm = () => this.planForm = new WeaForm();//方案-初始化新增编辑Form
  @observable planCopyForm = new WeaForm(); //方案-复制Form
  @action initPlanCopyForm = () => this.planCopyForm = new WeaForm();//方案-初始化复制Form
  @observable planCustomForm = new WeaForm(); //方案-新建编辑自定义方案Form
  @action initPlanCustomForm = () => this.planCustomForm = new WeaForm();//方案-初始化新建编辑自定义方案Form
  @observable hasBeenModify = false; //社保福利方案-员工薪资档数据-是否修改过
  @action setHasBeenModify = (v) => this.hasBeenModify = v;//设置社保福利方案-员工薪资档数据


  @observable tableStore = new TableStore(); // new table
  @observable condition = []; // 存储后台得到的form数据
  @observable hasRight = true; // 判断用户是有权限查看当前页面： 没有权限渲染无权限页面，有权限渲染数据
  @observable showSearchAd = false; // 高级搜索面板显示
  @observable loading = true; // 数据加载状态
  @observable deleteLoading = false; // 删除加载状态
  @observable selectedKey = "SOCIAL_SECURITY";
  @observable customSelectkey = "";
  @observable defaultPersonDataSource = []; // 默认新增列表DataSource
  @observable defaultCompanyDataSource = [];
  @observable requestParams = {
    schemeName: "",
    remarks: "",
    paymentArea: "1",
    sharedType: "",
    taxAgentIds: ""
  };
  @observable form = new WeaForm();
  @observable formCondition = []; // 存储后台得到的form数据
  @observable customNewVisible = false;
  @observable customRequest = {};

  // 福利方案列表
  @observable tableDataSource = [];
  @observable tableColumns = [];
  @observable tablePageInfo = {};


  @action
  setCustomSelectkey = customSelectkey => this.customSelectkey = customSelectkey;

  @action
  setCustomRequest = customRequest => this.customRequest = customRequest;

  @action
  setCustomNewVisible = customNewVisible => this.customNewVisible = customNewVisible;

  @action
  setRequestParams = requestParams => this.requestParams = requestParams;

  @action
  setDefaultPersonDataSource = defaultPersonDataSource => this.defaultPersonDataSource = defaultPersonDataSource;

  @action
  setDefaultCompanyDataSource = defaultCompanyDataSource => this.defaultCompanyDataSource = defaultCompanyDataSource;

  @action
  initSlideParms = () => {
    this.requestParams = {
      schemeName: "",
      remarks: "",
      paymentType: "SCHEME_TOWN",
      sharedType: "",
      taxAgentIds: ""
    };
    this.defaultPersonDataSource = [];
    this.defaultCompanyDataSource = [];
  };

  @action
  setSelectedKey = selectedKey => this.selectedKey = selectedKey;

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

  // 获得高级搜索表单数据
  // @action
  // getCondition = () => {
  //   API.getForm().then(action(res => {
  //     if (res.status) { // 接口请求成功/失败处理
  //       this.condition = res.condition;
  //       this.form.initFormFields(res.condition); // 渲染高级搜索form表单
  //     } else {
  //       message.error(res.msg || '接口调用失败！')
  //     }
  //   }));
  // }

  // 渲染table数据
  @action
  getTableDatas = (selectKey = "SOCIAL_SECURITY", params) => {
    this.loading = true;
    API.getTable({ ...params, ...this.planSearchForm.getFormParams(), welfareTypeEnum: selectKey })
      .then(action(res => {
        if (res.status) { // 接口请求成功/失败处理
          // this.tableStore.getDatas(res.data.datas); // table 请求数据
          this.tableDataSource = res.data.list ? res.data.list : [];
          this.tableColumns = res.data.columns;
          this.tablePageInfo = res.data;
        } else {
          message.error(res.errormsg || "接口调用失败！");
        }
        this.loading = false;
      }));
  };


  // 渲染自定义福利
  @action
  getCustomCategoryList = (selectKey = "", params) => {
    this.loading = true;
    const formParams = this.form.getFormParams() || {};
    params = params || formParams;
    params.welfareTypeEnum = selectKey;
    API.getCustomCategoryList(params).then(action(res => {
      if (res.status) { // 接口请求成功/失败处理
      } else {
        message.error(res.errormsg || "接口调用失败！");
      }
      this.loading = false;
    }));
  };

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

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

  // 获取form, 获取获取详情
  @action getForm = (params) => {
    return new Promise((resolve, reject) => {
      API.getForm(params).then(res => {
        if (res.status) {
          let resultList = res.data.form.schemeDetailList;
          resultList = _.map(resultList, it => ({
            ...it,
            rententionRule: it.rententionRule ? it.rententionRule : "2",
            validNum: !_.isNil(it.validNum) ? it.validNum : "2"
          }));
          this.defaultPersonDataSource = resultList.filter(item => item.paymentScope == "个人");
          this.defaultCompanyDataSource = resultList.filter(item => item.paymentScope == "公司");
          let defaultRequest = {
            schemeName: "",
            remarks: "",
            paymentArea: "1"
          };
          this.requestParams = { ...defaultRequest, ...res.data.form.schemeBatch };
          resolve();
        } else {
          reject();
        }
      }).catch(() => reject());
    });
  };

  valideForm(params) {
    if (!notNull(params.insuranceScheme.paymentType)) {
      message.warning("缴纳类型不能为空");
      return false;
    }

    if (!notNull(params.insuranceScheme.schemeName)) {
      message.warning("方案名称不能为空");
      return false;
    }

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

  @action createScheme = (params) => {
    params.insuranceScheme.paymentArea = params.insuranceScheme.paymentType;
    return new Promise((resolve, reject) => {
      if (!this.valideForm(params)) {
        reject("新建失败");
        return;
      }
      API.createScheme(params).then(res => {
        if (res.status) {
          resolve(res);
          message.success("新建成功");
          this.getTableDatas(this.selectedKey);
        } else {
          reject("新建失败");
          message.error(res.errormsg || "新建失败");
        }
      });
    });
  };

  @action updateScheme = (params) => {
    params.insuranceScheme.paymentArea = params.insuranceScheme.paymentType;
    return new Promise((resolve, reject) => {
      if (!this.valideForm(params)) {
        reject("新建失败");
        return;
      }
      API.updateScheme(params).then(res => {
        if (res.status) {
          resolve(res);
          message.success("更新成功");
          this.getTableDatas(this.selectedKey);
        } else {
          reject("更新失败");
          message.error(res.errormsg || "更新失败");
        }
      });
    });
  };

  @action("复制福利方案")
  copyScheme = (params) => {
    return new Promise((resolve, reject) => {
      API.copyScheme(params).then(res => {
        if (res.status) {
          resolve("复制成功");
          message.success("复制成功");
          this.getTableDatas(this.selectedKey);
        } else {
          reject(res.errormsg || "复制失败");
          message.error(res.errormsg || "复制失败");
        }
      });
    });
  };
  @action("删除社保数据")
  deleteScheme = (params) => {
    this.deleteLoading = true;
    API.deleteScheme(params).then(res => {
      this.deleteLoading = false;
      if (res.status) {
        message.success("刪除成功");
        this.getTableDatas(this.selectedKey);
      } else {
        message.error(res.errormsg || "刪除失败");
      }
    });
  };

  @action getCustomForm = (params) => {
    API.getCustomCategoryForm(params).then(res => {
      if (res.status) {
        let condition = res.data.item;
        let items = Object.keys(condition).map(item => {
          return condition[item];
        });
        let fieldCondtion = items;
        this.formCondition = fieldCondtion;
      } else {
        message.error(res.errormsg || "获取失败");
      }
    });
  };

  validateCustomRequest() {
    let flag = true;
    try {
      this.formCondition.forEach(item => {
        if (item.rules == "required") {
          if (!notNull(this.customRequest[item.domkey[0]])) {
            message.warning(item.label + "不能为空");
            throw new Error(item.label + "不能为空");
          }
        }
      });
    } catch (e) {
      flag = false;
    }
    return flag;
  }

  // 新增自定义福利
  @action createSICategory = (params) => {
    return new Promise((resolve, reject) => {
      if (!this.validateCustomRequest()) {
        reject();
        return;
      }
      API.createSICategory({ ...params, paymentScope: params.paymentScope.split(",") }).then(res => {
        if (res.status) {
          message.success("新增成功");
          resolve();
        } else {
          reject();
          message.error(res.errormsg || "新增失败");
        }
      }).catch(() => {
        message.error("新增失败");
      });
    });

  };

  // 自定义福利启用、停用
  @action
  updateCustomCategoryStatus = (id, isUse) => {
    let params = {
      id,
      isUse: isUse ? 1 : 0
    };
    API.updateCustomCategoryStatus(params).then(res => {
      if (res.status) {
        message.success("修改成功");
        this.getCustomCategoryList();
      } else {
        message.error(res.errormsg || "修改失败");
      }
    });
  };

  // 自定义福利编辑
  @action
  updateCustomCategory = (params) => {
    return new Promise((resolve, reject) => {
      API.updateCustomCategory({
        ..._.pick(params, ["id", "insuranceName"]),
        paymentScope: _.pick(params, ["paymentScope"]).paymentScope.split(",")
      }).then(res => {
        if (res.status) {
          message.success("编辑成功");
          resolve();
        } else {
          reject();
          message.error(res.errormsg || "编辑失败");
        }
      });
    });

  };


}
