import { ACCESS_TOKEN, ACCESS_EXPIRE } from '@/store/mutation-types'
import { errorHandler } from './request'
import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE, UPCLOUD_RDC_TMS_BUSINESS_SERVICE, SERVICE_PLATFORM_POWER_BASE } from '@/config/serviceSettings.js'
const plglib = require('plglib')

//plglib.ExceptionModal
// var Prolog = {
//   GridImageBasePath: "/prologui/dist/images/PlgGrid/",
//   token: "",

//   loginUrl: "",
//   loginPage: "",
//   refreshTokenUrl: "",
//   showLoginForm: false
// };
let Prolog = window.Prolog
Prolog.GridImageBasePath = '/tms/prologui/dist/images/PlgGrid/'
Prolog.reloadToken = function () {
  Prolog.token = 'Bearer ' + sessionStorage.getItem(ACCESS_TOKEN)
  return Prolog.token
}
/**
 * 刷新token逻辑
 */
Prolog.refreshToken = function () {
  var expir = sessionStorage.getItem(ACCESS_EXPIRE)
  var authorization = sessionStorage.getItem(ACCESS_TOKEN)
  if (expir && authorization) {
    var exp = parseInt(expir)
    var now = new Date().getTime()
    var b = exp - now < 360000 && now < exp ? true : false
    //console.log(b);
    if (b && Prolog.refreshTokenUrl != undefined && Prolog.refreshTokenUrl != '') {
      $.ajax({
        url: Prolog.refreshTokenUrl,
        method: 'GET',
        beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', authorization)
        },
        success: function (data) {
          if (data.success) {
            sessionStorage.setItem('authorization', 'Bearer ' + data.data.token)
            sessionStorage.setItem(ACCESS_EXPIRE, data.data.expir)
            Prolog.reloadToken()
          }
        },
      })
    }
  }
}

Prolog.ajax = function (options) {
  //检验token
  if (Prolog.requireLogin(options)) {
    Prolog.closeLoading()
    return
  }

  Prolog.refreshToken()
  Prolog.reloadToken()
  var pdefault = {
    timeout: 30000,
    dataType: 'json',
  }
  var opt = $.extend(true, pdefault, options)

  opt.error = function (XMLHttpRequest, textStatus, errorThrown) {
    layer.closeAll('loading')
    XMLHttpRequest.data = {}
    Prolog.closeLoading()
    XMLHttpRequest.data.message = options.url
    errorHandler({ response: XMLHttpRequest })
    if (options.error) options.error(XMLHttpRequest, textStatus, errorThrown)
  }
  opt.beforeSend = function (xhr) {
    xhr.setRequestHeader('Authorization', Prolog.token)
    if (options.beforeSend) {
      options.beforeSend(xhr)
    }
  }
  opt.success = function (data) {
    if (data && !data.success) {

      data.data = data.data ? data.data : data.message;
      plglib.ExceptionModal(data)
    }
    return options.success && options.success(data)
  }

  $.ajax(opt)
}
/**
 * 登录失效处理逻辑
 */
Prolog.requireLogin = function (options) {
  var url = options.url
  if (url == null) return false

  if (url.indexOf(Prolog.loginUrl) > -1) return false

  if (Prolog.isLogined()) {
    return false
  }
  if (Prolog.showLoginForm) {
    return false
  }
  Prolog.showLoginForm = true
  if (Prolog.loginUrl == undefined || Prolog.loginUrl == '') {
    if (Prolog.loginPage != undefined && Prolog.loginPage != '') {
      sessionStorage.clear()
      location.href = Prolog.loginPage
    }
    return
  }

  var iidx = layer.prompt(
    {
      title: _t('请验证你的密码'),
      formType: 1,
      closeBtn: 0,
      btn: [_t('确认'), _t('退出登录')],
      success: function (layero, index) {
        var inp = layero.find('input')
        Prolog.removeLoading()
        inp[0].onkeydown = function (event) {
          if (13 == event.keyCode) {
            inp[0].blur()
            var pass = layero.find('input').val()
            Prolog.validatePassword(pass, options), (Prolog.showLoginForm = !1)
            layer.close(iidx)
          }
        }
      },
      btn2: function () {
        //layer.msg("请验证密码",function(){});
        sessionStorage.clear()
        location.href = Prolog.loginPage
        return true
      },
    },
    function (pass, index) {
      var btn = $('#layui-layer' + index).find('.layui-layer-btn0')
      if (btn.hasClass('layui-btn-disabled')) return

      btn.addClass('layui-btn-disabled')
      Prolog.validatePassword(pass, options)
      Prolog.showLoginForm = false
      layer.close(index)
    }
  )

  return true
}
/**
 * 验证密码
 */
