/**
 * jiw
 * 2019.1.15
 * 打印模版维护
 */

 import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
 import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';
 export default () => {
  //var userinfo = window.localStorage.getItem("userinfo");
  //if (userinfo != null) userinfo = JSON.parse(userinfo);
  var userinfo = {
    p_id: '',
    p_username: '',
    p_workernumber: '',
    p_nickname: '',
    p_phone: null,
    p_email: null,
    p_companyid: '',
    p_enterpriseid: '',
    p_organizationid: '',
    p_companyname: '',
    p_orgname: '',
    p_enterprisename: '',
    p_usertype: '',
    p_lastlogindate: '',
    p_lastmodipassdate: null,
    p_validdate: '',
    p_import_batchno: null,
    p_data_source: null,
    forceModifyPasswdFlag: false,
    vehicle: null,
  }
  let form1;

  // 承运商table
  var carrierTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "承运商编号", type: "ro" },
      { id: "companyname", name: "承运商名称", type: "ro" }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 70 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "companycode", label: "承运商编号:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyCarrier",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "Y" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  //获取通用参照数据
  var rsp_temptype = [],
    rsp_branchid = [];
  Prolog.ajax({
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/company/list-by-type",
    type: "post",
    contentType: "application/x-www-form-urlencoded",
    data: { "types": "S" },
    async: false,
    success: function (data) {
      if (data.success) {
        rsp_branchid.push({ text: "", value: "" });
        for (var i = 0; i < data.data.length; i++) {
          rsp_branchid.push({ text: data.data[i].text, value: data.data[i].value });
        }
      }
    },
    error: function () { PlgDialog.msg("接口调用失败"); }
  });
  var req = [{ "objectcode": "sys_print_templet_temptype" }];
  Prolog.ajax({
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/refdata/dtl/dd-list",
    type: "post",
    contentType: "application/json",
    data: JSON.stringify(req),
    async: false,
    success: function (data) {
      if (data.success) {
        bindRefdata(rsp_temptype, data.data.sys_print_templet_temptype, true);
      }
    },
    error: function () { PlgDialog.msg("接口调用失败"); }
  });

  var ptUpload = layui.upload,
    grid = null;
  var param = { "pageNum": 1, "pageSize": 10 };
  var type = 0;

  //滑屏
  var carousel = layui.carousel;
  var car = carousel.render({
    elem: "#printTemplate_grid",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });

  function changePanel(name) {
    car.slide(name);
  }

  //返回主页面
  $("#printTemplate_btn_back").click(function () {
    changePanel("printTemplate_grid_01");
    return false;
  });

  gridInit();


  //主页面Grid
  function gridInit() {
    var numOpts = {
      skin: "terrace",
      rowId: "tempid",
      columns: [
        { id: "tempid", name: "ID", type: "ro", width: 100, hidden: true },
        { id: "branchid", name: "仓", align: "center", type: "ro", width: 150, hidden: true, render: function (v) { return Prolog.getNameByID(rsp_branchid, v); } },
        { id: "configname", name: "方案名称", align: "left", type: "ro", width: 200 },
        { id: "configid", name: "方案编号", align: "left", type: "ro", width: 150 },
        { id: "configid", name: "方案编号", align: "left", type: "ro", width: 150 },
        { id: "shipvendorname", name: "承运商", type: "ro", width: 150 },
        { id: "temptype", name: "模板类型", align: "center", type: "ro", width: 100, render: function (v) { return Prolog.getNameByID(rsp_temptype, v); } },
        { id: "tempname", name: "模板文件名", align: "left", type: "ro", width: 150 },
        { id: "tempwidth", name: "模板宽度", type: "ro", align: "right", width: 100 },
        { id: "tempheight", name: "模板高度", type: "ro", align: "right", width: 100 },
        {
          id: "status",
          name: "是否启用",
          align: "center",
          type: "ro",
          width: 100,
          render: function (v) {
            return "<input disabled=\"disabled\" type=\"checkbox\" " + (v === 1 ? "checked=\"\"" : "") + " name=\"chk_status\" lay-skin=\"switch\" lay-filter=\"chk_status\" lay-text=\"ON|OFF\">";
          }
        },
        { id: "temppath", name: "模板路径", type: "ro", width: 300, hidden: true },
        { id: "remark", name: "备注", type: "ro", width: 200 },
        {
          id: "op",
          name: "操作",
          type: "button",
          align: "center",
          width: 150,
          render: function () {
            return "详情^res_printTemplate_showClick,修改^res_printTemplate_editClick,删除^res_printTemplate_delClick";
          }
        }

      ],
      multiselect: false,
      fixedLast: true,
      toolbar: [
        { type: "input", width: 300, name: "parameter", label: "查询条件:", placeholder: "请输入编号/名称" }, { type: "newcolumn" },
        { type: "button", name: "btn_search", value: "查询" }, { type: "newcolumn" },
        { type: "newcolumn" },
        { type: "button", name: "btn_reset", className: " normal", value: "重置" },
        { type: "newcolumn" },
        { type: "button", name: "btn_add", className: "plg-toolbar-right", value: "<i class='layui-icon layui-icon-add-1'></i>新增" }, { type: "newcolumn" }
      ],
      formData: [],

      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/printconf/list",
      type: "get",
      params: param,
      contentType: "application/x-www-form-urlencoded",
      page: true,
      totalCount: "totalCount"
    };
    //分页参数 pageSize pageNum
    grid = new PlgGrid(numOpts);
    grid.renderTo("printTemplate_grid_01");
    grid.loadData();
    grid.getGrid().enableEditEvents(true, false, true);

    $("#printTemplate_grid_01").addClass("layui-form");
    grid.attachEvent("onDataReady", function () {
      setTimeout(function () {
        layui.form.render();
      }, 200);
    });

    // 双击行
    grid.on("onRowDblClicked", function () {
      show_printTemplateinfo(grid.getSelectedRowId(), grid.getSelectedRowData());
    });

    //工具栏键盘事件
    grid.getToolBarForm().attachEvent("onKeyDown", function (inp, ev) {
      if (ev.key == "Enter") {
        grid.setParams(grid.getToolBarForm().getFormData());
        grid.reload();
      }
    });

    //工具栏按钮事件
    grid.attachToolBarEvent("onButtonClick", function (name) {
      // 查询
      if (name === "btn_search") {
        grid.setParams(grid.getToolBarForm().getFormData());
        grid.reload();
      }
      // 新增
      else if (name === "btn_add") {
        addprintTemplate();
      }
      else if (name == "btn_reset") {
        grid.getToolBarForm().clear();
      }
    });
  }

  //添加打印模版
  function addprintTemplate() {
    type = 0;
    var str = "<div class=\"layui-col-lg12\" id=\"printTemplate_grid_add_content\"></div>";
    $("#printTemplate_grid_sub").html(str);

    changePanel("printTemplate_grid_01_edit");
    printTemplateFormInit(0, { branchid: userinfo.p_companyid });
  }

  $("#btn_save_printTemplate").click(function () {
    var b = form1.validate();
    if (!b) return;
    var fd = form1.getFormData();
    fd.ins_dt = null;
    fd.ins_usr_id = null;
    fd.lst_upd_dt = null;
    fd.lst_upd_usr_id = null;
    if (type === 0) {
      save_printTemplate(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/printconf/create", "post", "application/json", JSON.stringify([fd]));
    }
    else if (type === 1) {
      save_printTemplate(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/printconf/update", "post", "application/x-www-form-urlencoded", fd);
    }
  });

  //打印模版表单
  function printTemplateFormInit(ntype, rdata) {
    var tit = "新增打印模版";
    var rediv = "printTemplate_grid_add_content";
    if (ntype === 1) {
      tit = "打印模版 [" + rdata.configname + "] 信息修改";
      rediv = "printTemplate_grid_sub";
    }
    $("#printTemplate_span_title").html(tit);
    $("#printTemplate_grid_sub").removeClass("ul_bg");
    $("#btn_save_printTemplate").show();
    $("#" + rediv).html("");
    var formcfg = {
      renderer: rediv,
      items: [
        { type: "settings", labelAlign: "right", labelWidth: 80 },
        {
          type: "row",
          list: [
            { type: "hidden", name: "tempid" },
            { type: "combo", readonly: true, disabled: true, name: "branchid", label: "仓号:", className: "layui-col-md3", options: rsp_branchid, validate: "NotEmpty", required: true },
            {
              type: "selectTable",
              className: "layui-col-md3",
              placeholder: "请选择承运商",
              readonly: false,
              table: carrierTable,
              tableWidth: 600,
              tableHeight: 500,
              fieldText: "companyname",
              fieldValue: ["companyid", "companyname"],
              name: "shipvendoridList",
              label: "承运商:",
              listener: {
                "init": function (Grid) {
                  setMethod(Grid, carrierTable, function () { });
                },
                "afterClose": function (text, value) {
                  if (!value) return;
                  let selectedData = JSON.parse(value);
                  if (selectedData.length > 0) {
                    form1.setItemValue("shipvendorname", selectedData[0].companyname);
                    form1.setItemValue("shipvendorid", selectedData[0].companyid);
                  }
                  else {
                    form1.setItemValue("shipvendorname", "");
                    form1.setItemValue("shipvendorid", "");
                  }
                }
              }
            },
            { type: "hidden", name: "shipvendorname" },
            { type: "hidden", name: "shipvendorid" },
            { type: "combo", readonly: true, name: "temptype", label: "模版类型:", className: "layui-col-md3", options: rsp_temptype, validate: "NotEmpty", required: true }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", name: "configname", label: "方案名称:", className: "layui-col-md3", validate: "NotEmpty", required: true },
            { type: "input", name: "configid", label: "方案编号:", className: "layui-col-md3", validate: "NotEmpty", required: true },
            { type: "checkbox", name: "status", label: "是否启用:", className: "layui-col-md3" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", name: "tempwidth", label: "模版宽度:", className: "layui-col-md2", validate: "ValidNumeric" },
            { type: "label", label: "厘米", className: "layui-col-md1" },
            { type: "input", name: "tempheight", label: "模版高度:", className: "layui-col-md2", validate: "ValidNumeric" },
            { type: "label", label: "厘米", className: "layui-col-md1" },
            { type: "input", name: "remark", label: "备注:", className: "layui-col-md3" }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", name: "tempname", label: "模板文件名:", className: "layui-col-md3", placeholder: "请上传文件", readonly: true },
            { type: "input", name: "temppath", label: "模板路径:", className: "layui-col-md6", placeholder: "请选择文件", readonly: true, validate: "NotEmpty", required: true },
            {
              type: "row",
              list: [
                { type: "button", className: "btnUpload", name: "btn_upload", value: "上传" }
              ]
            }
          ]
        }
      ]
    };
    form1 = new PlgForm(formcfg);
    if (ntype === 1) {
      form1.getDForm().disableItem("branchid");
      uploadData = { "tempid": rdata.tempid };
      rdata.shipvendoridList = rdata.shipvendorid ? JSON.stringify([{ companyid: rdata.shipvendorid, companyname: rdata.shipvendorname }]) : "[]";
      form1.setText("shipvendoridList", rdata.shipvendorname || "");
    }
    form1.setFormData(rdata);

    ptUpload.render({
      headers: {
        "Authorization": localStorage.getItem("authorization")
      },
      elem: ".btnUpload",
      url: "/app/biz-file/upload",
      size: 1024,
      accept: "file",
      exts: "grf",
      field: "files",
      data: {
        bizId: "1",
        bizType: 0,
        enterpriseid: userinfo.p_enterpriseid,
        indexCol1: "02"
      },
      choose: function (obj) {
        form1.setItemValue("tempname", "");
        obj.preview(function (index, file) {
          form1.setItemValue("tempname", file.name);
        });
      },
      done: function (res) {
        if (res.success)
          form1.setItemValue("temppath", res.data[0].file.fileUrl);
        else
          setTimeout(() => { PlgDialog.alert(res.message == null ? "接口调用失败" : res.message); }, 300);
      }
    });
  }


  //打印模版信息保存
  function save_printTemplate(grid, url, type, contentType, formData) {
    var pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    var rep = null;
    Prolog.ajax({
      url: url,
      type: type,
      contentType: contentType,
      data: formData,
      success: function (data) {
        PlgDialog.close(pload);
        rep = data;
        if (data.success) {
          PlgDialog.msg(data.message);
          setTimeout(function () {
            changePanel("printTemplate_grid_01");
            grid.reload();
          }, 10);
        }
        else {
          setTimeout(() => { PlgDialog.alert(data.message == null ? "接口调用失败" : data.message); }, 300);
        }
      },
      error: function () {
        PlgDialog.close(pload);
        PlgDialog.msg("接口调用失败");
      }
    });
    return rep;
  }

  //查看打印模版详细
  function show_printTemplateinfo(rid, rdata) {
    grid.selectRowById(rid);
    $("#btn_save_printTemplate").hide();
    $("#printTemplate_span_title").html("打印模版 [" + rdata.configname + "] 信息查看");
    changePanel("printTemplate_grid_01_edit");
    $("#printTemplate_grid_sub").removeClass();

    new PlgPanel({
      renderer: "printTemplate_grid_sub",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            {
              label: "方案名称",
              value: rdata.configname
            },
            {
              label: "方案编号",
              value: rdata.configid
            },
            {
              label: "仓号",
              value: Prolog.getNameByID(rsp_branchid, rdata.branchid)
            },
            {
              label: "承运商",
              value: rdata.shipvendorname
            },
            {
              label: "模版类型",
              value: Prolog.getNameByID(rsp_temptype, rdata.temptype)
            },
            {
              label: "模板宽度",
              value: rdata.tempwidth
            },
            {
              label: "模板高度",
              value: rdata.tempheight
            },
            {
              label: "是否启用",
              value: rdata.status == "1" ? "是" : "否"
            },
            {
              label: "模版路径",
              value: rdata.temppath,
              layoutCol: 6
            },
            {
              label: "备注",
              value: rdata.remark,
              layoutCol: 6
            }
          ],
          [
            {
              label: "创建人",
              value: rdata.createby
            },
            {
              label: "创建时间",
              value: rdata.createdate
            },
            {
              label: "修改人",
              value: rdata.lastmodifyby
            },
            {
              label: "修改时间",
              value: rdata.lastmodifydate
            }
          ]
        ]
      }
    });
  }

  function bindRefdata(rsp, data, addNsN) {
    if (addNsN) {
      rsp.push({ text: "", value: "" });
    }
    for (var i = 0; i < data.length; i++) {
      rsp.push({ text: data[i].text, value: data[i].value });
    }
  }

  window.res_printTemplate_editClick = function (rid, rdata) {
    grid.selectRowById(rid);
    type = 1;
    changePanel("rulefactor_grid_01_edit");
    printTemplateFormInit(1, rdata);
    return false;
  };
  window.res_printTemplate_delClick = function (rid) {
    Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/printconf/batch-delete", "post", "application/json", JSON.stringify([rid]), false);
    return false;
  };
  window.res_printTemplate_showClick = function (rid, rdata) {
    grid.selectRowById(rid);
    show_printTemplateinfo(rid, rdata);
    return false;
  };
}