/**
   * guoj
   * 2020.10.26
   * 回单登记
   */
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 () => {
  let queryItem = "";
  // 获取默认时间
  var sdate = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var edate = Prolog.formatDate(new Date()) + " 23:59:59";
  let dataSelect, selectedRowData;

  //获取下拉框
  getSelectGJ([{ "objectcode": "SIGNSTATUS" }, { "objectcode": "TMS_SHIP_BILLTYPE" }], function (data) {
    data.data.TMS_SHIP_BILLTYPE.unshift({ "text": "", "value": "" });
    dataSelect = data.data;
  });
  let ddfrom;
  //跳转页面
  var carousel = layui.carousel;
  var car = carousel.render({
    elem: "#receiptRegistration_div",
    autoplay: false,
    index: 0,
    arrow: "none",
    indicator: "none",
    anim: "fade",
    width: "100%", //设置容器宽度
    height: "100%"
  });
  //跳转方法
  var tt = "receiptRegistration_zhu_div";

  function changePanel() {
    car.slide(tt);
    tt = tt == "receiptRegistration_xi1" ? "receiptRegistration_zhu_div" : "receiptRegistration_xi1";
  }
  var grid;
  //配送中心table
  var userTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "配送中心编号", type: "ro" },
      { id: "companyname", name: "配送中心名称", type: "ro" }
    ],
    multiselect: false,
    contentType: "application/json",
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyBranch", //数据接口
    type: "post", //数据提交方式，默认为get
    pagebar: { type: "simple" },
    params: JSON.stringify({ "companytype": "S" }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //客户table
  var companyTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "编号", type: "ro" },
      { id: "companyname", name: "名称", type: "ro" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyCustomer", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ companytypes: ["C"] }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //货主table
  var connerTable = {
    columns: [
      { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
      { id: "companycode", name: "编号", type: "ro" },
      { id: "companyname", name: "名称", type: "ro" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyConsignor", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ companytypes: ["H"] }), //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数
  var opts = {
    //terrace显示全部，card分页显示
    skin: "card",
    //renderer:"grid",
    columns: [
      { id: "INDEX", name: "id", type: "ro", width: "80", hidden: true },
      { id: "branchname", name: "配送中心", type: "ro", width: "100" },
      { id: "shipbillno", name: "运单号", type: "ro", width: "100" },
      { id: "consignorname", name: "货主", type: "ro", width: "80" },
      {
        id: "billtype", name: "运单类型", type: "ro", width: "100", render: (v) => {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { id: "linenane", name: "线路名称", type: "ro", width: "80" },
      { id: "billdate", name: "单据日期", type: "ro", width: "120" },
      {
        id: "urgentIdentify", name: "是否急单", type: "ro", width: "120", render: (v) => {
          return v == "01" ? "是" : "否";
        }
      },
      { id: "refbillno", name: "业务单号", type: "ro", width: "120" },
      {
        id: "refbilltype", name: "业务类型", type: "ro", width: "130", render: (v) => {
          return getSelectValue(dataSelect.TMS_SHIP_BILLTYPE, v);
        }
      },
      { id: "shiptoCustomerName", name: "客户名称", type: "ro", width: "80" },
      { id: "shiptoAddress", name: "客户地址", type: "ro", width: "80" },
      { id: "rsumcases", name: "件数", type: "ro", width: "80" },
      { id: "rsumgoodsweight", name: "重量", type: "ro", width: "80" },
      { id: "rsumgoodsvol", name: "体积", type: "ro", width: "80" },
      { id: "memo", name: "备注", type: "ro", width: "80" },
      {
        id: "op", name: "操作", type: "button", align: "center", width: 150, render: function () {
          return "回单登记^receiptRegistration";
        }
      }
    ],
    multiselect: true,
    fixedLast: true,
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", name: "sdate", className: "layui-col-md3", label: "开始时间:", value: sdate },
          { type: "calendar", name: "edate", className: "layui-col-md3", label: "结束时间:", value: edate },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择配送中心",
            readonly: false,
            table: userTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companycode",
            name: "branchid",
            label: "配送中心:"
          },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择货主",
            readonly: false,
            table: connerTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "consignor",
            label: "货主:"
          },
          { type: "input", name: "refbillno", className: "layui-col-md3", label: "业务单号:" },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择客户",
            readonly: false,
            table: companyTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companyid",
            name: "shiptoCustomerId",
            label: "客户:",
            listener: function () {
            }
          },
          { type: "input", name: "shipbillno", className: "layui-col-md3", label: "运单号:" },
          {
            type: "block", className: "layui-col-md6 form_btn_left",
            list: [
              { type: "button", className: "btn-normal", name: "querycarr", value: "查 询" },
              { type: "newcolumn" },
              { type: "button", name: "car_Reset", className: "normal", value: "重 置" }
            ]
          },
          {
            type: "block", className: "layui-col-md6 right",
            list: [
              { type: "button", className: "btn-addBtn btn-normal", name: "returnAll", value: "批量回单" }
            ]
          }
        ]
      }],
    beforeLoadData: function (res) {
      res.data.list.forEach((item, index) => {
        item.INDEX = index + "";
      });
      return res;
    },
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/returnOrderRegister/returnOrderRegisterQuery",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ sdate: sdate, edate: edate }),//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("receiptRegistration_zhu");
  grid.getToolBarForm().setFormData({ "systemId": "prolog-healthy-wms" });
  grid.loadData();
  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querycarr") {
      var jsonData = grid.getToolBarForm().getFormData();
      jsonData.sdate = jsonData.sdate ? Prolog.formatDate(jsonData.sdate) + " 00:00:00" : "";
      jsonData.edate = jsonData.edate ? Prolog.formatDate(jsonData.edate) + " 23:59:59" : "";
      if (jsonData.sdate > jsonData.edate) {
        layer.msg("开始时间不能大于结束时间");
        return false;
      }
      jsonData.branchid = jsonData.branchid ? JSON.parse(jsonData.branchid)[0] : "";
      jsonData.shiptoCustomerId = jsonData.shiptoCustomerId ? JSON.parse(jsonData.shiptoCustomerId)[0] : "";
      jsonData.consignor = jsonData.consignor ? JSON.parse(jsonData.consignor)[0] : "";
      grid.setParams(JSON.stringify(jsonData));
      grid.reload();
    }
    //重置
    if (name == "car_Reset") {
      grid.getToolBarForm().getDForm().setText("branchid", "");
      grid.getToolBarForm().getDForm().setText("shiptoCustomerId", "");
      grid.getToolBarForm().getDForm().setText("consignor", "");
      grid.getToolBarForm().clear();
      grid.getToolBarForm().setFormData({ sdate: sdate, edate: edate });
    }
    //批量回单
    if (name == "returnAll") {
      let dataList = getDeleteAll(grid);
      if (dataList == null || dataList == "") {
        layer.msg("请选择一行数据");
        return;
      }
      for (var i = 0; i < dataList.length; i++) {
        dataList[i] = grid.getRowData(dataList[i]);
      }
      //调用ajax方法
      utilAjaxGJ(UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/returnOrderRegister/returnOrderRegister", "post", JSON.stringify({ list: dataList }), function (data) {
        if (data.success) {
            grid.reload();
        }
      }, "application/json");
    }
  });
  //回单登记
  window.receiptRegistration = function (rid) {
    let rdata = grid.getRowData(rid);
    rdata.signCases = rdata.rsumcases;
    selectedRowData = JSON.parse(JSON.stringify(rdata));
    ddfrom = new PlgForm({
      renderer: "receiptRegistration_xi",
      items: [
        { type: "settings", labelWidth: 90, labelAlign: "right" },
        {
          type: "row",
          list: [
            { type: "settings", position: "label-left", width: 300, labelWidth: 90 },
            { type: "hidden", name: "shipbillid", label: "id:", className: "layui-col-md3" },
            {
              type: "input", name: "branchid", label: "配送中心:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "branchname", label: "机构名称:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "shipbillno", label: "运单号:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "refbillno", label: "单据编号:", className: "layui-col-md3", disabled: true
            },
            {
              type: "combo", name: "refbilltype", label: "单据类型:", className: "layui-col-md3", disabled: true, options: dataSelect.TMS_SHIP_BILLTYPE
            },
            {
              type: "input", name: "carriername", label: "承运商:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "shiptoCustomerName", label: "收货人:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "rsumcases", label: "发货件数:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "shipfromAddress", label: "发货地址:", className: "layui-col-md3", disabled: true
            },
            {
              type: "input", name: "shiptoAddress", label: "收货地址:", className: "layui-col-md6", disabled: true
            },
            { type: "calendar", name: "signdate", label: "签收时间:", dateFormat: "%Y-%m-%d %H:%i", className: "layui-col-md3" },
            {
              type: "input", name: "signer", label: "签收人 :", className: "layui-col-md3"
            },
            { type: "combo", name: "signstatus", label: "签收状态:", className: "layui-col-md3", options: dataSelect.SIGNSTATUS },
            { type: "input", name: "signCases", placeholder: "请输入数字", validate: "ValidNumeric", maxLength: 8, label: "签收件数:", className: "layui-col-md3", required: true },
            {
              type: "input", name: "rejectreason", label: "拒收原因 :", className: "layui-col-md6"
            },
            {
              type: "input", name: "memo", label: "备注 :", className: "layui-col-md6"
            }
          ]
        }]
    });
    ddfrom.disableItem("signCases");
    ddfrom.disableItem("rejectreason");
    ddfrom.setFormData(rdata);
    ddfrom.getCombo("signstatus").attachEvent("onChange", function (value) {
      if (value == "01") {
        let dataItem = ddfrom.getFormData();
        ddfrom.disableItem("signCases");
        ddfrom.disableItem("rejectreason");
        ddfrom.setItemValue("signCases", dataItem.rsumcases);
        ddfrom.setItemValue("rejectreason", "");
      }
      if (value == "02") {
        ddfrom.enableItem("signCases");
        ddfrom.enableItem("rejectreason");
        ddfrom.setItemValue("signCases", 1);
        ddfrom.setItemValue("rejectreason", "");
      }
      if (value == "03") {
        ddfrom.disableItem("signCases");
        ddfrom.enableItem("rejectreason");
        ddfrom.setItemValue("signCases", 0);
        ddfrom.setItemValue("rejectreason", "");
      }
    });
    changePanel();
    queryItem = {
      bizId: rdata.shipbillid,
      bizType: "0",
      enterpriseid: userGJ.p_enterpriseid
    };
    getImgList(queryItem);
    setUploadMouth(queryItem);
  };

  //查询图片
  var imgList = [];
  function getImgList(data) {
    imgList = [];
    $("#receiptRegistration_xi2").html("");
    utilAjaxGJ("/app/biz-file/list", "post", data, (data) => {
      let imgListData = data.data;
      for (var i = 0; i < imgListData.length; i++) {
        imgList.push({ fileUrl: imgListData[i].file.fileUrl })
        $("#receiptRegistration_xi2").append("<img onclick='showCustImg(this)'  class='leftImg' src='" + imgListData[i].file.fileUrl + "'/>" +
          "<div class='deleteCustomerImg' id='" + imgListData[i].id + "' onclick='deletecustImg(this)'>X</div>");
      }
      $("#receiptRegistration_xi2").append("<img id='receiptRegistrationAddImg' class='leftImg' src='/img/addimg.png'/>");
      setUploadMouth(queryItem);
    });

  }
  //设置上传
  function setUploadMouth(data) {
    var token = Prolog.reloadToken();
    if (token == null || token == "") {
      PlgDialog.msg("登录状态异常，请重新登录！");
      window.location.href = "/menu?path=login";
      return;
    }
    var upload = layui.upload;
    upload.render({
      elem: "#receiptRegistrationAddImg",
      url: "/app/biz-file/upload",
      accept: "images",
      field: "files",
      acceptMime: "image/*",
      headers: { "Authorization": token },
      data: data,
      contentType: "multipart/form-data",
      size: 10 * 1024,
      before: function () { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
        PlgDialog.load(2, { shade: [0.6, "#fff"] });
      },
      done: function () {
        layer.closeAll();
        getImgList(queryItem);
      },
      error: function () {
        layer.closeAll();
        layer.msg("失败");
      }
    });
  }
  //删除
  window.deletecustImg = function (data) {
    utilAjaxGJ("/app/biz-file/del", "post", { ids: data.id }, () => {
      layer.msg("成功");
      getImgList(queryItem);
    });
  };
  //展示图片
  window.showCustImg = function (data) {
    let index = 0;
    for(let i=0;i<imgList.length;i++){
      let t = imgList[i];
      if (t.fileUrl == data.src) index = i;
    }
    imageView(imgList,index);
  };
  //返回
  document.querySelector("#receiptRegistration_back1").onclick = function () {
    changePanel();
  };
  //确认
  document.querySelector("#receiptRegistration_save").onclick = function () {
    //信息比对
    let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/returnOrderRegister/returnOrderRegister";
    //数据修改
    var feik = ddfrom.validate();
    if (!feik) {
      return;
    }
    let datai = ddfrom.getFormData();
    datai.list = [selectedRowData];
    if (datai.signstatus == null || datai.signstatus == "") {
      layer.msg("签收状态不为空");
      return;
    }
    if (datai.signstatus != "01" && (datai.rejectreason == null || datai.rejectreason == "")) {
      layer.msg("拒收原因不能为空");
      return;
    }
    if (datai.signstatus != "03" && datai.signCases * 1 <= 0) {
      layer.msg("签收件数不能小于0");
      return;
    }
    datai.signTime = FormatDateTime(datai.signTime);
    //调用ajax方法
    utilAjaxGJ(url, "post", JSON.stringify(datai), function (data) {
      if (data.success) {
        grid.reload();
        changePanel();
      }
    }, "application/json");
  };
};