let cacheData = []
let cacheItems = []
$(function () {
  // let query_params = decodeURIComponent(window.location.href.split('?')[1])
  // console.log(query_params)
  let userInfo =
    window.localStorage && JSON.parse(localStorage.getItem('_userInfo'))
  let userName = getQueryString('userName')
  let brandId = getQueryString('id')

  $('#jqGrid').Grid({
    url: '../sys/user/bindList',
    rownumWidth: 60,
    postData: {
      deptId: userInfo.deptId,
      brandId: brandId,
    },
    prmNames: {
      page: 'pageNum',
      rows: 'pageSize',
      order: 'order',
    },
    onSelectAll: function () {
      var grid = $('#jqGrid')
      var rowKey = grid.getGridParam('selarrrow')
      $('#selctedNum').html(rowKey.length)

      cacheData.forEach((item) => {
        $('#' + item.userId)
          .children('input')
          .attr('disabled', true)
      })
      var data = getSelectedRowDatas('#jqGrid')
      data.forEach((item) => {
        $('#' + item.userId)
          .children('input')
          .attr('disabled', false)
      })
    },
    beforeSelectRow(rowid) {
      var grid = $('#jqGrid')
      var item = grid.jqGrid('getRowData', rowid)
      let idx = cacheItems.findIndex((sub) => {
        return sub.userId == item.userId
      })
      console.log(idx)

      if (idx == -1) {
        cacheItems.push(item)
      } else {
        cacheItems[idx] = item
      }

      // cacheItems.indexOf(item)<=-1 && cacheItems.push(rowid)
    },
    onSelectRow: function () {
      var grid = $('#jqGrid')
      var rowKey = grid.getGridParam('selarrrow')
      $('#selctedNum').html(rowKey.length)
      cacheData.forEach((item) => {
        $('#' + item.userId)
          .children('input')
          .attr('disabled', true)
      })
      var data = getSelectedRowDatas('#jqGrid')
      data.forEach((item) => {
        $('#' + item.userId)
          .children('input')
          .attr('disabled', false)
      })
    },
    loadComplete: function () {
      let arr = userName ? userName.split(';') : []
      arr.forEach((item) => {
        $('#jqGrid').jqGrid('setSelection', item)
      })
    },
    height: 450,
    jsonReader: {
      root: 'list',
      page: 'curPage',
      total: 'totalPageNum',
      records: 'totalNum',
    },
    colModel: [
      {
        label: 'userId',
        name: 'userId',
        index: 'userId',
        key: true,
        hidden: true,
      },
      {
        label: '员工名称',
        name: 'username',
        index: 'nickname',
        key: true,
      },
      {
        label: '角色',
        name: 'roleName',
        index: 'roleName',
        width: 75,
        formatter: function (v, c, r) {
          cacheData.push(r)
          console.log(r)
          var str = ''

          if (r.roleId == 8 && r.isPlatformStreamer) {
            str += `<span style="color:#009f95;">${r.roleName}</span>`
          } else {
            str += `<span>${r.roleName}</span>`
          }
          return str
        },
      },
      {
        label: '手机号',
        name: 'mobile',
        index: 'mobile',
        width: 75,
      },
      {
        label: '绑定时间',
        name: 'createTime',
        index: 'create_time',
        width: 100,
        formatter: function (value) {
          return transDate(value, 'yyyy-MM-dd')
        },
      },
      {
        label: '是否同时开通一起逛',
        name: 'canShow',
        index: 'canShow',
        width: 100,
        sortable: false,
        formatter: function (value, col, row) {
          cacheData.push(row)
          return `<div  id="${
            row.userId
          }" style="display: flex;align-items: center;justify-content: center;">
                <input style="width:20px;height:20px;" name="${
                  row.userId
                }" disabled id="${row.userId}" type="radio" value="1" ${
            value ? 'checked' : ''
          }  >
                <span style="margin-right:10px;">是</span>
                <input  style="width:20px;height:20px;" name="${
                  row.userId
                }" disabled id="${row.userId}" type="radio"  value="0" ${
            !value ? 'checked' : ''
          }> 
                <span>否</span>
               </div>`
        },
      },
    ],
  })
})

var setting = {
  data: {
    simpleData: {
      enable: true,
      idKey: 'deptId',
      pIdKey: 'parentId',
      rootPId: -1,
    },
    key: {
      url: 'nourl',
    },
  },
}
var ztree

let id = getQueryString('id')
let sceneName = decodeURIComponent(getQueryString('sceneName'))
console.log(sceneName)
let name = decodeURIComponent(getQueryString('name'))
console.log(name)
const validatePhoneCheck = function (rule, value, callback) {
  if (value === '' || !value) {
    callback(new Error('手机号不能为空'))
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error('手机号不正确'))
  } else {
    callback()
  }
}

