import * as mobx from "mobx";
import { action, computed, extendObservable, observable } from "mobx";
import HrmBaseStore from "./baseStore";
import { WeaTableNew } from "comsMobx";
import { message } from "antd";
import { WeaHelpfulTip, WeaInputLocale,WeaLocaleProvider } from "ecCom";
import { cloneDeep, has, indexOf, isEmpty, remove, uniq } from "lodash";
import { i18n } from "../public/i18n";
import * as Api from "../apis/columnSetting";
import { validDBKeys } from "../util";
import { saveFieldDefinedInfo } from "../apis/columnSetting";

const getLabel = WeaLocaleProvider.getLabel;

const getCurrentLabel = WeaInputLocale.getCurrentLabel;
const { TableStore } = WeaTableNew;

const toJS = mobx.toJS;

export class ColumnSetting {
  @observable tableStore = new TableStore();
  @observable columnsPermissionData = [];
  @observable selectedKey = "0";
  @observable authorized = '';
  @observable loading = true;
  @observable tabOneRelatedData = {
    datas: [], //datas受控
    columns: [],
    loading: true
  };
  @observable tabTwoRelatedData = {
    datas: [], //datas受控
    columns: [],
    loading: true,
    selectedData: {}, //selectedData受控
  };
  @observable tabThreeRelatedData = {
    datas: [], //datas受控
    columns: [],
    loading: true,
    selectedData: {} //selectedData受控
  };

  @computed get checkedItems() {
    const data = isEmpty(this.columnsPermissionData) ? toJS(this.tableStore.datas) : this.columnsPermissionData;
    return this.arrColumnsToJson(data);
  }

  @computed get tabTwoSaveParams() {
    let datas = this.tabTwoRelatedData.datas;
    let selectedData = this.tabTwoRelatedData.selectedData.isused;
    let params = this.arrToJson(toJS(datas), toJS(selectedData));
    params.rownum = datas.length;
    return params;
  }
  @computed get tabThreeSaveParams() {
    let datas = this.tabThreeRelatedData.datas;
    let selectedData = this.tabThreeRelatedData.selectedData.status;
    let params = this.arrToJson(toJS(datas), toJS(selectedData), 'status');
    params.rownum = datas.length;
    return params;
  }

  @action
  getRight() {
    Api.hasRight().then(res => {
      let { code, data, msg } = res;
      const { hasRight } = data;
      if (code === 200) {
        this.setRight(hasRight);
      } else {
        message.error(msg);
      }
    }).catch(error => {
      message.error(error);
    });
  }

  loadTabOneRelatedData() {
    this.tabOneRelatedData.loading = true;
    Promise.all(
      [
        Api.getTable()
      ]
    ).then(([res]) => {
      if (res.code === 200) {
        res.data.datas && this.tableStore.getDatas(res.data.datas, 1);
      } else {
        message.warning(res.msg);
      }
    }).catch(error => {
      message.error(error);
    });
  }

  loadTabTwoRelatedData() {
    this.tabTwoRelatedData.loading = true;
    Promise.all(
      [
        Api.getTableEdit()
      ]
    ).then(res => {
      res.map((rs, index) => {
        if (index == 0) {
          let {
            api_status,
            datas,
            columns,
            selectedData
          } = rs;

          if (api_status) {
            columns.map((c, index) => {
              if (c.key === "itemurl") {
                c.title = <span>
					                        <span>{c.title}</span>
					                        <span style={{ marginLeft: 10 }}>
						                        <WeaHelpfulTip
                                                  ecId={`${this && this.props && this.props.ecId || ""}_WeaHelpfulTip@4vdvfp@${index}`}
                                                  title={getLabel('547383',`自定义页面链接地址可以为外网地址，如：http://www.baidu.com
								            		也可以是内部地址，如：/test.jsp，可以带上参数传参，像这样：/test.jsp?a=1&b=2
								            		也可以写占位符{#id}传人员id，像这样：/test.jsp?a=1&b={#id}&mypara2={#id}
								            		即使不写占位符，默认也会收到1个固定的参数：hrmResourceID=人员id`)}/>
								            </span>
							            </span>;
              } else if (c.key === "itemnum") {
                c.title = <span>
					                        <span>{c.title}</span>
					                        <span style={{ marginLeft: 10 }}>
						                        <WeaHelpfulTip
                                                  ecId={`${this && this.props && this.props.ecId || ""}_WeaHelpfulTip@wotuuk@${index}`}
                                                  title={getLabel('547382', "填写类的全路径例如：com.engine.hrm.cmd.hrmcarditem.GetTabNumDemoCmd,类中包含execute方法返回int型数据。 填写不正确的路径并启用，对应tab页title将会出现（error）字样。")}/>
								            </span>
							           </span>;
              }
            });

            extendObservable(this.tabTwoRelatedData, {
              datas: datas,
              columns: columns
            });

            selectedData && extendObservable(this.tabTwoRelatedData, {
              selectedData: selectedData
            });
            extendObservable(this.tabTwoRelatedData, {
              loading: false
            });
          } else {
            message.error(rs.message);
          }
        }
      });
    }).catch(error => {
      message.error(error);
    });
  }

