import dayjs from "dayjs";
import * as _BOX from "@/api/ecw/box";
import FileSaver from "file-saver";
import Decimal from "decimal.js";
import i18n from "@/i18n";

/**
 * 空运流程
 *
 * @return {*}
 */
function airBaseData() {
  return [
    [
      {
        title: i18n.$t("订舱"),
        imgSrc: {
          start: require("@/assets/images/shipping/dc-start.png"),
          end: require("@/assets/images/shipping/dc-end.png"),
        },
        type: "booking", // 类型
        dataKey: "1", // 字典数据键值
        /**
         * 订舱状态：11、未订舱；12、已订舱
         */
        voName: "bookAirInfo", // 订舱对象vo
        keyName: "bkStatus",
        status: {
          start: [11],
          wait: [],
          end: [12],
        },
      },
    ],
    [
      {
        title: i18n.$t("分拣"),
        imgSrc: {
          start: require("@/assets/images/shipping/yz-start.png"),
          wait: require("@/assets/images/shipping/yz-wait.png"),
          end: require("@/assets/images/shipping/yz-end.png"),
        },
        type: "preinstall",
        dataKey: "2", // 字典数据键值
        /**
         * 预装状态：21、未预装；22、预装中；23、预装审核中；24、预装审核失败；25、预装审核成功
         */
        voName: "preInstallInfo",
        keyName: "prStatus",
        status: {
          start: [21],
          wait: [22, 23, 24],
          end: [25],
        },
      }
    ],
    [
      {
        title: i18n.$t("理货"),
        imgSrc: {
          start: require("@/assets/images/shipping/lh-start.png"),
          wait: require("@/assets/images/shipping/lh-wait.png"),
          end: require("@/assets/images/shipping/lh-end.png"),
        },
        type: "tally",
        dataKey: "16", // 字典数据键值
        /**
         * 理货状态：2111、未理货；2112、已理货
         */
        voName: "tallyInfo",
        keyName: "tyStatus",
        status: {
          start: [2111],
          wait: [],
          end: [2112],
        },
      },
      {
        title: i18n.$t("合包"),
        imgSrc: {
          start: require("@/assets/images/shipping/qg-start.png"),
          wait: require("@/assets/images/shipping/qg-wait.png"),
          end: require("@/assets/images/shipping/qg-end.png"),
        },
        type: "mergePkg",
        dataKey: "3", // 字典数据键值
        /**
         * 合包状态：161待合包   162已合包
         */
        voName: "trailerInfo",
        keyName: "mergePkgStatus",
        status: {
          start: [161],
          wait: [],
          end: [162],
        },
      },
    ],
    [
      {
        title: i18n.$t("出货"),
        imgSrc: {
          start: require("@/assets/images/shipping/zg-start.png"),
          wait: require("@/assets/images/shipping/zg-wait.png"),
          end: require("@/assets/images/shipping/zg-end.png"),
        },
        type: "shipment",
        dataKey: "4", // 字典数据键值
        /**
         * 出货状态：171、待出货   172、已出货
         */
        voName: "boxAirShipmentBackVO",
        keyName: "airShipmentStatus",
        status: {
          start: [171],
          wait: [],
          end: [172],
        },
      },
      {
        title: i18n.$t("出仓"),
        imgSrc: {
          start: require("@/assets/images/shipping/zg-start.png"),
          wait: require("@/assets/images/shipping/zg-wait.png"),
          end: require("@/assets/images/shipping/zg-end.png"),
        },
        type: "checkout",
        dataKey: "5", // 字典数据键值
        /**
         * 出仓状态：221、未出仓  222、已出仓
         */
        voName: "boxAirCheckoutBackVO",
        keyName: "checkoutStatus",
        status: {
          start: [221],
          wait: [],
          end: [222],
        },
      },
    ],
    [
      {
        title: "AGENT",
        imgSrc: {
          start: require("@/assets/images/shipping/agent-start.png"),
          wait: require("@/assets/images/shipping/agent-wait.png"),
          end: require("@/assets/images/shipping/agent-end.png"),
        },
        type: "agent",
        voName: "agentInfo",
        currStatus: "start",
      },
      {
        title: i18n.$t("报关"),
        imgSrc: {
          start: require("@/assets/images/shipping/bg-start.png"),
          wait: require("@/assets/images/shipping/bg-wait.png"),
          end: require("@/assets/images/shipping/bg-end.png"),
        },
        type: "cusDeclaration",
        dataKey: "5", // 字典数据键值
        /**
         *报关状态：51、未报关；52、报关中；53、已报关
         */
        voName: "customsInfo",
        keyName: "dcStatus",
        status: {
          start: [51],
          wait: [52],
          end: [53],
        },
      },
      {
        title: i18n.$t("提单补料"),
        imgSrc: {
          start: require("@/assets/images/shipping/tdcl-start.png"),
          wait: require("@/assets/images/shipping/tdcl-wait.png"),
          end: require("@/assets/images/shipping/tdcl-end.png"),
        },
        type: "subMaterial",
        dataKey: "7", // 字典数据键值
        /**
         * 提单补料状态：71、未提单补料；72、已提单补料
         */
        voName: "ladingBillInfo",
        keyName: "blStatus",
        status: {
          start: [71],
          wait: [],
          end: [72],
        },
      },
    ],
    [
      {
        title: i18n.$t("起飞"),
        imgSrc: {
          start: require("@/assets/images/shipping/ecqf-start.png"),
          wait: require("@/assets/images/shipping/ecqf-wait.png"),
          end: require("@/assets/images/shipping/ecqf-end.png"),
        },
        type: "twoWayTakeoff",
        dataKey: "9", // 字典数据键值
        /**
         * 起飞状态：231、未起飞；232、已起飞
         */
        voName: "boxAirFlyInfo",
        keyName: "flyStatus",
        status: {
          start: [231],
          wait: [],
          end: [232],
        },
      },
    ],
    [
      {
        type: "clrDocument",
        imgSrc: {
          start: require("@/assets/images/shipping/qg-start.png"),
          wait: require("@/assets/images/shipping/qg-wait.png"),
          end: require("@/assets/images/shipping/qg-end.png"),
        },
        title: i18n.$t("清关文件"),
        dataKey: "11", // 字典数据键值
        /**
         * 清关文件状态：111、未清关文件；112、已清关文件
         */
        voName: "clearanceDocInfo",
        keyName: "cdStatus",
        status: {
          start: [111],
          wait: [],
          end: [112],
        },
      },
    ],
    [
      {
        title: i18n.$t("到港"),
        imgSrc: {
          start: require("@/assets/images/shipping/dg-start.png"),
          wait: require("@/assets/images/shipping/dg-wait.png"),
          end: require("@/assets/images/shipping/dg-end.png"),
        },
        type: "arrival",
        dataKey: "12", // 字典数据键值
        /**
         * 到港状态：151、未到港；152、已到港
         */
        voName: "airArrivalInfo",
        keyName: "sapStatus",
        status: {
          start: [151],
          wait: [],
          end: [152],
        },
      },
    ],
    [
      {
        title: i18n.$t("清关"),
        imgSrc: {
          start: require("@/assets/images/shipping/qg-start.png"),
          wait: require("@/assets/images/shipping/qg-wait.png"),
          end: require("@/assets/images/shipping/qg-end.png"),
        },
        type: "cusClearance",
        dataKey: "13", // 字典数据键值
        /**
         * 清关状态：131、未清关；132、已清关
         */
        voName: "clearanceInfo",
        keyName: "clStatus",
        status: {
          start: [131],
          wait: [],
          end: [132],
        },
      },
    ],
    [
      {
        title: i18n.$t("到仓"),
        imgSrc: {
          start: require("@/assets/images/shipping/xg-start.png"),
          wait: require("@/assets/images/shipping/xg-wait.png"),
          end: require("@/assets/images/shipping/xg-end.png"),
        },
        type: "unloading",
        dataKey: "14", // 字典数据键值
        /**
         * 卸柜状态：181、未卸柜；182、卸柜中；183、卸柜审核中；184、卸柜审核失败；185、卸柜审核成功；186、已卸柜
         */
        voName: "cabinetUnloadInfo",
        keyName: "ulStatus",
        status: {
          start: [181],
          wait: [182, 183, 184, 185],
          end: [186],
        },
      },
    ],
    [
      {
        title: i18n.$t("结算"),
        imgSrc: {
          start: require("@/assets/images/shipping/js-start.png"),
          wait: require("@/assets/images/shipping/js-wait.png"),
          end: require("@/assets/images/shipping/js-end.png"),
        },
        type: "settlement",
        dataKey: "15", // 字典数据键值
        /**
         * 结算状态：191、未结算；192、结算中；193、已结算
         */
        voName: "settlementInfo",
        keyName: "slStatus",
        status: {
          start: [191],
          wait: [192],
          end: [193],
        },
      },
    ],
  ];
}

