/**
 * jiw
 * 2019.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 userinfo = window.localStorage.getItem("userinfo");
  // if (userinfo != null) userinfo = JSON.parse(userinfo);

  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 rsp_config = [],
    rsp_branchid = [{ value: userinfo.p_companyid, text: userinfo.p_companyname }]
  Prolog.ajax({
    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/printconf/list-dd',
    type: 'get',
    contentType: 'application/json',
    data: null,
    async: false,
    success: function (data) {
      if (data.success) {
        rsp_config = [{ text: '', value: '' }]
        if (data.data != null) {
          data.data.forEach((t) => {
            rsp_config.push({ text: t.configname, value: t.configid })
          })
        }
      }
    },
    error: function () {
      PlgDialog.msg('接口调用失败')
    },
  })

  var grid = null
  var param = { pageNum: 1, pageSize: 10 }
  var type = 0

  //滑屏
  var carousel = layui.carousel
  var car = carousel.render({
    elem: '#printRoute_grid',
    autoplay: false,
    index: 0,
    arrow: 'none',
    indicator: 'none',
    anim: 'fade',
    width: '100%', //设置容器宽度
    height: '100%',
  })

  function changePanel(name) {
    car.slide(name)
  }

  //返回主页面
  $('#printRoute_btn_back').on('click', function () {
    changePanel('printRoute_grid_01')
  })

  // 路由名称弹窗
  let machineip_Table = {
    columns: [
      { id: 'printerid', name: 'id', type: 'ro', width: 100, hidden: true },
      { id: 'printercode', name: '打印机编号', type: 'ro', width: 120 },
      { id: 'printername', name: '打印机名称', type: 'ro', width: '*' },
      { id: 'branchid', name: '仓库名称', type: 'ro', width: '*' },
    ],
    toolbar: [
      { type: 'settings', labelAlign: 'left', labelWidth: 65 },
      { type: 'input', name: 'printercode', label: '查询条件:', offsetLeft: 5, placeholder: '请输入打印机名称/编号', width: 300 },
      { type: 'newcolumn' },
      { type: 'button', name: 'btn_search', value: '查询' },
    ],
    multiselect: false,

    url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sys-print-mst/lists',
    type: 'post',
    params: JSON.stringify({ pageNum: 1, pageSize: 10, data: { status: 'C' } }),
    contentType: 'application/json',
    page: true,
    totalCount: 'totalCount',
  }

  // 工号弹窗
  let operator_Table = {
    columns: [
      { id: 'p_id', name: 'id', type: 'ro', width: 100, hidden: true },
      { id: 'p_workernumber', name: '员工号', type: 'ro', width: 120 },
      { id: 'p_nickname', name: '员工姓名', type: 'ro', width: '*' },
    ],
    toolbar: [
      { type: 'settings', labelAlign: 'left', labelWidth: 65 },
      { type: 'input', name: 'search', label: '查询条件:', offsetLeft: 5, placeholder: '请输入工号/名称', width: 300 },
      { type: 'newcolumn' },
      { type: 'button', name: 'btn_search', value: '查询' },
    ],
    multiselect: false,

    url: '/users/users/list',
    type: 'post',
    params: { branchid: userinfo.p_companyid, pageNum: 1, pageSize: 10 },
    contentType: 'application/x-www-form-urlencoded',
    pagebar: { type: 'simple' },
    page: true,
    totalCount: 'totalCount',
  }

  gridInit()

  //主页面Grid
  function gridInit() {
    var numOpts = {
      skin: 'terrace',
      rowId: 'printrouteid',
      columns: [
        { id: 'printrouteid', name: '路由配置ID', type: 'ro', hidden: true, width: 100 },
        { id: 'operatorcode', name: '工号', align: 'left', type: 'ro', width: 150 },
        { id: 'printername', name: '打印机名称', align: 'center', type: 'ro', width: 150 },
        { id: 'branchid', name: '仓编码', align: 'left', type: 'ro', width: 150 },
        { id: 'remark', name: '备注', type: 'ro', width: 150 },
        {
          id: 'status',
          name: '状态',
          align: 'center',
          type: 'ro',
          width: 100,
          render: function (v) {
            return '<input disabled="disabled" type="checkbox" ' + (v === 1 ? 'checked=""' : '') + ' name="chk_statue" lay-skin="switch" lay-filter="chk_statue" lay-text="ON|OFF">'
          },
        },
        { id: 'createby', name: '创建人', type: 'ro', width: 100 },
        { id: 'createdate', name: '创建时间', type: 'ro', width: 130 },
        { id: 'lastmodifyby', name: '最后修改人', type: 'ro', width: 100 },
        { id: 'lastmodifydate', name: '最后修改时间', type: 'ro', width: 130 },
        {
          id: 'op',
          name: '操作',
          type: 'button',
          align: 'center',
          width: 150,
          render: function () {
            return '详情^res_printRoute_showClick,修改^res_printRoute_editClick,删除^res_printRoute_delClick'
          },
        },
      ],
      multiselect: false,
      fixedLast: true,
      toolbar: [
        {
          type: 'selectTable',
          name: 'operatorcode',
          width: 200,
          label: '工号：',
          placeholder: '请选择工号',
          readonly: true,
          table: operator_Table,
          tableWidth: 550,
          tableHeight: 500,
          fieldText: 'p_nickname',
          fieldValue: ['p_workernumber'],
          listener: {
            init: function (sgrid) {
              sgrid.attachToolBarEvent('onButtonClick', function (name) {
                if (name === 'btn_search') {
                  var p = sgrid.getToolBarForm().getFormData()
                  p.branchid = userinfo.p_companyid
                  sgrid.setParams(p)
                  sgrid.reload()
                }
              })
            },
          },
        },
        { type: 'newcolumn', offset: 20 },
        /* { type: "combo", name: 'tempname', label: '打印方案:', offsetLeft: 5, placeholder: '请选择打印方案', options: rsp_config, width: 200 }, */
        { type: 'newcolumn' },
        { type: 'button', name: 'btn_search', value: '查询' },
        { type: 'newcolumn' },
        { type: 'button', name: 'btn_reset', className: ' normal', value: '重置' },
        { type: 'newcolumn' },
        { type: 'button', name: 'btn_add', className: 'plg-toolbar-right', value: "<i class='layui-icon layui-icon-add-1'></i>新增" },
        { type: 'newcolumn' },
      ],
      formData: [],

      url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sys-defineprintroute/lists',
      type: 'post',
      params: JSON.stringify(param),
      contentType: 'application/json',
      page: true,
      totalCount: 'totalCount',
    }
    //分页参数 pageSize pageNum
    grid = new PlgGrid(numOpts)
    grid.renderTo('printRoute_grid_01')
    grid.loadData()
    grid.getGrid().enableEditEvents(true, false, true)

    $('#printRoute_grid_01').addClass('layui-form')
    grid.attachEvent('onDataReady', function () {
      setTimeout(function () {
        layui.form.render()
      }, 200)
    })

    //工具栏按钮事件
    grid.attachToolBarEvent('onButtonClick', function (name) {
      // 查询
      if (name === 'btn_search') {
        let p = grid.getToolBarForm().getFormData()
        if (p.operatorcode != '' && p.operatorcode != null) {
          let arr = JSON.parse(p.operatorcode)
          if (arr.length > 0) p.operatorcode = arr[0].p_workernumber
          else p.operatorcode = ''
        }
        grid.setParams(JSON.stringify(p))
        grid.reload()
      }
      // 新增
      else if (name === 'btn_add') {
        addprintRoute()
      } else if (name == 'btn_reset') {
        grid.getToolBarForm().clear()
        grid.getToolBarForm().setText('operatorcode', '')
      }
    })
  }

  //添加打印路由
  function addprintRoute() {
    type = 0
    var str = '<div class="layui-col-lg12" id="printRoute_grid_add_content"></div>'
    $('#printRoute_grid_sub').html(str)

    changePanel('printRoute_grid_01_edit')
    printRouteFormInit(0, { branchid: userinfo.p_companyid })
  }

  //打印路由表单
  function printRouteFormInit(ntype, rdata) {
    var tit = '新增打印路由'
    var rediv = 'printRoute_grid_add_content'
    if (ntype === 1) {
      tit = '打印路由 [' + rdata.operatorcode + '] 信息修改'
      rediv = 'printRoute_grid_sub'
    }
    $('#printRoute_span_title').html(tit)
    $('#printRoute_grid_sub').removeClass('ul_bg')
    $('#btn_save_printRoute').show()
    $('#' + rediv).html('')
    var formcfg = {
      renderer: rediv,
      items: [
        { type: 'settings', inputWidth: 230, width: '*', labelWidth: 80, position: 'label-left', labelAlign: 'left' },
        {
          type: 'block',
          width: '*',
          list: [
            { type: 'combo', readonly: true, disabled: true, name: 'branchid', label: '仓号:', width: 230, options: rsp_branchid, validate: 'NotEmpty', required: true },
            { type: 'newcolumn', offset: 40 },
          ],
        },
        {
          type: 'block',
          width: '*',
          list: [
            {
              type: 'selectTable',
              name: 'machine_iplist',
              width: 230,
              label: '打印机：<span class="dhxform_item_required">*</span>',
              placeholder: '请选择打印机名称',
              readonly: true,
              table: machineip_Table,
              tableWidth: 550,
              tableHeight: 500,
              fieldText: 'printername',
              fieldValue: 'printername',
              required: true,
              listener: {
                init: function (sgrid) {
                  sgrid.attachToolBarEvent('onButtonClick', function (name) {
                    if (name === 'btn_search') {
                      var p = sgrid.getToolBarForm().getFormData()
                      p.status = 'C'
                      sgrid.setParams(JSON.stringify(p))
                      sgrid.reload()
                    }
                  })
                },
              },
            },
            { type: 'newcolumn', offset: 40 },
            {
              type: 'selectTable',
              name: 'operatorcode',
              width: 230,
              label: '工号：<span class="dhxform_item_required">*</span>',
              placeholder: '请选择工号',
              readonly: true,
              table: operator_Table,
              tableWidth: 550,
              tableHeight: 500,
              fieldText: 'p_nickname',
              fieldValue: ['p_workernumber', 'p_nickname'],
              listener: {
                init: function (sgrid) {
                  sgrid.attachToolBarEvent('onButtonClick', function (name) {
                    if (name === 'btn_search') {
                      var p = sgrid.getToolBarForm().getFormData()
                      p.branchid = userinfo.p_companyid
                      sgrid.setParams(p)
                      sgrid.reload()
                    }
                  })
                },
              },
            },
          ],
        },
        {
          type: 'block',
          width: '*',
          list: [
            { type: 'input', name: 'remark', label: '备注:' },
            { type: 'newcolumn', offset: 40 },
            { type: 'checkbox', name: 'status', label: '是否启用:' },
          ],
        },
      ],
    }
   let form1 = new PlgForm(formcfg)
    form1.setFormData(rdata)

    if (ntype === 1) {
      form1.setItemValue('machine_iplist', JSON.stringify([rdata.printername]))
      form1.getDForm().setText('machine_iplist', rdata.printername)
      form1.setItemValue('operatorcode', '[{"p_workernumber":"' + rdata.operatorcode + '", "p_nickname":"' + rdata.operatorname + '"}]')
      form1.getDForm().setText('operatorcode', rdata.operatorname)
    }
  }

  //打印路由信息保存
  $('#btn_save_printRoute').click(function () {
    var b = form1.validate()
    if (!b) return
    var fd = form1.getFormData()
    //console.log(fd)

    if (!fd.machine_iplist || fd.machine_iplist == '[]') {
      PlgDialog.msg('请选择打印机')
      return
    }
    if (!fd.operatorcode || fd.operatorcode == '[]') {
      PlgDialog.msg('请选择员工')
      return
    }

    let iplist = JSON.parse(fd.machine_iplist)
    let arr = JSON.parse(fd.operatorcode)
    if (iplist.length > 0) {
      fd.printername = iplist[0]
    }
    delete fd.machine_iplist
    if (arr.length > 0) {
      if (!arr[0].p_workernumber) {
        PlgDialog.msg('员工号不能为空')
        return
      }
      fd.operatorcode = arr[0].p_workernumber
      fd.operatorname = arr[0].p_nickname
    }
    rsp_config.forEach((t) => {
      if (t.value == fd.tempid) {
        fd.tempname = t.text
      }
    })

    if (type === 0) {
      save_printRoute(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sys-defineprintroute/create', 'post', 'application/json', JSON.stringify(fd))
    } else if (type === 1) {
      save_printRoute(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sys-defineprintroute/update', 'post', 'application/json', JSON.stringify(fd))
    }
  })
  function save_printRoute(grid, url, type, contentType, formData) {
    var pload = PlgDialog.load(2, { shade: [0.6, '#fff'] })
    var rep = null
    Prolog.ajax({
      url: url,
      type: type,
      contentType: contentType,
      data: formData,
      success: function (data) {
        PlgDialog.close(pload)
        rep = data
        if (data.success) {
          PlgDialog.msg(data.message)
          setTimeout(function () {
            changePanel('printRoute_grid_01')
            grid.reload()
          }, 10)
        } else {
          setTimeout(() => {
            PlgDialog.alert(data.message == null ? '接口调用失败' : data.message)
          }, 300)
        }
      },
      error: function () {
        PlgDialog.close(pload)
        PlgDialog.msg('接口调用失败')
      },
    })
    return rep
  }

  //查看打印路由详细
  function show_printRouteinfo(rid, rdata) {
    grid.selectRowById(rid)
    $('#btn_save_printRoute').hide()
    $('#printRoute_span_title').html('打印路由 [' + rdata.printername + '] 信息查看')
    changePanel('printRoute_grid_01_edit')
    $('#printRoute_grid_sub').removeClass()

    new PlgPanel({
      renderer: 'printRoute_grid_sub',
      skin: 2,
      header: {
        isShow: true,
        title: '基本信息',
      },
      defaultBody: {
        layoutCol: 3,
        valueBj: true,
        cols: [
          [
            {
              label: '仓号',
              value: Prolog.getNameByID(rsp_branchid, rdata.branchid),
            },
            {
              label: '工号',
              value: rdata.operatorcode,
            },
            {
              label: '打印机名称',
              value: rdata.printername,
            },
            {
              label: '是否启用',
              value: rdata.status == 1 ? '是' : '否',
            },
            {
              label: '备注',
              value: rdata.remark,
            },
          ],
          [
            {
              label: '创建人',
              value: rdata.createby,
            },
            {
              label: '创建时间',
              value: rdata.createdate,
            },
            {
              label: '修改人',
              value: rdata.lastmodifyby,
            },
            {
              label: '修改时间',
              value: rdata.lastmodifydate,
            },
          ],
        ],
      },
    })
  }

  window.res_printRoute_editClick = function (rid, rdata) {
    grid.selectRowById(rid)
    type = 1
    changePanel('rulefactor_grid_01_edit')
    printRouteFormInit(1, rdata)
  }
  window.res_printRoute_delClick = function (rid) {
    Prolog.delGridRowData(grid, UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/sys-defineprintroute/delete', 'post', 'application/x-www-form-urlencoded', { ids: rid }, false)
  }
  window.res_printRoute_showClick = function (rid, rdata) {
    grid.selectRowById(rid)
    show_printRouteinfo(rid, rdata)
  }
}