  loadTabThreeRelatedData() {
    this.tabThreeRelatedData.loading = true;
    Promise.all(
      [
        Api.getCardButtonTable()
      ]
    ).then(result => {
      result.map((item, index) => {
        if (index === 0) {
          let { code, data, msg } = item;
          if (code === 200) {
            const { columns, datas, selectedData } = data;
            if (!columns || !datas) {
              return;
            }

            columns.map((c, index) => {
              if (c.key === "url") {
                c.title = <span>
                  <span>{c.title}</span>
                  <span style={{ marginLeft: 10 }}>
                    <WeaHelpfulTip
                      ecId={`${this && this.props && this.props.ecId || ""}_WeaHelpfulTip@4vdvfp@${index}`}
                      title={getLabel('547638', "页面链接地址可以为外网地址，如：http://www.baidu.com也可以是内部地址，如：/test.jsp，可以带上参数传参，像这样：/test.jsp?a=1&b=2也可以写占位符${id}传人员id，像这样：/test.jsp?a=1&b=${id}&mypara2=${id}")}/>
                  </span>
              </span>;
              }
            });
            extendObservable(this.tabThreeRelatedData, {
              datas: datas,
              columns: columns
            });

            selectedData && extendObservable(this.tabThreeRelatedData, {
              selectedData: selectedData
            });
            extendObservable(this.tabThreeRelatedData, {
              loading: false
            });
          } else {
            message.error(msg);
          }
        }
      });
    });
  }

  columnPermissionSave() {
    let params = {
      ...toJS(this.checkedItems)
    };
    Api.cardAccessSave(params).then(({ code, msg }) => {
      if (code === 200) {
        this.loadTabOneRelatedData();
        message.success(msg || "操作成功");
      } else {
        message.error(msg || "操作失败");
      }
    }).catch(error => {
      message.error(error);
    });
  }

  userDefineCardItemSave() {
    if (!this.verify(toJS(this.tabTwoRelatedData.datas))) return;
    let params = this.tabTwoSaveParams;

    Api.userDefineCardItemSave(params).then(res => {
      let {
        api_status,
        sign
      } = res;

      if (api_status) {
        if (sign == "1") {
          res.message && message.success(res.message);
        } else {
          res.message && message.warning(res.message);
        }
      } else {
        message.error(res.message);
      }
    }).catch(error => {
      message.error(error);
    });
  }
  customItemSave() {
    let params = this.tabThreeSaveParams;
    Api.saveFieldDefinedInfo(params).then(res => {
      let { code, msg } = res;
      if (code === 200) {
        message.success(msg || "操作成功");
        this.loadTabThreeRelatedData();
      } else {
        message.error(msg);
      }
    }).catch(error => {
      message.error(error);
    });
  }

  arrColumnsToJson(arr, rows) {
    let jsonColumn = {
      rownum: arr.length
    };
    arr.map((item, index) => {
      for (let key in item) {
        jsonColumn[key + "_" + index] = item[key];
      }
    });
    return jsonColumn;
  }

  setTableEditDatas(e) {
    e.map(item => {
      for (let key in item) {
        if (key == "undefined") {
          delete item[key];
        }
        if (!item["isused"]) {
          item["isused"] = "";
        }
      }
    });
    extendObservable(this.tabTwoRelatedData, {
      datas: e
    });
  }
  setCustomTableEditDatas(e) {
    e.map(item => {
      for (let key in item) {
        if (key == "undefined") {
          delete item[key];
        }
        if (!item["status"]) {
          item["status"] = "";
        }
      }
    });
    extendObservable(this.tabThreeRelatedData, {
      datas: e
    });
  }

  setEnableRows(e) {
    extendObservable(this.tabTwoRelatedData, {
      selectedData: {
        isused: e
      }
    });
  }
  setEnableThreeRows(e) {
    extendObservable(this.tabThreeRelatedData, {
      selectedData: {
        status: e
      }
    });
  }

  arrToJson(arr, rows, rowKey="isused") {
    let json = {};
    const _rows = isEmpty(arr) ? [] : rows;
    _rows && _rows.map(index => {
      arr[index][rowKey] = "1";
    });
    arr.map((item, index) => {
      if (!item[rowKey]) item[rowKey] = "0";
      for (let key in item) {
        json[key + "_" + index] = item[key];
      }
    });

    return json;
  }

  verify(arr) {
    for (let i = 0; i < arr.length; i++) {
      if (!arr[i].itemname || !arr[i].itemurl) {
        const temp = i18n.message.requiredInfoIsNotFull().replace("{param}", i + 1);
        message.warning(temp);
        return false;
      }
    }
    return true;
  }

  setRight(right) {
    this.authorized = right;
  }

  setSelectedKey(key) {
    this.selectedKey = key;
  }

  setColumnsPermissionData(list) {
    this.columnsPermissionData = list;
  }
}
