'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var iconsReact = require('@cloudtower/icons-react');
var parrot = require('@cloudtower/parrot');
var core = require('@linaria/core');
var index = require('../../core/AccordionCard/index.js');
var index$4 = require('../../core/Button/index.js');
var index$3 = require('../../core/Fields/index.js');
var index$5 = require('../../core/ParrotTrans/index.js');
var index$2 = require('../../core/Switch/index.js');
var index$6 = require('../../core/TimePicker/index.js');
var index$1 = require('../../core/Typo/index.js');
var useParrotTranslation = require('../../hooks/useParrotTranslation.js');
var antd = require('antd');
var dayjs = require('dayjs');
var _ = require('lodash');
var moment = require('moment');
var React = require('react');
var cronTime = require('../../utils/cron-time.js');
var time = require('../../utils/time.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var dayjs__default = /*#__PURE__*/_interopDefault(dayjs);
var ___default = /*#__PURE__*/_interopDefault(_);
var moment__default = /*#__PURE__*/_interopDefault(moment);
var React__default = /*#__PURE__*/_interopDefault(React);

var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
  enumerable: true,
  configurable: true,
  writable: true,
  value
}) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) {
    if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]);
  }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
const CronPlanWrapper = "E_c1up1pdz";
const CronPlanHeader = "E_c156wh19";
const ModeTabs = "E_m126spxy";
const Wrapper = "E_wpbf4pq";
const stringifyPlan = (mode, daily, weekly, monthly, i18n) => {
  const isEn = i18n.language === parrot.ParrotLngs.en;
  const mark = isEn ? " , " : "\u3001";
  const days_map = isEn ? EN_WEEK_DAYS_MAP(i18n.t) : WEEK_DAYS_MAP(i18n.t);
  if (mode === "day") {
    const time = daily.time.format("HH:mm");
    const count = daily.step || 0;
    return count > 1 ? i18n.t("components.every_day_with_count_and_time", {
      count: daily.step,
      time
    }) : i18n.t("components.every_day_with_time", {
      time
    });
  }
  if (mode === "week") {
    const time = weekly.time.format("HH:mm");
    const count = weekly.step || 0;
    const day = weekly.days.map(d => days_map[d]).join(mark);
    const repeat_day = weekly.days.length > 0;
    return count > 1 ? repeat_day ? i18n.t("components.every_weeks_with_count_and_day_and_time", {
      count,
      day,
      time
    }) : i18n.t("components.every_weeks_with_count_and_time", {
      count,
      time
    }) : repeat_day ? i18n.t("components.every_week_with_day_and_time", {
      time,
      day
    }) : i18n.t("components.every_week_with_time", {
      time
    });
  }
  if (mode === "month") {
    const time = monthly.time.format("HH:mm");
    const count = monthly.step || 0;
    const day = monthly.days.join(mark);
    const repeat_day = monthly.days.length > 0;
    return count > 1 ? repeat_day ? i18n.t("components.every_months_with_count_and_day_and_time", {
      count,
      time,
      day
    }) : i18n.t("components.every_months_with_count_and_time", {
      count,
      time
    }) : repeat_day ? i18n.t("components.every_month_with_day_and_time", {
      day,
      time
    }) : i18n.t("components.every_month_with_time", {
      time
    });
  }
};
const Mode = ({
  mode,
  setMode
}) => {
  const {
    t
  } = useParrotTranslation();
  return /* @__PURE__ */React__default.default.createElement("div", {
    className: ModeTabs
  }, /* @__PURE__ */React__default.default.createElement(index$4, {
    className: core.cx(mode === "day" && "active"),
    type: "link",
    onClick: () => setMode("day")
  }, t("components.as_day")), /* @__PURE__ */React__default.default.createElement(index$4, {
    className: core.cx(mode === "week" && "active"),
    type: "link",
    onClick: () => setMode("week")
  }, t("components.as_week")), /* @__PURE__ */React__default.default.createElement(index$4, {
    className: core.cx(mode === "month" && "active"),
    type: "link",
    onClick: () => setMode("month")
  }, t("components.as_month")));
};
const Daily = ({
  daily,
  setDaily
}) => {
  return /* @__PURE__ */React__default.default.createElement("div", {
    className: Wrapper
  }, /* @__PURE__ */React__default.default.createElement(index$5.ParrotTrans, {
    i18nKey: "components.day_execute_task",
    count: daily.step
  }, /* @__PURE__ */React__default.default.createElement(index$3.Int, {
    meta: {},
    input: {
      value: daily.step,
      onChange: value => {
        setDaily(__spreadProps(__spreadValues({}, daily), {
          step: value
        }));
      },
      name: "daily-step",
      onBlur() {},
      onFocus() {},
      maxLength: 3
    }
  }), /* @__PURE__ */React__default.default.createElement(index$6, {
    format: "HH:mm",
    value: daily.time,
    onChange: value => {
      if (value) {
        setDaily(__spreadProps(__spreadValues({}, daily), {
          time: value
        }));
      }
    },
    clearIcon: null,
    suffixIcon: null
  })));
};
const WEEK_DAYS = t => [{
  value: 1,
  text: t("common.monday")
}, {
  value: 2,
  text: t("common.tuesday")
}, {
  value: 3,
  text: t("common.wednesday")
}, {
  value: 4,
  text: t("common.thursday")
}, {
  value: 5,
  text: t("common.friday")
}, {
  value: 6,
  text: t("common.saturday")
}, {
  value: 0,
  text: t("common.sunday")
}];
const WEEK_DAYS_MAP = t => WEEK_DAYS(t).reduce((prev, cur) => {
  prev[cur.value] = cur.text[1];
  return prev;
}, {});
const EN_WEEK_DAYS_MAP = t => WEEK_DAYS(t).reduce((prev, cur) => {
  prev[cur.value] = cur.text;
  return prev;
}, {});
const Weekly = ({
  weekly,
  setWeekly
}) => {
  const {
    t,
    i18n
  } = useParrotTranslation();
  const week_days = React.useMemo(() => WEEK_DAYS(t), [t]);
  return /* @__PURE__ */React__default.default.createElement("div", {
    className: Wrapper
  }, /* @__PURE__ */React__default.default.createElement(index$5.ParrotTrans, {
    i18nKey: "components.week_with_below_date",
    count: weekly.step,
    values: {
      day: t("components.day_date", {
        count: weekly.days.length
      })
    }
  }, /* @__PURE__ */React__default.default.createElement(index$3.Int, {
    meta: {},
    input: {
      value: weekly.step,
      onChange: value => {
        setWeekly(__spreadProps(__spreadValues({}, weekly), {
          step: value
        }));
      },
      name: "weekly-step",
      onBlur() {},
      onFocus() {},
      maxLength: 3
    }
  })), /* @__PURE__ */React__default.default.createElement("div", {
    className: "options"
  }, week_days.map(d => {
    const active = weekly.days.includes(d.value);
    return /* @__PURE__ */React__default.default.createElement(index$4, {
      className: core.cx("week-day-option", active && "active", i18n.language === parrot.ParrotLngs.en && "en-text"),
      type: "default",
      key: d.value,
      onClick: () => setWeekly(__spreadProps(__spreadValues({}, weekly), {
        days: active ? weekly.days.filter(day => day !== d.value) : weekly.days.concat(d.value).sort((a, b) => a - b)
      }))
    }, d.text);
  })), t("components.execution_time"), /* @__PURE__ */React__default.default.createElement(index$6, {
    style: {
      marginLeft: 0
    },
    format: "HH:mm",
    value: weekly.time,
    onChange: value => {
      if (value) {
        setWeekly(__spreadProps(__spreadValues({}, weekly), {
          time: value
        }));
      }
    },
    clearIcon: null,
    suffixIcon: null
  }));
};
const MONTH_DAYS = ___default.default.range(1, 32);
const Monthly = ({
  monthly,
  setMonthly
}) => {
  const mayNotExistDays = ___default.default.intersection(monthly.days, [29, 30, 31]);
  const {
    t,
    i18n
  } = useParrotTranslation();
  let date;
  if (i18n.language === parrot.ParrotLngs.en && mayNotExistDays.length === 3) {
    date = `${mayNotExistDays[0]}, ${mayNotExistDays[1]}, or ${mayNotExistDays[2]}`;
  } else {
    date = mayNotExistDays.join(i18n.t("components.date_mark"));
  }
  return /* @__PURE__ */React__default.default.createElement("div", {
    className: Wrapper
  }, /* @__PURE__ */React__default.default.createElement(index$5.ParrotTrans, {
    i18nKey: "components.month_with_below_date",
    count: monthly.step,
    values: {
      day: t("components.day_date", {
        count: monthly.days.length
      })
    }
  }, /* @__PURE__ */React__default.default.createElement(index$3.Int, {
    meta: {},
    input: {
      value: monthly.step,
      onChange: value => {
        setMonthly(__spreadProps(__spreadValues({}, monthly), {
          step: value
        }));
      },
      name: "monthly-step",
      onBlur() {},
      onFocus() {},
      maxLength: 3
    }
  })), /* @__PURE__ */React__default.default.createElement("div", {
    className: "options"
  }, MONTH_DAYS.map(d => {
    const active = monthly.days.includes(d);
    return /* @__PURE__ */React__default.default.createElement(index$4, {
      className: core.cx("month-day-option", active && "active"),
      type: "default",
      key: d,
      onClick: () => setMonthly(__spreadProps(__spreadValues({}, monthly), {
        days: active ? monthly.days.filter(day => day !== d) : monthly.days.concat(d).sort((a, b) => a - b)
      }))
    }, d);
  }), mayNotExistDays.length > 0 && /* @__PURE__ */React__default.default.createElement("span", {
    className: core.cx("help", index$1.Typo.Label.l4_regular)
  }, t("components.will_excute_at_last_day_with_date", {
    date
  }))), t("components.execution_time"), /* @__PURE__ */React__default.default.createElement(index$6, {
    style: {
      marginLeft: 0
    },
    format: "HH:mm",
    value: monthly.time,
    onChange: value => {
      if (value) {
        setMonthly(__spreadProps(__spreadValues({}, monthly), {
          time: value
        }));
      }
    },
    clearIcon: null,
    suffixIcon: null
  }));
};
const CronPlan = props => {
  const {
    value,
    onChange,
    onRemove
  } = props;
  const {
    t,
    i18n
  } = useParrotTranslation();
  const cronTime$1 = React.useMemo(() => {
    return new cronTime.CronTime(value.expression, value.startAt);
  }, [value]);
  const sendAtDate = React.useMemo(() => cronTime$1.sendAt(), [cronTime$1]);
  const changeValue = newValue => {
    onChange(__spreadValues(__spreadValues({}, value), newValue));
  };
  const [mode, setMode] = React.useState(time.getMode(cronTime$1["source"]));
  const source = cronTime$1["source"];
  const [,,, day, month] = source.split(" ");
  const time$1 = time.getTime(cronTime$1);
  const [daily, setDaily] = React.useState(() => {
    const rawDaily = time.getDaily(mode, source, time$1);
    return __spreadProps(__spreadValues({}, rawDaily), {
      time: moment__default.default(rawDaily.time.format())
    });
  });
  const [weekly, setWeekly] = React.useState(() => {
    const rawWeekly = time.getWeekly(mode, source, time$1);
    return __spreadProps(__spreadValues({}, rawWeekly), {
      time: moment__default.default(rawWeekly.time.format())
    });
  });
  const [monthly, setMonthly] = React.useState(() => {
    const rawMonthly = time.getMonthly(mode, month, day, time$1);
    return __spreadProps(__spreadValues({}, rawMonthly), {
      time: moment__default.default(rawMonthly.time.format())
    });
  });
  React.useEffect(() => {
    let newExpression = "";
    let empty = false;
    switch (mode) {
      case "day":
        newExpression = time.toDailyString(daily.step, dayjs__default.default(daily.time.format()));
        break;
      case "week":
        newExpression = time.toWeeklyString(weekly.step, dayjs__default.default(weekly.time.format()), weekly.days);
        if (weekly.days.length === 0) {
          empty = true;
        }
        break;
      case "month":
        newExpression = time.toMonthlyString(monthly.step, dayjs__default.default(monthly.time.format()), monthly.days);
        if (monthly.days.length === 0) {
          empty = true;
        }
        break;
    }
    if (newExpression === value.expression) {
      return;
    }
    changeValue({
      expression: newExpression,
      empty
    });
  }, [mode, daily, weekly, monthly]);
  const title = stringifyPlan(mode, daily, weekly, monthly, i18n);
  return /* @__PURE__ */React__default.default.createElement(index, {
    className: CronPlanWrapper,
    header: /* @__PURE__ */React__default.default.createElement("div", {
      className: CronPlanHeader
    }, /* @__PURE__ */React__default.default.createElement("div", {
      className: "left"
    }, /* @__PURE__ */React__default.default.createElement(iconsReact.ClockIcon, null), /* @__PURE__ */React__default.default.createElement("span", {
      className: core.cx(index$1.Typo.Label.l2_regular, "title"),
      title
    }, title), /* @__PURE__ */React__default.default.createElement("span", {
      className: core.cx(index$1.Typo.Label.l4_regular, "retain")
    }, t("components.retain_with_count", {
      count: value.retain || 1
    }))), /* @__PURE__ */React__default.default.createElement("div", {
      className: "right",
      onClick: e => e.stopPropagation()
    }, /* @__PURE__ */React__default.default.createElement("span", {
      className: "reverse"
    }, /* @__PURE__ */React__default.default.createElement(index$2, {
      checked: value.enabled,
      onChange: v => changeValue({
        enabled: v
      })
    }, value.enabled ? t("common.enabled") : t("common.disabled"))), /* @__PURE__ */React__default.default.createElement("span", {
      className: "close",
      onClick: onRemove
    }, /* @__PURE__ */React__default.default.createElement(iconsReact.CloseIcon, null)))),
    expand: /* @__PURE__ */React__default.default.createElement(React__default.default.Fragment, null, /* @__PURE__ */React__default.default.createElement(Mode, {
      mode,
      setMode
    }), mode === "day" && /* @__PURE__ */React__default.default.createElement(Daily, {
      daily,
      setDaily
    }), mode === "week" && /* @__PURE__ */React__default.default.createElement(Weekly, {
      weekly,
      setWeekly
    }), mode === "month" && /* @__PURE__ */React__default.default.createElement(Monthly, {
      monthly,
      setMonthly
    }), /* @__PURE__ */React__default.default.createElement("div", {
      className: "field-item"
    }, /* @__PURE__ */React__default.default.createElement("label", {
      className: index$1.Typo.Label.l3_regular_title
    }, t("components.start_date")), /* @__PURE__ */React__default.default.createElement("div", {
      className: "field"
    }, /* @__PURE__ */React__default.default.createElement(antd.DatePicker, {
      format: "YYYY/M/DD",
      value: moment__default.default(value.startAt.toISOString()),
      onChange: value2 => {
        if (value2) {
          changeValue({
            startAt: dayjs__default.default(value2.toISOString())
          });
        }
      },
      suffixIcon: null,
      clearIcon: null
    }), /* @__PURE__ */React__default.default.createElement("div", {
      className: core.cx("help", index$1.Typo.Footnote.f2_regular)
    }, t("components.next_generate_with_date", {
      date: sendAtDate.format("YYYY/M/DD HH:mm"),
      interpolation: {
        escapeValue: false
      }
    })))), /* @__PURE__ */React__default.default.createElement("div", {
      className: "field-item"
    }, /* @__PURE__ */React__default.default.createElement("label", {
      className: index$1.Typo.Label.l3_regular_title
    }, t("components.retain_date")), /* @__PURE__ */React__default.default.createElement("div", {
      className: "field"
    }, /* @__PURE__ */React__default.default.createElement(index$3.Int, {
      suffix: t("components.count"),
      meta: {},
      input: {
        value: value.retain,
        onChange: v => changeValue({
          retain: v
        }),
        onBlur() {},
        onFocus() {},
        name: "retain",
        maxLength: 2
      }
    }), /* @__PURE__ */React__default.default.createElement("div", {
      className: core.cx("help", index$1.Typo.Footnote.f2_regular)
    }, t("components.will_save_one_to_thirty_report")))))
  });
};
var CronPlan$1 = CronPlan;

exports.default = CronPlan$1;
exports.stringifyPlan = stringifyPlan;
