import {getToken} from "../../utils/auth";
import {openCnPrint} from "../../components/cnPrint/index";
import {openHiPrint} from "../../components/hiprint/index";
import {openJdPrint} from "../../components/jdPrint/index";
import {openPddPrint} from "../../components/pddPrint/index";
import {openVipPrint} from "../../components/vipPrint/index";
import {openXhsPrint} from "../../components/xhsPrint/index";

let modules;
let configUtil = {
  baseUrl: process.env.VUE_APP_BASE_API,
  getToken,
};

modules = {
  props: ["parentTarget", "option"],
  data() {
    return {
      showJSONDialog: false,
      exportJson: {},
      exportOption: {},
      param: null,
      showContaint: false,
      timer: null,
      exportTemplates: [],
      printTypes: [2, 3, 6, 7, 8, 9],
      exportTypes: [0, 1, 5],
    };
  },
  computed: {
    buttonName() {
      if(this.option.label){
        return this.option.label;
      }
      let exportTemplates = this.exportTemplates;
      let printTypes = this.printTypes;
      if (exportTemplates.length) {
        let btn1 = exportTemplates.find((item) => {
          return item.etType === 0 || item.etType === 1 || item.etType === 5;
        });
        let btn2 = exportTemplates.find((item) => {
          return printTypes.includes(item.etType);
        });
        if (btn1 && btn2) {
          return this.$t2(
            "导出/打印",
            "components.baseInputExport.exportAndPrint"
          );
        } else if (btn1) {
          return this.$t2("导出", "components.baseInputExport.export");
        } else if (btn2) {
          return this.$t2("打印", "components.baseInputExport.print");
        }
      }
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  mounted() {
    this.initExportTemplates();
  },
  methods: {
    getPrintData(code, condition, callback) {
      return this.parentTarget.$http({
        url: this.option.prefix + `/export_ins/export`,
        method: `post`,
        data: {
          condition: condition,
          etCode: code,
        },
        isLoading: true,
        success: (res) => {
          let printData = Array.isArray(condition.id)
            ? res.objx.data || []
            : [res.objx.data];
          callback && callback(printData);
        },
      });
    },
    handleWebPrintData(datas) {
      let toDo = function (printData) {
        Object.keys(printData).forEach((key) => {
          let value = printData[key];
          if (Array.isArray(value)) {
            printData[key] = loop(value);
          } else if (value === 0) {
            printData[key] = "0";
          }
        });
        return printData;
      };
      let loop = function (data) {
        if (Array.isArray(data)) {
          data.forEach((printData) => {
            printData = toDo(printData);
          });
        } else {
          data = toDo(data);
        }
        return data;
      };
      return loop(datas);
    },
    onBeforePrint(template, callback) {
      let config = this.exportOption;
      if (config.onBeforePrint) {
        config.onBeforePrint(callback, template);
      } else {
        callback();
      }
    },
    exportPrint(code, condition, title, template) {
      this.onBeforePrint(template, () => {
        this.parentTarget.$http({
          url: USER_PREFIX + `/export_template/getByCode`,
          method: `post`,
          data: {
            stringOne: code,
          },
          isLoading: true,
          success: (res) => {
            let exportTemplate = res.objx || {};
            let printJson = JSON.parse(exportTemplate.etText || "{}");
            this.getPrintData(code, condition, (printDatas) => {
              printDatas = this.handleWebPrintData(printDatas);
              openHiPrint(null, printJson, printDatas);
            });
          },
        });
      });
    },
    initExportTemplates() {
      this.parentTarget.$http({
        url: USER_PREFIX + `/export_template/getByCodes`,
        method: `post`,
        data: this.option.codes,
        isLoading: false,
        success: (res) => {
          this.exportTemplates = res.objx || [];
        },
      });
    },
    getTableGrid() {
      let grid = null;
      let tableTarget = this.option.tableTarget
      if (tableTarget) {
        if (typeof tableTarget === "function") {
          grid = tableTarget();
        } else {
          grid = tableTarget;
        }

      } else if (this.option.tableRef) {
        grid = this.parentTarget.$refs[this.option.tableRef];
      }
      return grid;
    },
    tableDefalutHandle(item) {
      let checkRows = [];
      let $grid = this.getTableGrid();


      let condition = null;
      if(this.option.customCondition){
        let condition1 = this.option.customCondition(item);
        if(condition1)condition = condition1;
      }
      if(!condition){
        if ($grid) {
          checkRows = $grid.getCheckboxRecords(true);
        } else {
          checkRows
            = typeof this.option.param === "function"
            ? this.option.param(item)
            : this.option.param;
        }
        let ids = checkRows ? checkRows.map((row) => row.id) : [];
        condition = ids.length ? {id: ids} : null;
      }
      return condition;

      /* if (item.etType === 0 || item.etType === 1) {
        //excel 或 pdf
        let rows = checkRows.map((row) => row.id);
        return rows.length
          ? {
            id: rows,
          }
          : null;
      }
      if (item.etType === 2) {
        //菜鸟打印
        let rows = checkRows.map((row) => row.id);
        return rows.length
          ? {
            id: rows,
          }
          : null;
      } else {
        //网页打印
        let rows = checkRows.map((row) => row.id);
        return rows.length
          ? {
            id: rows,
          }
          : null;
      } */
    },
    initExportData() {
      this.exportOption = this.option;
      this.showContaint = true;
    },
    exportBill(exportTemplate) {
      this.exportOption = this.option;
      let code = exportTemplate.etCode;
      let exportOption = this.option;
      let btnName = exportTemplate.etName;
      let fileName = (exportOption.title || "") + "-" + btnName;
      let $grid = this.getTableGrid();
      let checkRows = [];
      if ($grid) {
        checkRows = $grid.getCheckboxRecords(true);
        if (!checkRows.length) {
          this.$baseAlert(this.$t2("请选择需要导出/打印的数据", "components.baseInputExport.selectDataTip"));
          return;
        }
      }
      let etType = exportTemplate.etType;
      if (exportTemplate.etType === 2) {
        //菜鸟打印
        let condition = this.tableDefalutHandle(exportTemplate);
        let param = {
          etCode: code,
          condition: condition,
        };
        this.cnPrinter(param, exportTemplate);
      } else if (this.exportTypes.includes(etType)) {
        //导出excel
        let conditions = this.tableDefalutHandle(exportTemplate) || [];
        this.$baseConfirm(this.$t2("您确定要导出吗？", "components.baseInputExport.exportTip")).then(() => {
          let condition = $grid
            ? this.tableDefalutHandle(exportTemplate)
            : this.tableDefalutHandle(exportTemplate);
          let param = {
            etCode: code,
            condition: condition,
          };
          this.$commonExportBill(param, fileName, true);
        });
      } else if (exportTemplate.etType === 6) {
        //京东打印
        let condition = this.tableDefalutHandle(exportTemplate);
        let param = {
          etCode: code,
          condition: condition,
        };
        this.jdPrinter(param, exportTemplate);
      } else if (exportTemplate.etType === 7) {
        //拼多多打印
        let condition = this.tableDefalutHandle(exportTemplate);
        let param = {
          etCode: code,
          condition: condition,
        };
        this.pddPrinter(param, exportTemplate);
      } else if (exportTemplate.etType === 8) {
        //唯品会打印
        let condition = this.tableDefalutHandle(exportTemplate);
        let param = {
          etCode: code,
          condition: condition,
        };
        this.vipPrinter(param, exportTemplate);
      } else if (exportTemplate.etType === 9) {
        //小红书打印
        let condition = this.tableDefalutHandle(exportTemplate);
        let param = {
          etCode: code,
          condition: condition,
        };
        this.xhsPrinter(param, exportTemplate);
      } else {
        let condition = $grid
          ? this.tableDefalutHandle(exportTemplate)
          : this.tableDefalutHandle(exportTemplate);
        this.exportPrint(code, condition, fileName, exportTemplate);
      }
    },
    cnPrinter(param, exportTemplate) {
      this.onBeforePrint(exportTemplate, () => {
        openCnPrint({
          prefix: this.option.prefix,
          getParam() {
            return param;
          },
          template: exportTemplate,
          config: this.option,
        });
      });
    },
    jdPrinter(param, exportTemplate) {
      this.onBeforePrint(exportTemplate, () => {
        openJdPrint({
          prefix: this.option.prefix,
          getParam() {
            return param;
          },
          template: exportTemplate,
          config: this.option,
        });
      });
    },
    pddPrinter(param, exportTemplate) {
      this.onBeforePrint(exportTemplate, () => {
        openPddPrint({
          prefix: this.option.prefix,
          getParam() {
            return param;
          },
          template: exportTemplate,
          config: this.option,
        });
      });
    },
    vipPrinter(param, exportTemplate) {
      this.onBeforePrint(exportTemplate, () => {
        openVipPrint({
          prefix: this.option.prefix,
          getParam() {
            return param;
          },
          template: exportTemplate,
          config: this.option,
        });
      });
    },
    xhsPrinter(param, exportTemplate) {
      this.onBeforePrint(exportTemplate, () => {
        openXhsPrint({
          prefix: this.option.prefix,
          getParam() {
            return param;
          },
          template: exportTemplate,
          config: this.option,
        });
      });
    },
    $commonExportBill(param, fileName, multi) {
      let that = this;
      let toDo = function () {
        return that.parentTarget.$http({
          url: that.option.prefix + "/export_ins/export",
          method: `post`,
          data: param,
          isLoading: true,
          success: (res) => {
            downLoadFile(res.objx.data, that);
          },
        });
      };
      if (!multi) {
        this.$baseConfirm(
          this.$t2("您确定要导出吗？", "components.baseInputExport.exportTip")
        ).then(() => {
          toDo();
        });
      } else {
        toDo();
      }

      function downLoadFile(row, that) {
        let realFileName = fileName ? fileName + "-" + row.uuid : row.uuid;
        let fileUrl
          = configUtil.baseUrl
          + that.option.prefix
          + "/export_ins/download?uuid="
          + row.uuid
          + "&ippaaapp="
          + row.ippaaapp
          + "&n="
          + realFileName;
        var params = {};
        that.parentTarget.$http({
          method: "post",
          url: fileUrl,
          data: params,
          responseType: "blob",
          resultType: "other",
          isLoading: true,
          callback: (res, response) => {
            const blobUrl = window.URL.createObjectURL(res);
            const a = document.createElement("a");
            // a.download = fullName;
            a.download = realFileName;
            a.href = blobUrl;
            a.click();
          },
        });
      }
    },
  },
};
export default modules;
