/**
   * guoj
   * 2020.10.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 () => {
  let queryItem = "";
  let handoverNumber, volist = []; // 判断是单个交接还是批量交接
  // 获取默认时间
  var startdate = Prolog.formatDate(new Date(), "%YY-%MM") + "-01 00:00:00";
  var enddate = Prolog.formatDate(new Date()) + " 23:59:59";

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

  function changePanel() {
    car.slide(tt);
    tt = tt == "customerHandover_xi1" ? "customerHandover_zhu_div" : "customerHandover_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: "seqno", name: "id", type: "ro", width: "120", hidden: true },
      { id: "branchname", name: "配送中心", type: "ro", width: "100" },
      { id: "shipbillno", name: "运单号", type: "ro", width: "100" },
      { id: "consignorname", name: "货主", type: "ro", width: "120" },
      { id: "loadbillno", name: "装车单号", type: "ro", width: "120" },
      {
        id: "billtype", name: "运单类型", type: "ro", width: "100", render: (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: (v) => {
          return v == "01" ? "是" : "否";
        }
      },
      { id: "refbillno", name: "业务单号", type: "ro", width: "120" },
      {
        id: "refbilltype", name: "业务类型", type: "ro", width: "130", render: (v) => {
          return getSelectValue(dataSelect.TMS_REF_BILLTYPE, v);
        }
      },
      { id: "shiptoCustomerName", name: "客户名称", type: "ro", width: "120" },
      { id: "shiptoAddress", name: "客户地址", type: "ro", width: "120" },
      { id: "rsumcases", name: "件数", type: "ro", width: "120" },
      { id: "rsumgoodsweight", name: "重量", type: "ro", width: "120" },
      { id: "rsumgoodsvol", name: "体积", type: "ro", width: "120" },
      { id: "memo", name: "备注", type: "ro", width: "120" },
      {
        id: "op", name: "操作", type: "button", align: "left", fixed: "right", width: "100", render: function () {
          return "客户交接^customerHandover_handover";
        }
      }
    ],
    multiselect: true,
    fixedLast: true,
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "calendar", name: "startdate", className: "layui-col-md3", label: "开始时间:", value: startdate },
          { type: "calendar", name: "enddate", className: "layui-col-md3", label: "结束时间:", value: enddate },
          {
            className: "layui-col-md3",
            type: "selectTable",
            placeholder: "请选择配送中心",
            readonly: false,
            table: userTable,
            tableWidth: 500,
            tableHeight: 400,
            fieldText: "companyname",
            fieldValue: "companycode",
            name: "branchid",
            label: "配送中心:"
          },
          { type: "input", name: "loadbillno", className: "layui-col-md3", 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: "arrivalConfirmation_print", value: "客户交接" }
            ]
          }
        ]
      }],
    url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/customerHandover/noHandoverShipbillQuery/v1.0",//数据接口
    type: "post",//数据提交方式，默认为get
    contentType: "application/json",
    params: JSON.stringify({ startdate: startdate, enddate: enddate }),//查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };
  //分页参数 pageSize pageNum
  grid = new PlgGrid(opts);
  grid.renderTo("customerHandover_zhu");
  grid.getToolBarForm().setFormData({ "systemId": "prolog-healthy-wms" });
  grid.loadData();
  //按钮添加方法
  grid.attachToolBarEvent("onButtonClick", function (name) {
    //查询
    if (name == "querycarr") {
      let jsonData = grid.getToolBarForm().getFormData();
      jsonData.startdate = jsonData.startdate ? Prolog.formatDate(jsonData.startdate) + " 00:00:00" : "";
      jsonData.enddate = jsonData.enddate ? Prolog.formatDate(jsonData.enddate) + " 23:59:59" : "";
      if (jsonData.startdate > jsonData.enddate) {
        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({ startdate: startdate, enddate: enddate });
    }
    //客户交接
    if (name == "arrivalConfirmation_print") {
      let ids = grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      volist = [];
      let loadbillnoSet = new Set();
      let shiptoCustomerIdSet = new Set();
      let shipgoodsgroupSet = new Set();
      ids.split(",").forEach(item => {
        const element = grid.getRowData(item);
        volist.push(element);
        loadbillnoSet.add(element.loadbillno);
        shiptoCustomerIdSet.add(element.shiptoCustomerId);
        shipgoodsgroupSet.add(element.shipgoodsgroup == "04" || element.shipgoodsgroup == "05" ? "1" : "0");
      });

      if (shiptoCustomerIdSet.size > 1) {
        layer.msg("不同客户的单据不能批量操作");
        return false;
      }
      if (loadbillnoSet.size > 1) {
        layer.msg("不同装车单的单据不能批量操作");
        return false;
      }
      if (shipgoodsgroupSet.size > 1) {
        layer.msg("危险、特管品运单请独立处理");
        return false;
      }
      handoverNumber = volist.length;

      let formData = {
        rsumcases: 0,
        rsumpcs: 0,
        rsumboxnum: 0
      };
      volist.forEach(item => {
        formData.rsumcases = Prolog.floatOper(formData.rsumcases, item.rsumcases, "+");
        formData.rsumpcs = Prolog.floatOper(formData.rsumpcs, item.rsumpcs, "+");
        formData.rsumboxnum = Prolog.floatOper(formData.rsumboxnum, item.rsumboxnum, "+");
      });
      formData = Object.assign({}, volist[0], formData);

      formInit(formData);
    }
  });
  window.customerHandover_handover = function (rid) {
    handoverNumber = 1;
    let rdata = grid.getRowData(rid);
    volist = [rdata];
    formInit(rdata);
  };
  // 注册表单
  function formInit(formData) {
    $("#customerHandover_xi").html("");
    let signstatusEnums = [];
    dataSelect.SIGNSTATUS.forEach(item => {
      if (handoverNumber < 2 || item.value !== "02") {
        signstatusEnums.push(item);
      }
    });
    ddfrom = new PlgForm({
      renderer: "customerHandover_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:" },
            { 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: "rsumpcs", label: "整件数 :", className: "layui-col-md3", disabled: true },
            { type: "input", name: "rsumboxnum", label: "拼箱数 :", className: "layui-col-md3", disabled: true }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", name: "signer", label: "签收人1:", className: "layui-col-md3", required: true },
            { type: "input", name: "signer2nd", label: "签收人2:", className: "layui-col-md3", hidden: true },
            { type: "combo", name: "signstatus", label: "签收状态:", className: "layui-col-md3", options: signstatusEnums },
            { type: "input", name: "rejectreason", label: "拒收原因:", className: "layui-col-md3", hidden: true }
          ]
        },
        {
          type: "row",
          list: [
            { type: "input", name: "rejectqty", label: "拒收件数:", className: "layui-col-md3", placeholder: "请输入数字", validate: "ValidNumeric", maxLength: 8, hidden: true },
            { type: "input", name: "shiptohjwd", placeholder: "请输入数字", validate: "ValidNumeric", maxLength: 8, label: "到货环境温度:", className: "layui-col-md3", hidden: true },
            { type: "input", name: "shiptotemperature", placeholder: "请输入数字", validate: "ValidNumeric", maxLength: 8, label: "到货温度:", className: "layui-col-md3", hidden: true }
          ]
        }
      ]
    });

    ddfrom.attachComboEvent("signstatus", "onChange", function (id) {
      ddfrom.setFormData({ rejectreason: "" });
      if (id == "01") {
        ddfrom.hideItem("rejectreason");
        ddfrom.hideItem("rejectqty");
        ddfrom.enableItem("rejectqty");
        ddfrom.setFormData({ rejectqty: "" });
        ddfrom.getDForm().setRequired("rejectreason", false);
      }
      else if (id == "02") {
        ddfrom.showItem("rejectreason");
        ddfrom.showItem("rejectqty");
        ddfrom.enableItem("rejectqty");
        ddfrom.setFormData({ rejectqty: "" });
        ddfrom.getDForm().setRequired("rejectreason", true);
      }
      else if (id == "03") {
        let data = ddfrom.getFormData();
        ddfrom.showItem("rejectreason");
        ddfrom.showItem("rejectqty");
        ddfrom.disableItem("rejectqty");
        ddfrom.setFormData({ rejectqty: data.rsumcases });
        ddfrom.getDForm().setRequired("rejectreason", true);
      }
    });

    ddfrom.setFormData(formData);
    if (formData.temperatureRequire == "01" || formData.temperatureRequire == "02") {
      ddfrom.showItem("shiptohjwd");
      ddfrom.showItem("shiptotemperature");
    }
    if (formData.shipgoodsgroup == "04" || formData.shipgoodsgroup == "05") {
      ddfrom.showItem("signer2nd");
    }
    changePanel();
    if (handoverNumber > 1) {
      $("#customerHandover_imageUpload").hide();
      $("#customerHandoverErr").html("批量交接");
    }
    else {
      $("#customerHandover_imageUpload").show();
      $("#customerHandoverErr").html("客户交接");
      queryItem = {
        bizId: formData.shipbillid,
        bizType: "0",
        enterpriseid: userGJ.p_enterpriseid
      };
      getImgList(queryItem);
    }
  }

  //查询图片
  var imgList = [];
  function getImgList(data) {
    imgList = [];
    $("#customerHandover_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 })
        $("#customerHandover_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>");
      }
      $("#customerHandover_xi2").append("<img id='customerHandoverAddImg' 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: "#customerHandoverAddImg",
      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);
      }
    });
  }
  //删除
  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("#customerHandover_back1").onclick = function () {
    changePanel();
  };
  //确认
  document.querySelector("#customerHandover_save").onclick = function () {
    //信息比对
    let url = UPCLOUD_RDC_TMS_BUSINESS_SERVICE+"/customerHandover/customerHandoverByWaybill/v1.0";
    //数据修改
    let feik = ddfrom.validate();
    if (!feik) {
      return;
    }
    let datai = ddfrom.getFormData();
    datai.loadingbill = datai.loadbillno;
    datai.signqty = Prolog.floatOper(datai.rsumcases, datai.rejectqty || 0, "-");
    let list = volist.map(item => {
      item.signstatus = datai.signstatus;
      item.signer = datai.signer;
      item.signer2nd = datai.signer2nd;
      item.signqty = datai.signqty;
      item.rejectreason = datai.rejectreason;
      item.rejectqty = datai.rejectqty;
      item.shiptotemperature = datai.shiptotemperature;
      item.shiptohjwd = datai.shiptohjwd;
      return item;
    });
    // console.log(list);
    //调用ajax方法
    utilAjaxGJ(url, "post", JSON.stringify(list), function (data) {
      if (data.success) {
        grid.reload();
        changePanel();
      }
    }, "application/json");
  };
};