/**
 * zzx
 * 2020.05.25
 * 仓库站台管理
 */
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, details_form_opts, details_form
  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 carousel = layui.carousel
  carousel.render({
    elem: '#warehousePortManage',
    autoplay: false,
    index: 0,
    arrow: 'none',
    indicator: 'none',
    anim: 'fade',
    width: '100%', // 设置容器宽度
    height: '100%',
  })
  // 切换页面
  function changePanel(name) {
    var slideList = ['#warehousePortManage_master', '#warehousePortManage_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', '#warehousePortManage_details_return', function () {
    changePanel('#warehousePortManage_master')
  })

  // 获取下拉框
  var dataSelect = {
    TMS_PLATFORM_TYPE: [],
    TMS_PLATFORM_STATUS: [],
    TMS_PLATFORM_STATUS_ALL: [],
  }
  getSelectGJ([{ objectcode: 'TMS_PLATFORM_TYPE' }, { objectcode: 'TMS_PLATFORM_STATUS' }], function (data) {
    dataSelect = data.data
    dataSelect.TMS_PLATFORM_STATUS_ALL = JSON.parse(JSON.stringify(dataSelect.TMS_PLATFORM_STATUS))
    dataSelect.TMS_PLATFORM_TYPE.unshift({ value: '', text: '' })
    dataSelect.TMS_PLATFORM_STATUS_ALL.unshift({ value: '', text: '' })
  })
  let priorityEnums = [{ value: '', text: '' }]
  for (let index = 1; index < 10; index++) {
    priorityEnums.push({ value: index, text: index })
  }

  // 装卸点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/queryPubCompany",
  //   pagebar: { type: "simple" },
  //   type: "post", // 数据提交方式，默认为get
  //   params: JSON.stringify({ companytype: "S" }), // 查询提交参数，分页参数默认为pageNum,pageSize
  //   contentType: "application/json",
  //   page: true, // 是否启用分页
  //   totalCount: "totalCount" // 总记录数字段，默认totalCount
  // };
  // 车辆规格table
  var appointVehicleModelTable = {
    // terrace显示全部，card分页显示
    skin: 'card',
    // renderer:"grid",
    columns: [
      { id: 'id', name: 'id', type: 'ro', width: '130', hidden: true },
      { id: 'vehicleSpecsNo', name: '规格编号', type: 'ro' },
      { id: 'vehicleSpecsName', name: '规格名称', type: 'ro' },
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/tBaseVehicleSpecs/queryTBaseVehicleSpecs',
    pagebar: { type: 'simple' },
    type: 'post', // 数据提交方式，默认为get
    params: '{}', // 查询提交参数，分页参数默认为pageNum,pageSize
    contentType: 'application/json',
    page: true, // 是否启用分页
  }

  // 主页grid
  var master_grid_opts = {
    skin: 'card',
    columns: [
      { id: 'platformId', name: 'id', type: 'ro', width: '130', hidden: true },
      { id: 'branchName', name: '配送中心/站点名称', type: 'ro', width: 150 },
      { id: 'platformCode', name: '站台编号', type: 'ro', width: 150 },
      { id: 'platformName', name: '站台名称', type: 'ro', width: 150 },
      {
        id: 'platformType',
        name: '类型',
        type: 'ro',
        width: 150,
        render: function (v) {
          return getSelectValue(dataSelect.TMS_PLATFORM_TYPE, v)
        },
      },
      { id: 'goodsStatus', name: '货物状态', type: 'ro', width: 150, hidden: true },
      {
        id: 'vehicleStatus',
        name: '车辆状态',
        type: 'ro',
        width: 150,
        render: function (v) {
          return getSelectValue(dataSelect.TMS_PLATFORM_STATUS, v)
        },
      },
      { id: 'location', name: '站台位置(描述)', type: 'ro', width: 150 },
      { id: 'priority', name: '优先级', type: 'ro', width: 150 },
      { id: 'memo', name: '备注', type: 'ro', width: 150 },
      {
        id: 'op',
        name: '操作',
        type: 'button',
        align: 'left',
        width: 150,
        fixed: 'right',
        render: function () {
          return '修改^warehousePortManage_edit,删除^warehousePortManage_del'
        },
      },
    ],
    toolbar: [
      { type: 'settings', labelWidth: 90, labelAlign: 'right' },
      {
        type: 'row',
        list: [
          // {
          //   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: 'combo', className: 'layui-col-md3', readonly: true, name: 'platformType', label: '站台类型:', options: dataSelect.TMS_PLATFORM_TYPE },
          { type: 'input', className: 'layui-col-md3', name: 'platformCode', label: '站台编号:' },
          { type: 'combo', className: 'layui-col-md3', readonly: true, name: 'vehicleStatus', label: '站台状态:', options: dataSelect.TMS_PLATFORM_STATUS_ALL },
          {
            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_add', value: "<i class='layui-icon layui-icon-add-1'></i>新 增" }],
          },
        ],
      },
    ],
    pagebar: {
      buttons: [{ text: "<i class='layui-icon layui-icon-delete'></i>删除", className: 'plg-btn-normal', name: 'page_del' }],
    },
    fixedLast: true, // 开启固定列，固定最后一行，倒数第二列不能隐藏
    multiselect: true, // 是否支持多选

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/platform/queryBasePlatform', // 数据接口
    type: 'post', // 数据提交方式，默认为get
    params: JSON.stringify({ vehicleStatus: '01' }), // 查询提交参数，分页参数默认为pageNum,pageSize
    page: true, // 是否启用分页
    contentType: 'application/json',
    totalCount: 'totalCount', // 总记录数字段，默认totalCount
  }
  master_grid = new PlgGrid(master_grid_opts)
  master_grid.renderTo('warehousePortManage_master')
  master_grid.getToolBarForm().setFormData({ vehicleStatus: '01' })
  master_grid.loadData()
  master_grid.attachToolBarEvent('onButtonClick', function (name) {
    switch (name) {
      case 'master_search':
        var request = master_grid.getToolBarForm().getFormData()
        request.branchid = request.branchidList ? JSON.parse(request.branchidList)[0] : ''
        dealNullQueryCondition(request)
        master_grid.setParams(JSON.stringify(request))
        master_grid.reload()
        break
      case 'master_reset':
        master_grid.getToolBarForm().clear()
        // master_grid.getToolBarForm().setText("branchidList", "");
        break
      case 'master_add':
        details_form = new PlgForm(details_form_opts)
        details_form.enableItem('platformCode')
        details_form.setFormData({ vehicleStatus: '01', branchId: userinfo.p_companyid, branchName: userinfo.p_companyname })
        $('#warehousePortManage_details_title').html('新增')
        changePanel('#warehousePortManage_details')
        break
    }
  })
  // 批量删除
  master_grid.attachPageBarEvent(function (name, ids) {
    deleteData(ids)
  })
  // 修改
  window.warehousePortManage_edit = function (rid, rdata) {
    details_form = new PlgForm(details_form_opts)
    details_form.disableItem('platformCode')
    rdata.branchidList = JSON.stringify([rdata.branchId])
    rdata.applyModelsList = rdata.applyModels ? JSON.stringify([rdata.applyModels]) : '[]'
    rdata.modelTypeList = rdata.modelType ? JSON.stringify([rdata.modelType]) : '[]'
    details_form.setFormData(rdata)
    details_form.setText('branchidList', rdata.branchName || '')
    details_form.setText('applyModelsList', rdata.applyModelsName || '')
    details_form.setText('modelTypeList', rdata.modelTypeName || '')
    $('#warehousePortManage_details_title').html('修改')
    changePanel('#warehousePortManage_details')
  }
  // 删除
  window.warehousePortManage_del = function (rid) {
    deleteData(rid)
  }
  // 删除方法
  function deleteData(ids) {
    layer.open({
      title: '删除',
      content: '是否删除？',
      btn: ['确认', '取消'],
      yes: function () {
        let list = ids.split(',').map((item) => {
          return { platformId: item }
        })
        let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] })
        Prolog.ajax({
          url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/platform/deletePlatform',
          type: 'post',
          contentType: 'application/json',
          data: JSON.stringify(list),
          success: function (data) {
            PlgDialog.close(pload)
            if (data.success) {
              layer.closeAll()
              PlgDialog.msg(data.message)
              master_grid.reload()
              return true
            }
            setTimeout(() => {
              PlgDialog.alert(data.message || '接口调用失败')
            }, 300)
            return false
          },
          error: function () {
            PlgDialog.close(pload)
            return false
          },
        })
      },
    })
  }

  // 详情form
  details_form_opts = {
    renderer: 'warehousePortManage_details_form',
    items: [
      { type: 'settings', position: 'label-left', labelWidth: 90, inputWidth: 190 },
      {
        type: 'block',
        width: '*',
        list: [
          // {
          //   width: 190,
          //   type: "selectTable",
          //   placeholder: "请选择装卸点",
          //   readonly: false,
          //   table: branchTable,
          //   tableWidth: 600,
          //   tableHeight: 500,
          //   fieldText: "companyname",
          //   fieldValue: "companyid",
          //   name: "branchidList",
          //   label: "装卸点:",
          //   listener: function (Grid) {
          //     setMethod(Grid, branchTable, function (data) {
          //       let selectedLength = JSON.parse(details_form.getItemValue("branchidList")).length;
          //       if (selectedLength) {
          //         let request = {
          //           branchId: data.companyid,
          //           branchName: data.companyname
          //         };
          //         details_form.setFormData(request);
          //       }
          //       else {
          //         let request = {
          //           branchId: "",
          //           branchName: ""
          //         };
          //         details_form.setFormData(request);
          //       }
          //     });
          //   }
          // },
          { type: 'input', name: 'branchName', label: '配送中心/站点名称:', disabled: true },
          { type: 'newcolumn', offset: 40 },
          { type: 'input', name: 'platformCode', label: '站台编号:', required: true },
          { type: 'newcolumn', offset: 40 },
          { type: 'input', name: 'platformName', label: '站台名称:', required: true },
        ],
      },
      {
        type: 'block',
        width: '*',
        list: [
          { type: 'combo', name: 'platformType', label: '站台类型:', width: 190, options: dataSelect.TMS_PLATFORM_TYPE, readonly: true, required: true },
          { type: 'newcolumn', offset: 40 },
          { type: 'combo', name: 'vehicleStatus', label: '启用状态:', width: 190, options: dataSelect.TMS_PLATFORM_STATUS, readonly: true, required: true },
          { type: 'newcolumn', offset: 40 },
          {
            width: 190,
            type: 'selectTable',
            placeholder: '请选择适用车型',
            readonly: false,
            table: appointVehicleModelTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: 'vehicleSpecsName',
            fieldValue: 'vehicleSpecsNo',
            name: 'applyModelsList',
            label: '适用车型:',
            listener: function (Grid) {
              setMethod(Grid, appointVehicleModelTable, function (data) {
                let selectedLength = JSON.parse(details_form.getItemValue('applyModelsList')).length
                if (selectedLength) {
                  let request = {
                    applyModels: data.vehicleSpecsNo,
                    applyModelsName: data.vehicleSpecsName,
                  }
                  details_form.setFormData(request)
                } else {
                  let request = {
                    applyModels: '',
                    applyModelsName: '',
                  }
                  details_form.setFormData(request)
                }
              })
            },
          },
        ],
      },
      {
        type: 'block',
        width: '*',
        list: [
          { type: 'input', name: 'loadingEfficiency', label: '装载效率:', validate: 'ValidNumeric' },
          { type: 'newcolumn', offset: 40 },
          { type: 'input', name: 'dischargeEfficiency', label: '卸货效率:', validate: 'ValidNumeric' },
          { type: 'newcolumn', offset: 40 },
          { type: 'calendar', name: 'upTimeFrom', label: '使用时间起:' },
        ],
      },
      {
        type: 'block',
        width: '*',
        list: [
          { type: 'calendar', name: 'upTimeTo', label: '使用时间止:' },
          { type: 'newcolumn', offset: 40 },
          { type: 'input', name: 'location', label: '站台位置(描述):' },
          { type: 'newcolumn', offset: 40 },
          { type: 'combo', name: 'priority', label: '优先级:', width: 190, options: priorityEnums, readonly: true, required: true },
          { type: 'newcolumn' },
          { type: 'label', label: '(1级最高)' },
        ],
      },
      {
        type: 'block',
        width: '*',
        list: [
          {
            width: 190,
            type: 'selectTable',
            placeholder: '请选择最大车型',
            readonly: false,
            table: appointVehicleModelTable,
            tableWidth: 600,
            tableHeight: 500,
            fieldText: 'vehicleSpecsName',
            fieldValue: 'vehicleSpecsNo',
            name: 'modelTypeList',
            label: '最大车型:',
            listener: function (Grid) {
              setMethod(Grid, appointVehicleModelTable, function (data) {
                let selectedLength = JSON.parse(details_form.getItemValue('modelTypeList')).length
                if (selectedLength) {
                  let request = {
                    modelType: data.vehicleSpecsNo,
                    modelTypeName: data.vehicleSpecsName,
                  }
                  details_form.setFormData(request)
                } else {
                  let request = {
                    modelType: '',
                    modelTypeName: '',
                  }
                  details_form.setFormData(request)
                }
              })
            },
          },
          { type: 'newcolumn', offset: 40 },
          { type: 'input', name: 'memo', label: '备注:', inputWidth: 518, rows: 6 },
          { type: 'hidden', name: 'platformId', label: '站台id:' },
          { type: 'hidden', name: 'branchId', label: '配送中心id:' },
          { type: 'hidden', name: 'modelType', label: '适用车型:' },
          { type: 'hidden', name: 'modelTypeName', label: '适用车型:' },
        ],
      },
    ],
  }

  // 保存
  $(document).on('click', '#warehousePortManage_details_save', function () {
    let feik = details_form.validate()
    if (!feik) return
    let formData = details_form.getFormData()
    formData.upTimeFrom = formData.upTimeFrom ? Prolog.formatDate(formData.upTimeFrom) + ' 00:00:00' : ''
    formData.upTimeTo = formData.upTimeTo ? Prolog.formatDate(formData.upTimeTo) + ' 23:59:59' : ''
    dealNullQueryCondition(formData)

    let url = formData.platformId ? UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/platform/updateBasePlatform' : UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/platform/addPlatform'
    let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] })
    Prolog.ajax({
      url,
      type: 'post',
      contentType: 'application/json',
      data: JSON.stringify(formData),
      success: function (data) {
        PlgDialog.close(pload)
        if (data.success) {
          PlgDialog.msg(data.message)
          changePanel('#warehousePortManage_master')
          master_grid.reload()
          return true
        }
        setTimeout(() => {
          PlgDialog.alert(data.message || '接口调用失败')
        }, 300)
        return false
      },
      error: function () {
        PlgDialog.close(pload)
        return false
      },
    })
  })
}