var vm = new Vue({
  el: '#rrapp',
  data: {
    sceneName,
    name,
    brandId: id,
    modal1: false,
    q: {
      key: '',
    },
    showList: true,
    title: null,
    roleList: {},
    user: {
      status: 1,
      deptName: '',
      roleIdList: [],
      brandIdList: [],
      brandList: [],
    },
    ruleValidate: {
      username: [
        {
          required: true,
          message: '姓名不能为空',
          trigger: 'blur',
        },
      ],
      email: [
        {
          required: true,
          message: '邮箱不能为空',
          trigger: 'blur',
        },
        {
          type: 'email',
          message: '邮箱格式不正确',
          trigger: 'blur',
        },
      ],
      mobile: [
        {
          required: true,
          validator: validatePhoneCheck,
          trigger: 'blur',
        },
      ],
    },
    brandsList: [],
    brandPage: 1,
    brandPerPage: 10,
    brandTotal: 0,
    brandSeleced: [],
    social: [],
    cacheData: {},
    cacheDataFirst: {},
  },
  watch: {
    brandPage: function name(newVal) {
      this.getBrandList()
    },
  },
  methods: {
    submit() {
      var data = getSelectedRowDatas('#jqGrid')

      let parmas = cacheItems.map((ele) => {
        let canshow = $('#' + ele.userId)
          .children(':radio[name="' + ele.userId + '"]:checked')
          .val()
        let type = -1
        data.forEach((item) => {
          if (ele.userId == item.userId) {
            type = 1
          }
        })
        return {
          brandId: vm.brandId,
          canShow: Number(canshow),
          type: type,
          userId: ele.userId,
        }
      })

      if (parmas.length <= 0) {
        return alert('操作成功', function (index) {
          vm.close(1)
        })
      }

      Ajax.request({
        url: '../brand/bindUser',
        params: JSON.stringify(parmas),
        contentType: 'application/json',
        type: 'POST',
        successCallback: function () {
          alert('操作成功', function (index) {
            vm.close(1)
          })
        },
      })
    },
    close(isReload = '') {
      let name = isReload ? 'closeReload' : 'close'
      window.parent.postMessage(name, '*')
    },
    clickCheck: function (item, idx) {
      item['checked'] = !item['checked']
      this.$set(this.brandsList, idx, item)
    },
    ok: function () {
      let temp = []
      let tempid = []
      var that = this
      Object.keys(vm.cacheData).forEach(function (item) {
        that.cacheData[item].page.list.forEach(function (sub) {
          if (sub['checked']) {
            temp.push(sub)
            tempid.push(sub.id)
          }
        })
      })
      vm.user.brandList = temp
      vm.user.brandIdList = tempid
    },
    cancel: function () {
      this.cacheData = {}
      this.modal1 = false
    },
    query: function () {
      vm.reload(1)
    },
    add: function () {
      vm.showList = false
      vm.title = '新增'
      vm.roleList = {}
      vm.user = {
        status: 1,
        roleIdList: [],
        brandIdList: [],
        deptId: '',
        deptName: '',
      }

      //获取角色信息
      this.getRoleList()
      vm.getDept()
    },
    getDept: function () {
      //加载部门树
      Ajax.request({
        url: '../sys/dept/list?name=',
        async: true,
        successCallback: function (r) {
          ztree = $.fn.zTree.init($('#deptTree'), setting, r.list)
          var node = ztree.getNodeByParam('deptId', vm.user.deptId)
          if (node != null) {
            ztree.selectNode(node)

            vm.user.deptName = node.name
          }
        },
      })
    },
    pageChange: function (page) {
      this.brandPage = page
    },

    update: function () {
      var userId = getSelectedRow('#jqGrid')
      if (userId == null) {
        return
      }

      vm.showList = false
      vm.title = '修改'

      Ajax.request({
        url: '../sys/user/info/' + userId,
        async: true,
        successCallback: function (r) {
          vm.user = r.user
          //获取角色信息
          vm.getRoleList()
          vm.getDept()
        },
      })
    },
    del: function () {
      var userIds = getSelectedRows('#jqGrid')
      if (userIds == null) {
        return
      }

      confirm('确定要删除选中的记录？', function () {
        Ajax.request({
          url: '../sys/user/delete',
          params: JSON.stringify(userIds),
          contentType: 'application/json',
          type: 'POST',
          successCallback: function () {
            alert('操作成功', function (index) {
              vm.reload()
            })
          },
        })
      })
    },
    saveOrUpdate: function (event) {
      if ($('#isSign').css('display') == 'block') {
        return alert('手机号未在指房宝APP中进行注册')
      }
      var url =
        vm.user.userId == null ? '../sys/user/save' : '../sys/user/update'
      Ajax.request({
        url: url,
        params: JSON.stringify(vm.user),
        contentType: 'application/json',
        type: 'POST',
        successCallback: function () {
          alert('操作成功', function (index) {
            vm.reload()
          })
        },
      })
    },
    getRoleList: function () {
      Ajax.request({
        url: '../sys/role/select',
        async: true,
        successCallback: function (r) {
          vm.roleList = r.list
        },
      })
    },
    reload: function (p = '') {
      vm.showList = true
      var page = $('#jqGrid').jqGrid('getGridParam', 'page')
      $('#jqGrid')
        .jqGrid('setGridParam', {
          postData: {
            key: vm.q.key,
          },
          page: p || page,
        })
        .trigger('reloadGrid')
      vm.handleReset('formValidate')
    },
    deptTree: function () {
      openWindow({
        title: '选择部门',
        area: ['300px', '450px'],
        content: jQuery('#deptLayer'),
        btn: ['确定', '取消'],
        btn1: function (index) {
          var node = ztree.getSelectedNodes()
          //选择上级部门
          vm.user.deptId = node[0].deptId
          vm.user.deptName = node[0].name

          layer.close(index)
        },
      })
    },
    handleSubmit: function (name) {
      handleSubmitValidate(this, name, function () {
        vm.saveOrUpdate()
      })
    },
    handleReset: function (name) {
      handleResetForm(this, name)
      this.cacheData = {}
      this.user = {
        status: 1,
        deptName: '',
        roleIdList: [],
        brandIdList: [],
        brandList: [],
      }
    },
  },
})
