/**
 * zzx
 * 2022.02.14
 * 商品管理
 */
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, UPCLOUD_RDC_TMS_BUSINESS_SERVICE, UPCLOUD_RDC_TMS_INTERFACE_SERVICE, SERVICE_PLATFORM_POWER_BASE } from '@/config/serviceSettings.js';
import { getSelectGJ, querySysPicture, departmentDialog } from '@/utils/prolog.ajax.js';
export default (_vue) => {
  let master_grid, edit_form, editType;

  // 用户信息
  let userInfo = _vue.$store.state.user.info, parentDepartment = {}
  if (userInfo.userCategory !== 'I') {
    utilAjaxGJ(SERVICE_PLATFORM_POWER_BASE + "/organization/all", "get", "", function (res) {
      res.data.forEach(item => {
        if (item.parentId === "0") parentDepartment = item
      })
    })
  }

  // 获取扩展字段
  let gird_opts_list = [], form_opts_list = [], date_list = [];
  utilSyncAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/extendedField/list", "post", JSON.stringify({ "extendedObjectCode": "2" }), function (res) {
    extendedFieldList({ list: res.data, className: "layui-col-md3" }, function (res) {
      gird_opts_list = res.gird_opts_list;
      form_opts_list = res.form_opts_list;
      date_list = res.date_list;
    });
  }, "application/json");


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

  // 获取下拉框
  let dataSelect;
  getSelectGJ([
    { "objectcode": "ITEM_CATEGORY_LEVEL" },
    { "objectcode": "PACK_TYPE" },
    { "objectcode": "CARGO_THERMOSPHERE" }
  ], function (data) {
    data.data.ITEM_CATEGORY_LEVEL.unshift({ "text": "", "value": "" });
    data.data.PACK_TYPE.unshift({ "text": "", "value": "" });
    data.data.CARGO_THERMOSPHERE.unshift({ "text": "", "value": "" });
    dataSelect = data.data;
  });

  // 商品品类弹窗
  let itemCategory_table = {
    columns: [
      { id: "itemCategoryId", name: "id", type: "ro", hidden: true },
      { id: "itemCategoryCode", name: "商品品类编码", type: "ro" },
      { id: "itemCategoryName", name: "商品品类名称", type: "ro" },
      { id: "itemCategoryLevel", name: "类目级别", type: "ro", render: function (v) { return getSelectValue(dataSelect.ITEM_CATEGORY_LEVEL, v); } },
      { id: "fatherItemCategoryCode", name: "上级商品品类编码", type: "ro" },
      { id: "fatherItemCategoryName", name: "上级商品品类名称", type: "ro" },
      { id: "fatherItemCategoryLevel", name: "上级类目级别", type: "ro", render: function (v) { return getSelectValue(dataSelect.ITEM_CATEGORY_LEVEL, v); } }
    ],
    toolbar: [
      { type: "settings", labelAlign: "right", labelWidth: 65 },
      { type: "input", name: "search", label: "查询条件:", offsetLeft: 5, placeholder: "请输入商品品类编码/名称", width: 300 },
      { type: "newcolumn" },
      { type: "button", name: "querycarr", value: "查询" },
      { type: "newcolumn" },
      { type: "button", name: "car_Reset", value: "重置" }
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item_category/popup",
    type: "post",
    params: "{}",
    contentType: "application/json",
    pagebar: { type: "simple" },
    page: true,
    totalCount: "totalCount"
  };

  // 货主table
  var consignor_Table = {
    columns: [
      { id: "cargoOwnerId", name: "id", type: "ro", width: "130", hidden: true },
      { id: "cargoOwnerCode", name: "货主编号", type: "ro" },
      { id: "cargoOwnerName", name: "货主名称", type: "ro" },
      { id: "cargoOwnerShortName", name: "货主简称", type: "ro" }
    ],
    toolbar: [
      { type: "settings", labelAlign: "right", labelWidth: 65 },
      { type: "input", name: "cargoOwnerCode", label: "货主编码:", width: 150 },
      { type: "newcolumn" },
      { type: "input", name: "cargoOwnerName", label: "货主名称:", width: 150 },
      { type: "newcolumn" },
      { type: "button", name: "querycarr", value: "查询" },
      { type: "newcolumn" },
      { type: "button", name: "car_Reset", value: "重置" }
    ],
    multiselect: false,
    pagebar: { type: "simple" },

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/cargo_owner/popup", //数据接口
    type: "post", //数据提交方式，默认为get
    contentType: "application/json",
    params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
    page: true, //是否启用分页
    totalCount: "totalCount" //总记录数字段，默认totalCount
  };

  // 仓库table
  var branchTable = {
    // terrace显示全部，card分页显示
    skin: "card",
    // renderer:"grid",
    columns: [
      { id: "id", name: "id", type: "ro", width: "130", hidden: true },
      { id: "code", name: "仓库编码", type: "ro", width: 150 },
      { id: "name", name: "仓库名称", type: "ro", width: 150 },
      { id: "provinceName", name: "省", type: "ro", width: 80 },
      { id: "cityName", name: "市", type: "ro", width: 80 },
      { id: "districtName", name: "区", type: "ro", width: 80 },
      { id: "address", name: "详细地址", type: "ro", width: 150 }
    ],
    multiselect: false,
    toolbar: [
      { type: "settings", position: "label-left", width: 200, labelWidth: 110 },
      {
        type: "block", id: "bk", blockOffset: 0, list: [
          { type: "input", name: "code", label: "仓库编码:", width: 120 },
          { type: "newcolumn" },
          { type: "input", name: "name", label: "仓库名称:", width: 120 },
          { type: "newcolumn" },
          { type: "button", name: "querycarr", value: "查询" },
          { type: "newcolumn" },
          { type: "button", name: "car_Reset", value: "重置" }
        ]
      }
    ],
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/tmsBaseBranch/queryBranchPopup",
    pagebar: { type: "simple" },
    type: "post", // 数据提交方式，默认为get
    params: "{}", // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: "application/json",
    page: true, // 是否启用分页
    totalCount: "totalCount" // 总记录数字段，默认totalCount
  };

  let gird_opts_columns = [
    { id: "itemId", name: "id", type: "ro", width: 120, hidden: true },
    { id: "itemCode", name: "商品编码", type: "ro", width: 120 },
    { id: "itemName", name: "商品名称", type: "ro", width: 120 },
    { id: "departmentName", name: "部门", type: "ro", width: 120 },
    { id: "cargoOwnerName", name: "所属货主", type: "ro", width: 120 },
    { id: "itemCategoryName", name: "商品品类", type: "ro", width: 120 },
    { id: "packTypeName", name: "包装类型", type: "ro", width: 120 },
    { id: "cargoThermosphereName", name: "货物温层", type: "ro", width: 120 },
    { id: "memo", name: "备注", type: "ro", width: 120 },
    { id: "branchName", name: "默认存放仓库", type: "ro", width: 120 },
    { id: "inventoryPcs", name: "库存件数", type: "ro", width: 120 },
    { id: "stagingLocation", name: "暂存位", type: "ro", width: 120 },
    { id: "statusName", name: "状态", type: "ro", width: 120 },
    { id: "length", name: "长", type: "ro", width: 120 },
    { id: "width", name: "宽", type: "ro", width: 120 },
    { id: "heigth", name: "高", type: "ro", width: 120 },
    { id: "weight", name: "重量", type: "ro", width: 120 },
    { id: "volume", name: "体积", type: "ro", width: 120 },
    { id: "cargoValue", name: "货值", type: "ro", width: 120 },
  ];
  var master_grid_opts = {
    skin: "card",
    columns: gird_opts_columns.concat(gird_opts_list, [
      { id: "createperson", name: "创建人", type: "ro", width: 120 },
      { id: "createtime", name: "创建时间", type: "ro", width: 120 },
      { id: "updateperson", name: "修改人", type: "ro", width: 120 },
      { id: "updatetime", name: "修改时间", type: "ro", width: 120 },
      {
        id: "op", name: "操作", type: "button", align: "center", fixed: "right", width: 250, render: function (v, rd) {
          let result = "查看^iteminfo_view,复制^iteminfo_copy,修改^iteminfo_edit,";
          if (rd.status == "1") {
            result += "停用^iteminfo_enOrDis";
          }
          else {
            result += "启用^iteminfo_enOrDis";
          }
          result += ",删除^iteminfo_del";
          return result;
        }
      }
    ]),
    toolbar: [
      { type: "settings", labelWidth: 90, labelAlign: "right" },
      {
        type: "row",
        list: [
          { type: "input", className: "layui-col-md4", name: "itemCode", label: "商品编码:" },
          { type: "input", className: "layui-col-md4", name: "itemName", label: "商品名称:" },
          { type: "input", className: "layui-col-md4", name: "cargoOwnerName", label: "所属货主:" },
          {
            type: "block", className: "layui-col-md12 right",
            list: [
              { type: "button", className: "btn-normal", name: "master_search", value: "查询" },
              { type: "newcolumn" },
              { type: "button", name: "master_reset", value: "重置" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_add", value: "<i class='layui-icon layui-icon-add-1'></i>新增" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_en", value: "启用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_dis", value: "停用" },
              { type: "newcolumn" },
              { type: "button", className: "btn-danger", name: "master_del", value: "删除" },
              { type: "newcolumn" },
              { type: "button", className: "btn-normal", name: "master_import", value: "导入" }

            ]
          }
        ]
      }
    ],
    multiselect: true,
    fixedLast: true,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/paging_query",
    type: "post",
    contentType: "application/json",
    params: "{}",
    page: true,
    totalCount: "totalCount"
  };
  master_grid = new PlgGrid(master_grid_opts);
  master_grid.renderTo("iteminfo_master");
  master_grid.loadData();

  master_grid.attachToolBarEvent("onButtonClick", function (name) {
    if (name === "master_search") {
      var request = master_grid.getToolBarForm().getFormData();
      master_grid.setParams(JSON.stringify(request));
      master_grid.reload();
    }
    else if (name === "master_reset") {
      master_grid.getToolBarForm().clear();
    }
    else if (name === "master_add") {
      changePanel("#iteminfo_edit");
      $("#iteminfo_edit_title").html("新增");
      editType = "add";
      editFormInit();
    }
    else if (name === "master_en" || name === "master_dis") {
      var ids = master_grid.getCheckedIds();
      let status = name === "master_en" ? "1" : "0";
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      var list = ids.split(",").map(item => {
        return { itemId: item };
      });
      item_whetherToEnable(list, status);
    }
    else if (name === "master_del") {
      let ids = master_grid.getCheckedIds();
      if (!ids) {
        layer.msg("请选择数据");
        return false;
      }
      let list = ids.split(",").map(item => {
        return { itemId: item };
      });
      item_del(list);
    }
    else if (name === "master_import") {
      importDialog({ id: "import", importUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/import", downloadUrl: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/download_template", downloadName: "商品模板" });
    }
  });

  // 停用/启用
  window.iteminfo_enOrDis = function (rid, rdata) {
    let status = rdata.status == "1" ? "0" : "1";
    item_whetherToEnable([{ itemId: rid }], status);
  };
  // 停用/启用方法
  function item_whetherToEnable(idList, status) {
    let text = status == "1" ? "启用" : "停用";
    layer.open({
      title: text,
      content: "是否" + text + "？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/whether_to_enable", type: "post", contentType: "application/json", data: JSON.stringify({
            itemIds: idList,
            status
          }),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            return false;

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

  // 删除
  window.iteminfo_del = function (rid) {
    item_del([{ itemId: rid }]);
  };
  // 删除方法
  function item_del(idList) {
    layer.open({
      title: "删除",
      content: "是否删除？",
      btn: ["确认", "取消"],
      yes: function () {
        let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/batch_delete", type: "post", contentType: "application/json", data: JSON.stringify(idList),
          success: function (data) {
            PlgDialog.close(pload);
            if (data.success) {
              layer.closeAll();
              PlgDialog.msg(data.message);
              master_grid.reload();
              return true;
            }
            return false;

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

  // 复制
  window.iteminfo_copy = function (rid, rdata) {
    changePanel("#iteminfo_edit");
    $("#iteminfo_edit_title").html("复制");
    editType = "copy";
    editFormInit(rdata);
  };
  // 修改
  window.iteminfo_edit = function (rid, rdata) {
    changePanel("#iteminfo_edit");
    $("#iteminfo_edit_title").html("修改");
    editType = "modify";
    editFormInit(rdata);
  };
  //详情
  window.iteminfo_view = function (rid, rdata) {
    changePanel("#iteminfo_view");
    new PlgPanel({
      renderer: "iteminfo_view_form",
      skin: 2,
      header: {
        isShow: true,
        title: "基本信息"
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            { label: "商品编码", value: rdata.itemCode },
            { label: "商品名称", value: rdata.itemName },
            { label: "所属货主", value: rdata.cargoOwnerName },
            { label: "部门", value: rdata.departmentName },
          ],
          [
            { label: "商品品类", value: rdata.itemCategoryName },
            { label: "包装类型", value: rdata.packTypeName },
            { label: "货物温层", value: rdata.cargoThermosphereName },
            { label: "默认存放仓库", value: rdata.branchName }
          ],
          [
            { label: "长(m)", value: rdata.length },
            { label: "宽(m)", value: rdata.width },
            { label: "高(m)", value: rdata.heigth },
            { label: "库存件数", value: rdata.inventoryPcs }
          ],
          [
            { label: "重量(kg)", value: rdata.weight },
            { label: "体积(m³)", value: rdata.volume },
            { label: "货值", value: rdata.cargoValue },
            { label: "暂存位", value: rdata.stagingLocation }
          ],
          [
            { label: "备注", value: rdata.memo }
          ],
          gird_opts_list.map(item => {
            return { label: item.name, value: rdata[item.id] };
          })
        ]
      }
    });
  };

  // 创建form
  function editFormInit(rdata) {
    $("#iteminfo_edit_form").html("");
    edit_form = new PlgForm({
      renderer: "iteminfo_edit_form",
      items: [
        { type: "settings", labelAlign: "right", labelWidth: 110 },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "itemCode", label: "商品编码:", required: true },
            { type: "input", className: "layui-col-md3", name: "itemName", label: "商品名称:", required: true },
            {
              className: "layui-col-md3",
              type: "selectTable",
              placeholder: "请选择货主",
              readonly: false,
              table: consignor_Table,
              tableWidth: 800,
              tableHeight: 600,
              fieldText: "cargoOwnerName",
              fieldValue: "cargoOwnerCode",
              name: "consignorList",
              label: "所属货主:<span class='dhxform_item_required'>*</span>",
              listener: {
                "init": function (grid) {
                  setMethod(grid, consignor_Table, function () { });
                },
                "afterSelect": function (isSelected, selectId, sgrid) {
                  let sdata = sgrid.getRowData(selectId);
                  edit_form.setFormData({
                    cargoOwnerId: isSelected ? sdata.cargoOwnerId : "",
                    cargoOwnerCode: isSelected ? sdata.cargoOwnerCode : "",
                    cargoOwnerName: isSelected ? sdata.cargoOwnerName : ""
                  });
                }
              }
            },
            { type: "hidden", name: "cargoOwnerId" },
            { type: "hidden", name: "cargoOwnerCode" },
            { type: "hidden", name: "cargoOwnerName" },
            { type: "input", className: "layui-col-md3", name: "departmentName", label: "部门:", placeholder: "请选择部门", readonly: true, required: true, disabled: userInfo.userCategory !== 'I' },
            { type: "hidden", name: "departmentId" },
            { type: "hidden", name: "departmentCode" },
          ]
        },
        {
          type: "row",
          list: [
            {
              className: "layui-col-md3",
              type: "selectTable",
              placeholder: "请选择商品品类编码",
              readonly: false,
              table: itemCategory_table,
              tableWidth: 800,
              tableHeight: 600,
              fieldText: "itemCategoryCode",
              fieldValue: "itemCategoryCode",
              name: "itemCategoryList",
              label: "商品品类编码:",
              listener: {
                "init": function (grid) {
                  setMethod(grid, itemCategory_table, function () { });
                },
                "afterSelect": function (isSelected, selectId, sgrid) {
                  let sdata = sgrid.getRowData(selectId);
                  edit_form.setFormData({
                    itemCategoryId: isSelected ? sdata.itemCategoryId : "",
                    itemCategoryCode: isSelected ? sdata.itemCategoryCode : "",
                    itemCategoryName: isSelected ? sdata.itemCategoryName : "",
                    itemCategoryLevel: isSelected ? sdata.itemCategoryLevel + "" : ""
                  });
                }
              }
            },
            { type: "input", className: "layui-col-md3", name: "itemCategoryName", label: "商品品类名称:", disabled: "true" },
            { type: "hidden", name: "itemCategoryId" },
            { type: "hidden", name: "itemCategoryCode" },
            { type: "hidden", name: "itemCategoryName" },
            { type: "hidden", name: "itemCategoryLevel" },
            { type: "combo", className: "layui-col-md3", name: "packType", label: "包装类型:", options: dataSelect.PACK_TYPE, readonly: true },
            { type: "combo", className: "layui-col-md3", name: "cargoThermosphere", label: "货物温层:", options: dataSelect.CARGO_THERMOSPHERE, readonly: true },

          ]
        },
        {
          type: "row",
          list: [
            {
              className: "layui-col-md3",
              type: "selectTable",
              placeholder: "请选择默认存放仓库",
              readonly: false,
              table: branchTable,
              tableWidth: 800,
              tableHeight: 600,
              fieldText: "name",
              fieldValue: "code",
              name: "branchList",
              label: "默认存放仓库:",
              listener: {
                "init": function (grid) {
                  setMethod(grid, branchTable, function () { });
                },
                "afterSelect": function (isSelected, selectId, sgrid) {
                  let sdata = sgrid.getRowData(selectId);
                  edit_form.setFormData({
                    branchId: isSelected ? sdata.id : "",
                    branchCode: isSelected ? sdata.code : "",
                    branchName: isSelected ? sdata.name : ""
                  });
                }
              }
            },
            { type: "hidden", name: "branchId" },
            { type: "hidden", name: "branchCode" },
            { type: "hidden", name: "branchName" },
            { type: "input", className: "layui-col-md3", name: "length", label: "长(m):", validate: "ValidNumeric" },
            { type: "input", className: "layui-col-md3", name: "width", label: "宽(m):", validate: "ValidNumeric" },
            { type: "input", className: "layui-col-md3", name: "heigth", label: "高(m):", validate: "ValidNumeric" },

          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "inventoryPcs", label: "库存件数:", validate: "ValidNumeric" },
            { type: "input", className: "layui-col-md3", name: "weight", label: "重量(kg):", validate: "ValidNumeric" },
            { type: "input", className: "layui-col-md3", name: "volume", label: "体积(m³):", validate: "ValidNumeric" },
            { type: "input", className: "layui-col-md3", name: "cargoValue", label: "货值:", validate: "ValidNumeric" },

          ]
        },
        {
          type: "row",
          list: [
            { type: "input", className: "layui-col-md3", name: "stagingLocation", label: "暂存位:" },
            { type: "input", className: "layui-col-md9", name: "memo", label: "备注:" }
          ]
        },
        {
          type: "row",
          list: form_opts_list
        }
      ]
    });
    if (rdata) {
      rdata.itemCategoryList = rdata.itemCategoryCode ? JSON.stringify([rdata.itemCategoryCode]) : "";
      rdata.consignorList = rdata.cargoOwnerCode ? JSON.stringify([rdata.cargoOwnerCode]) : "";
      rdata.branchList = rdata.branchCode ? JSON.stringify([rdata.branchCode]) : "";
      edit_form.setFormData(rdata);
      edit_form.setText("itemCategoryList", rdata.itemCategoryCode || "");
      edit_form.setText("consignorList", rdata.cargoOwnerName || "");
      edit_form.setText("branchList", rdata.branchName || "");
    }

    if (editType === "modify") {
      edit_form.disableItem("itemCode");
      edit_form.disableItem("itemName");
    }
    else {
      edit_form.enableItem("itemCode");
      edit_form.enableItem("itemName");
      if (editType === "copy") {
        edit_form.setItemValue("itemCode", "");
        edit_form.setItemValue("itemName", "");
      }
    }

    if (userInfo.userCategory !== 'I') {
      edit_form.setFormData({ departmentId: parentDepartment.id, departmentCode: parentDepartment.code, departmentName: parentDepartment.name })
    } else {
      // 部门弹窗
      departmentDialog("#iteminfo_edit_form", edit_form)
    }
  }

  // 保存
  $("#iteminfo_save").on("click", function () {
    let feik = edit_form.validate();
    if (!feik) return;

    if (editType === "add") {
      Save();
    }
    else {
      layer.open({
        title: editType === "modify" ? "修改" : "复制",
        content: "是否保存？",
        btn: ["确认", "取消"],
        yes: function () {
          Save();
        }
      });
    }
  });
  function Save() {
    let formData = edit_form.getFormData();
    date_list.forEach(item => {
      formData[item] = FormatDateTime(formData[item]);
    });
    if (!formData.cargoOwnerId) {
      layer.msg("请选择货主");
      return false;
    }

    let url = UPCLOUD_RDC_TMS_MAINDATA_SERVICE + "/item/" + editType;
    let pload = PlgDialog.load(2, { shade: [0.6, "#fff"] });
    Prolog.ajax({
      url, type: "post", contentType: "application/json", data: JSON.stringify(formData),
      success: function (res) {
        PlgDialog.close(pload);
        if (res.success) {
          PlgDialog.msg(res.message);
          changePanel("#iteminfo_main");
          master_grid.reload();
          return true;
        }
        return false;
      }, error: function () { PlgDialog.close(pload); return false; }
    });
  }
};