/**
 * 详情显示列
 *
 * @return {*}
 */
function getColmnMapping() {
  return {
    bookAirInfo: [
      {
        title: i18n.$t("提单号"),
        key: "blNo",
      },
      {
        title: i18n.$t("起运港"),
        key: "departurePortId",
        type: "dock",
      },
      {
        title: i18n.$t("目的港"),
        key: "destPortId",
        type: "dock",
      },
      {
        title: i18n.$t("航空公司"),
        key: "airlineCompanyId",
        type: "supplier",
      },
      {
        title: i18n.$t("Shipper"),
        key: "shipperId",
        type: "supplier",
      },
      {
        title: i18n.$t("预计起飞时间"),
        key: "flyTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    preInstallInfo: [
      {
        title: i18n.$t("分拣时间"),
        key: "createTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    tallyInfo: [
      {
        title: i18n.$t("完成理货时间"),
        key: "tyTime",
        type: "datetime",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    boxAirShipmentBackVO: [
      {
        title: i18n.$t("送货时间"),
        key: "deliverTime",
        type: "datetime",
      },
      {
        title: i18n.$t("送货地址"),
        key: "deliverAddress",
      },
      {
        title: i18n.$t("车牌"),
        key: "licensePlate",
      },
      {
        title: i18n.$t("司机"),
        key: "driver",
      },
      {
        title: i18n.$t("司机联系方式"),
        key: "driverPhone"
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    boxAirCheckoutBackVO: [
      {
        title: i18n.$t("出仓时间"),
        key: "checkoutTime",
        type: "datetime",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    agentInfo: [
      {
        title: i18n.$t("代理商"),
        key: "agentId",
        type: "supplier",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    customsInfo: [
      {
        title: i18n.$t("报关方式"),
        key: "dcCustomsType",
        type: "shipping_customs_type",
      },
      {
        title: i18n.$t("报关行公司"),
        key: "dcCompanyId",
        type: "supplier",
      },
      {
        title: i18n.$t("截关时间"),
        key: "dcCutOffTime",
        type: "date",
      },
      {
        title: i18n.$t("状态"),
        key: "dcCustomsStatus",
        type: "shipping_dcCustoms_status",
      },
      {
        title: i18n.$t("查验时间"),
        key: "dcCheckTime",
        type: "date",
      },
      {
        title: i18n.$t("放行时间"),
        key: "dcPassTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    ladingBillInfo: [
      {
        title: i18n.$t("清关代理"),
        key: "agentId",
        type: "supplier",
      },
      {
        title: i18n.$t("提单号"),
        key: "blMblNo",
      },
      {
        title: i18n.$t("通知方"),
        key: "notifyingName",
      },
      {
        title: i18n.$t("提单备注"),
        key: "remarks",
      },
      {
        title: i18n.$t("数量（个）"),
        key: "packageNum",
      },
      {
        title: i18n.$t("体积"),
        key: "cbm",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    clearanceDocInfo: [
      {
        title: "agent list",
        key: "cdAgentlistType",
        type: "isFile",
      },
      {
        title: "soncap",
        key: "cdSoncapType",
        type: "isFile",
      },
      {
        title: i18n.$t("出单方式"),
        key: "cdOutBillType",
        type: "billingMethod",
      },
      {
        title: i18n.$t("寄送时间"),
        key: "cdSendTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    arrivalInfo: [
      {
        title: i18n.$t("实际到港时间"),
        key: "apRealTime",
        type: "datetime",
      },
      {
        title: i18n.$t("确认到港"),
        key: "apConfirmTime",
        type: "datetime",
      },
      {
        title: i18n.$t("卸港时间"),
        key: "apUnloadPortTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    clearanceInfo: [
      {
        title: i18n.$t("预计清关时间"),
        key: "clEstTime",
        type: "date",
      },
      {
        title: i18n.$t("清关时间"),
        key: "clClearTime",
        type: "datetime",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    airArrivalInfo: [
      {
        title: i18n.$t("预计到达时间"),
        key: "estTime",
        type: "datetime",
      },
      {
        title: i18n.$t("实际到达时间"),
        key: "actTime",
        type: "datetime",
      },
      {
        title: i18n.$t("实际二程时间"),
        key: "actSecondTime",
        type: "datetime",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    cabinetUnloadInfo: [
      {
        title: i18n.$t("到仓时间"),
        key: "ulWarehouseTime",
        type: "date",
      },
      {
        title: i18n.$t("卸货时间"),
        key: "ulBoxTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
    settlementInfo: [
      {
        title: i18n.$t("可结算"),
        key: "slSettlementTime",
        type: "date",
      },
      {
        title: i18n.$t("已结算"),
        key: "slSettledTime",
        type: "date",
      },
      {
        title: i18n.$t("业务员"),
        key: "operator",
      },
    ],
  };
}

/**
 * 常量字典
 */
const constantDict = {
  //航程
  voyageData: [
    {
      value: 1,
      label: i18n.$t("直飞"),
    },
    {
      value: 2,
      label: i18n.$t("中转"),
    },
  ],
  // 配船状态
  saExmtStatus: [
    {
      value: "1",
      label: i18n.$t("免配"),
    },
    {
      value: "2",
      label: i18n.$t("已配"),
    },
  ],
  // 驳船
  bgExmtStatus: [
    {
      value: "1",
      label: i18n.$t("无驳船"),
    },
    {
      value: "2",
      label: i18n.$t("有驳船"),
    },
  ],
  // 出单方式
  billingMethod: [
    {
      value: "1",
      label: i18n.$t("正本"),
    },
    {
      value: "2",
      label: i18n.$t("电放"),
    },
  ],
  // 是否有文件
  isFile: [
    {
      value: "1",
      label: i18n.$t("无需"),
    },
    {
      value: "2",
      label: i18n.$t("已做"),
    },
  ],

  deliverType: [
    {
      value: "1",
      label: i18n.$t("送货上门"),
    },
    {
      value: "2",
      label: i18n.$t("供应商自提"),
    },
  ],
};

/**
 * string format number
 *
 * @param {*} obj
 * @param {*} keys
 * @return {*}
 */
function formatStringNumber(obj, keys) {
  for (const [key, value] of Object.entries(obj)) {
    if (keys.includes(key) && !Number.isNaN(Number(value))) {
      obj[key] = Number(value);
    }
  }
  return obj;
}

/**
 * number format string
 *
 * @param {*} obj
 * @param {*} keys
 * @return {*}
 */
function formatNumberString(obj, keys) {
  for (const [key, value] of Object.entries(obj)) {
    if (keys.includes(key) && value) {
      obj[key] = String(value);
    }
  }
  return obj;
}

/**
 * stringDate format Date
 *
 * @param {*} obj
 * @param {*} keys
 * @param {string} [format="YYYY-MM-DD HH:mm:ss"]
 * @return {*}
 */
function formatDateStr(obj, keys, format = "YYYY-MM-DD HH:mm:ss") {
  for (const [key, value] of Object.entries(obj)) {
    if (keys.includes(key) && dayjs(value).isValid()) {
      obj[key] = dayjs(value).format(format);
    }
  }
  return obj;
}

/**
 * 格式化日期
 *
 * @param {*} date
 * @param {string} [format="YYYY-MM-DD HH:mm:ss"]
 * @return {*}
 */
function formatDate(date, format = "YYYY-MM-DD HH:mm:ss") {
  if (!date) return date;
  return dayjs(date).format(format);
}

/**
 * 获取海运流程状态
 *
 * @param {*} val
 * @return {*}
 */
function getSeaStatus(val) {
  let currNodeStatus = 11,
    isBreak = false,
    datas = seaBaseData();
  // 迭代每个节点
  for (let i = 0; i < datas.length; i++) {
    const nodes = datas[i];
    for (let j = 0; j < nodes.length; j++) {
      const node = nodes[j];
      const { keyName, voName, status } = node;
      if (!keyName) continue;
      const { start, wait, end } = status;

      if (start.includes(val[keyName]) && val[voName]) {
        currNodeStatus = val[keyName];
      }

      if (wait.includes(val[keyName])) {
        currNodeStatus = val[keyName];
        isBreak = true;
        break;
      }

      if (end.includes(val[keyName])) {
        currNodeStatus = val[keyName];
      }
    }
    if (isBreak) break;
  }
  return currNodeStatus;
}

/**
 * 组装统计信息文字
 *
 * @param {*} total
 * @param {string} [keys=["num", "volume", "weight"]]
 * @return {*}
 */
function getTotlContent(total, keys = ["num", "volume", "weight"]) {
  let content = [];
  for (const key of keys) {
    if (key === "num") {
      content.push(`${total?.num ?? 0}${i18n.$t("箱")}`);
    }
    if (key === "volume") {
      let volume = total?.volume ?? 0;
      volume = volume === 0 ? volume : new Decimal(volume).toFixed(2);
      content.push(`${volume}m³`);
    }
    if (key === "weight") {
      let weight = total?.weight ?? 0;
      weight = weight === 0 ? weight : new Decimal(weight).toFixed(2);
      content.push(`${weight}kg`);
    }
  }
  return content.join(" ");
}

function getCapacity(capacity) {
  return `${capacity?.name ?? ""}${i18n.$t("柜型")} ${capacity?.volume ?? 0}m³ ${
    capacity?.weight ?? 0
  }kg`;
}

function sumStatistics(val) {
  let count = { num: 0, volume: 0, weight: 0 };
  if (Array.isArray(val)) {
    val.forEach((item) => {
      const { secStatistics } = item;
      if (secStatistics) {
        if (!Number.isNaN(Number(secStatistics.num))) {
          count.num = Decimal.add(
            count.num,
            Number(secStatistics.num)
          ).toNumber();
        }
        if (!Number.isNaN(Number(secStatistics.volume))) {
          count.volume = Decimal.add(
            count.volume,
            Number(secStatistics.volume)
          );
        }
        if (!Number.isNaN(Number(secStatistics.weight))) {
          count.weight = Decimal.add(
            count.weight,
            Number(secStatistics.weight)
          );
        }
      }
    });
  }
  return getTotlContent(count);
}

export const fileTypes = [
  "doc",
  "xls",
  "ppt",
  "txt",
  "pdf",
  "png",
  "jpg",
  "jpeg",
];

/**
 * 服务提示消息回调
 *
 * @export
 * @param {*} result
 * @param {*} _vue
 * @return {*}
 */
function serviceMsg(result, _vue) {
  return new Promise((resolve, reject) => {
    const { code, msg } = result;
    if (code === 0) {
      _vue.$message.success(i18n.$t("操作成功"));
      resolve();
    } else {
      _vue.$message.error(msg);
      reject();
    }
  });
}

/**
 * 跳转审核详情
 *
 * @param {*} bpmProcessId
 */
function toReviewDetail(bpmProcessId) {
  this.$router.push({
    path: "/bpm/process-instance/detail",
    query: { id: bpmProcessId },
  });
}

function downloadFile(funName, params, fileName, fileFormat) {
  _BOX[funName](params).then((res) => {
    const reader = new FileReader();

    reader.onload = (event) => {
      try {
        // 将读取的string转换为json
        // 若果能转换成功 => 接口返回的是json数据，提示报错信息
        const json = JSON.parse(event.target.result);
        if (json.code) {
          window.ElementUI.Message.error(json.msg);
        }
      } catch (err) {
        let blob = new Blob([res], { type: `application/${fileFormat}` });
        FileSaver.saveAs(blob, fileName);
      }
    };
    reader.readAsText(res);
  });
}

function downloadFileByUrl(funName, params) {
  _BOX[funName](params).then((res) => {
    if (res.data) FileSaver.saveAs(res.data);
  });
}

export {
  getColmnMapping,
  getSeaStatus,
  airBaseData,
  constantDict,
  formatStringNumber,
  formatDateStr,
  formatNumberString,
  formatDate,
  getTotlContent,
  getCapacity,
  sumStatistics,
  serviceMsg,
  toReviewDetail,
  downloadFile,
  downloadFileByUrl,
};