Prolog.validatePassword = function (pass, options) {
  var close = PlgDialog.loading2()
  if (pass == null || pass == '') {
    close()
    layer.msg(_t('请输入有效密码'), function () { })
    return false
  }

  var userinfo = JSON.parse(sessionStorage.getItem('userinfo'))
  if (userinfo != null && userinfo.p_username != null) {
    $.ajax({
      url: Prolog.loginUrl,
      method: 'POST',
      async: false,
      data: { username: userinfo.p_username, password: pass },
      dataType: 'json',
      success: function (data) {
        if (data.success) {
          sessionStorage.setItem('authorization', 'Bearer ' + data.data.token)
          sessionStorage.setItem(ACCESS_EXPIRE, data.data.expir)
          Prolog.reloadToken()
          if (options) Prolog.ajax(options)
        } else {
          layer.msg(_t('密码错误'), { icon: 5 })
        }
      },
    })
    close()
  } else {
    sessionStorage.clear()
    location.href = Prolog.loginPage
    close()
  }
}

Prolog.syncAjax = function (options) {
  options.async = false
  return Prolog.ajax(options)
}

//公共查询下拉框
export function getSelectGJ(data, Callback) {
  //查询下拉框
  window.utilSyncAjaxGJ(
    UPCLOUD_RDC_TMS_MAINDATA_SERVICE + '/refdata/dtl/dd-list',
    'post',
    JSON.stringify(data),
    function (datas) {
      Callback(datas)
    },
    'application/json'
  )
}

/*
 * @method 获取图片url
 * @author zzx
 * @param request 接口请求参数
 */
export function querySysPicture(request) {
  let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] })
  return new Promise((resolve, reject) => {
    Prolog.ajax({
      url: UPCLOUD_RDC_TMS_BUSINESS_SERVICE + '/sysFile/querySysPicture',
      type: 'post',
      contentType: 'application/json',
      data: JSON.stringify(request),
      success: function (res) {
        PlgDialog.close(pload)
        if (res.success) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      error: function () {
        PlgDialog.close(pload)
        return false
      },
    })
  })
}

// 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';

//异步调后台
window.utilAjaxGJ = function (url, type, data, Callback, contentType) {
  let pload = PlgDialog.load(2, { shade: [0.6, '#fff'] })
  Prolog.ajax({
    url: url,
    type: type,
    data: data,
    contentType: contentType,
    success: function (da) {
      PlgDialog.close(pload)

      if (typeof da != 'object') {
        da = JSON.parse(da)
      }
      Callback && Callback(da)
    },
    error: function () { },
  })
}
//同步调后台
window.utilSyncAjaxGJ = function (url, type, data, Callback, contentType) {
  PlgDialog.load(2, { shade: [0.6, '#fff'] })
  Prolog.syncAjax({
    url: url,
    type: type,
    data: data,
    contentType: contentType,
    success: function (da) {
      layer.closeAll()
      if (typeof da != 'object') da = JSON.parse(da)

      Callback(da)
    },
    error: function () { },
  })
}

// 部门弹窗
export function departmentDialog(id, edit_form) {
  $(id + " input").on("click", function (data) {
    if (data.delegateTarget.name === "departmentName") {
      let zTree;
      Prolog.ajax({
        url: SERVICE_PLATFORM_POWER_BASE + "/organization/all", type: "get",
        success: function (res) {
          if (res.success) {
            let { departmentId } = edit_form.getFormData()
            let list = res.data.map(item => {
              if (item.id === departmentId) item.checked = true
              return item
            })
            PlgDialog.open({
              title: '部门',
              shadeClose: true,
              type: 1, // 设置为1，手动控制dialog的开关
              area: ['500px', '600px'],
              content: '<div id ="departmentDialog"></div>', //iframe的url
              btn: ["保存", "取消"],
              yes: function (index, layero) {
                let selectList = zTree.treeObj.getCheckedNodes()
                if (!selectList.length) {
                  layer.msg("请选择部门");
                  return;
                }
                let { id: departmentId, code: departmentCode, name: departmentName } = selectList[0]
                edit_form.setFormData({ departmentId, departmentCode, departmentName })
                PlgDialog.close(index);
              },
              btn2: function (index) {
                PlgDialog.close(index);
              },
            })

            zTree = new PlgZtree({
              renderer: "departmentDialog",
              skin: "menu-tree",
              setData: list,
              setting: {
                data: {
                  key: {
                    name: "name"
                  },
                  simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: "0",
                    id: 'id',
                  },
                },
                check: {
                  enable: true,
                  chkStyle: "radio",
                  radioType: "all"
                },
                callback: {
                  onClick: function (e, treeId, treeNode) {
                    zTree.treeObj.checkNode(treeNode, !treeNode.checked, true);
                  },
                  onCheck: function (e, treeId, treeNode) {
                    zTree.treeObj.selectNode(treeNode);
                  }
                }
              }
            })
            zTree.treeObj.expandAll(true)
            return true;
          }
          return false;
        },
        error: function () { return false; }
      });
    }
  });
}
