/**
 * zzx
 * 2020.07.29
 * 回单补录
 */
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 master_grid, edit_form;
  var token = Prolog.reloadToken();
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,
}
  var pload;
  var uploadImgNum = 0; // 需要上传的图片数量

  // 跳转页面
  var carousel = layui.carousel;
  carousel.render({
    elem: "#receiptSupplement",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", // 设置容器宽度
    height: "100%"
  });
  // 切换页面
  function changePanel(name) {
    var slideList = ["#receiptSupplement_master", "#receiptSupplement_details"];
    for (var i = 0; i < slideList.length; i++) {
      if (slideList[i] == name) {
        $(name).css("display", "block");
      }
      else {
        $(slideList[i]).css("display", "none");
      }
    }
  }
  // 返回
  $(document).on("click", "#receiptSupplement_details_return", function () {
    changePanel("#receiptSupplement_master");
  });

  // 获取默认时间
  var startTime = Prolog.formatDate(new Date(), "%YY-%MM") + "-01";
  var endTime = Prolog.formatDate(new Date());
  // 获取下拉框
  var dataSelect = {
    TMS_URGENTIDENTIFY: [],
    TMS_REF_BILLTYPE: [],
    TMS_SHIP_BILLTYPE: []
  };
  getSelectGJ([
    { "objectcode": "TMS_URGENTIDENTIFY" },
    { "objectcode": "TMS_REF_BILLTYPE" },
    { "objectcode": "TMS_SHIP_BILLTYPE" }], function (data) {
      dataSelect = data.data;
      dataSelect.TMS_URGENTIDENTIFY.unshift({ "value": "", "text": "" });
    });

  // 配送中心table
  var branchTable = {
    // 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: 100 },
      {
        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/queryCompanyBranch",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  // 主页grid
  var master_grid_opts = {
    skin: "card",
    columns: [
      { id: "seqno", name: "运单id", type: "ro", width: "130", hidden: true },
      { id: "branchname", name: "配送中心", type: "ro", width: 120 },
      { id: "shipbillno", name: "运单号", type: "ro", width: 120 },
      { id: "consignorname", name: "货主", type: "ro", width: 120 },
      {
        id: "billtype", name: "运单类型", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { id: "linenane", name: "线路名称", type: "ro", width: 120 },
      { id: "billdate", name: "单据日期", type: "ro", width: 120 },
      {
        id: "urgentIdentify", name: "是否急单", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.TMS_URGENTIDENTIFY, v);
        }
      },
      { id: "refbillno", name: "业务单号", type: "ro", width: 120 },
      {
        id: "refbilltype", name: "业务类型", type: "ro", width: 120, render: function (v) {
          return getSelectValue(dataSelect.TMS_REF_BILLTYPE, v);
        }
      },
      { id: "customerName", name: "承运商", type: "ro", width: 120 },
      { id: "shiptoCustomerName", name: "客户名称", type: "ro", width: 120 },
      { id: "shiptoAddress", name: "客户地址", type: "ro", width: 180 },
      { id: "rsumcases", name: "件数", type: "ro", width: 120 },
      { id: "rsumgoodsweight", name: "重量(KG)", type: "ro", width: 120 },
      { id: "rsumgoodsvol", name: "体积(m³)", type: "ro", width: 120 },
      { id: "memo", name: "备注", type: "ro", width: 120 }
    ],
    toolbar: [
      { type: "settings", labelWidth: 70, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", className: "layui-col-md3", name: "sdate", label: "开始时间:", value: startTime },
          { type: "calendar", className: "layui-col-md3", name: "edate", label: "结束时间:", value: endTime },
          {
            type: "selectTable",
            className: "layui-col-md3",
            placeholder: "请选择配送中心",
            readonly: false,
            table: branchTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "branchidList",
            label: "配送中心:",
            listener: function (Grid) {
              setMethod(Grid, branchTable, function () { });
            }
          },
          { type: "input", className: "layui-col-md3", name: "shipbillno", label: "运单号:" },
          { type: "input", className: "layui-col-md3", name: "refbillno", label: "业务单号:" },
          { type: "combo", className: "layui-col-md3", readonly: true, name: "urgentIdentify", label: "是否急单:", options: dataSelect.TMS_URGENTIDENTIFY },
          { type: "input", className: "layui-col-md3", name: "lineno", label: "运输线路:" },
          {
            type: "block", className: "layui-col-md2 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重 置" }

            ]
          },
          {
            type: "block", className: "layui-col-md1 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_receipt", value: "图片补录" }
            ]
          }
        ]
      }
    ],
    fixedLast: false, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: false, // 是否支持多选
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/onTheWay/returnSetimgQuery", // 数据接口
    type: "post", // 数据提交方式，默认为get
    params: JSON.stringify({ sdate: startTime, edate: endTime }),
    page: true, // 是否启用分页
    contentType: "application/json",
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("receiptSupplement_master");
  master_grid.loadData();
  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    switch (name) {
      case "master_search":
        var request = master_grid.getToolBarForm().getFormData();
        request.sdate = request.sdate ? Prolog.formatDate(request.sdate) : "";
        request.edate = request.edate ? Prolog.formatDate(request.edate) : "";
        request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : "";
        dealNullQueryCondition(request);
        delete request.branchidList;
        master_grid.setParams(JSON.stringify(request));
        master_grid.reload();
        break;
      case "master_reset":
        master_grid.getToolBarForm().clear();
        master_grid.getToolBarForm().setFormData({ sdate: startTime, edate: endTime });
        master_grid.getToolBarForm().setText("branchidList", "");
        break;
      case "master_receipt":
        var rid = master_grid.getSelectedRowId();
        if (!rid) {
          layer.msg("请选择数据");
          return false;
        }
        var rdata = master_grid.getRowData(rid);
        rdata.billtypename = getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, rdata.billtype);
        edit_form.setFormData(rdata);
        $("#receiptSupplement_imgList").html("");
        uploadImgNum = 0;
        changePanel("#receiptSupplement_details");
        break;
    }
  });

  // 注册详情页form表单
  let uploadLabel = "";
  uploadLabel += "签收图片:";
  uploadLabel += "<button type='button' class='layui-btn' id='receiptSupplement_upload_btn' style='margin-left: 10px;'>上传图片</button>";
  uploadLabel += "<div class=\"layui-upload-list\">";
  uploadLabel += "  <blockquote class='layui-elem-quote layui-quote-nm' style='margin-top: 10px;'>";
  uploadLabel += "    <div class='layui-upload-list' id='receiptSupplement_imgList'></div>";
  uploadLabel += "  </blockquote>";
  uploadLabel += "  <p id=\"receiptSupplement_text\"></p>";
  uploadLabel += "</div>";

  let edit_form_opts = {
    renderer: "receiptSupplement_edit_form",
    items: [
      { type: "settings", labelAlign: "left", labelWidth: 90 },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "branchname", label: "配送中心:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "shipbillno", label: "运单号:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "consignorname", label: "货主:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "billtypename", label: "运单类型:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "linenane", label: "线路名称:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "billdate", label: "单据日期:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "customerName", label: "承运商:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "appointDriver", label: "司机:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "appointVehicle", label: "车牌号:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "shiptoCustomerName", label: "客户:", readonly: true },
          { type: "input", className: "layui-col-md6 no-border", name: "shiptoAddress", label: "客户地址:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "rsumcases", label: "总件数:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "rsumgoodsweight", label: "总重量(KG):", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "rsumgoodsvol", label: "总体积(m³):", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "signdate", label: "签收时间:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md3 no-border", name: "signer", label: "签收人:", readonly: true },
          { type: "input", className: "layui-col-md3 no-border", name: "signqty", label: "签收件数:", readonly: true },
          { type: "input", className: "layui-col-md6 no-border", name: "signstatus", label: "签收状态:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md12 no-border", name: "memo", label: "备注:", readonly: true }
        ]
      },
      {
        type: "row",
        list: [
          { type: "label", className: "layui-col-md9 type_label", name: "", label: uploadLabel, labelWidth: 800 },
          { type: "hidden", name: "imgurl", label: "图片上传地址:" }
        ]
      }
    ]
  };
  edit_form = new PlgForm(edit_form_opts);

  layui.use("upload", function () {
    var upload = layui.upload;
    var uploadInst = upload.render({
      elem: "#receiptSupplement_upload_btn",
      url: "/app/biz-file/upload",
      headers: {
        Authorization: token
      },
      data: {
        bizId: edit_form.getFormData().seqno,
        bizType: 0,
        enterpriseid: userinfo.p_enterpriseid,
        indexCol1: "01"
      },
      accept: "images",
      acceptMime: "image/*",
      field: "files",
      multiple: true,
      auto: false,
      number: 5,
      bindAction: "#receiptSupplement_edit_imgsave",
      size: 10 * 1024,
      choose: function (obj) {
        var files = this.files = obj.pushFile();
        //预读本地文件示例，不支持ie8
        obj.preview(function (index, file, result) {
          uploadImgNum++;
          let html = "";
          html += "<div style='display: inline-block;margin-right: 20px;'>";
          html += "   <img src='" + result + "' alt='" + file.name + "' class='receiptSupplement_upload_image'>";
          html += "   <button class='layui-btn layui-btn-xs layui-btn-danger image_delete'>删除</button>";
          html += "</div>";
          let htmljs = $(html);
          // 删除
          htmljs.find(".image_delete").on("click", function () {
            delete files[index]; // 删除对应的文件
            htmljs.remove();
            uploadInst.config.elem.next()[0].value = ""; //清空 input file 值，以免删除后出现同名文件不可选
            uploadImgNum--;
          });
          // 点击展示
          htmljs.find(".receiptSupplement_upload_image").on("click", function () {
            imageView([{ fileUrl: result }]);
          });

          $("#receiptSupplement_imgList").append(htmljs);
        });
      },
      done: function (res, index) {
        PlgDialog.close(pload);
        //如果上传失败
        if (res.success) {
          return delete this.files[index];
        }
        return layer.msg("图片上传失败");
      },
      allDone: function (obj) {
        // 当文件全部被提交后触发
        if (obj.total === obj.successful) {
          PlgDialog.close(pload);
          PlgDialog.msg("操作成功！");
          changePanel("#receiptSupplement_master");
          master_grid.reload();
        }
      },
      error: function () {
        //演示失败状态，并实现重传
        var errorText = $("#receiptSupplement_text");
        errorText.html("<span style=\"color: #FF5722;\">上传失败</span> <a class=\"layui-btn layui-btn-xs demo-reload\">重试</a>");
        errorText.find(".demo-reload").on("click", function () {
          uploadInst.upload();
        });
      }
    });
  });

  // 保存
  $("#receiptSupplement_details_save").on("click", function () {
    let { shipbillid, shipbillno, seqno, appointVehicle, branchid, branchname } = edit_form.getFormData();
    let request = {
      shipbillid,
      shipbillno,
      seqno,
      appointVehicle,
      branchid,
      branchname
    };
    pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/onTheWay/returnSetimg", type: "post", contentType: "application/json", data: JSON.stringify({ volist: [request] }),
      success: function (res) {
        if (res.success) {
          if (!uploadImgNum) {
            PlgDialog.close(pload);
            PlgDialog.msg(res.message);
            changePanel("#receiptSupplement_master");
            master_grid.reload();
          }
          else {
            $("#receiptSupplement_edit_imgsave").click();
          }
          return true;
        }
                return false;

      }, error: function () { PlgDialog.close(pload); return false; }
    });
  });
};