let userInfo =
  window.localStorage && JSON.parse(localStorage.getItem('_userInfo'))

$(function () {
  $('#jqGrid').Grid({
    // url: '../brand/brandBindList',
    url: '../scene/list',
    // postData: {
    //     deptId: userInfo.deptId,
    //     bindStatus: ''
    // },
    dataType: 'json',
    ajaxGridOptions: {
      contentType: 'application/json',
    },
    mtype: 'POST',
    serializeGridData: function (postData) {
      return JSON.stringify(postData)
    },
    postData: {
      token: localStorage.getItem('token'),
      // pageNum:1,
      // pageSize:10
    },
    rownumWidth: 60,
    multiboxonly: true,
    jsonReader: {
      root: 'page.list',
      page: 'page.pageNum',
      total: 'page.pages',
      records: 'page.total',
    },
    colModel: [
      {
        label: '场景码',
        name: 'num',
        index: 'num',
        hidden: true,
        key: true,
      },
      {
        label: '场景ID',
        name: 'id',
        index: 'id',
        hidden: true,
      },
      {
        label: '场景名称',
        name: 'name',
        width: 75,
      },
      // { label: '所属VR场景', name: 'name', width: 75 },
      {
        label: '封面',
        // name: 'listPicUrl',
        name: 'appListPicUrl',
        width: 75,
        align: 'center',
        index: 'list_pic_url',
        formatter: function (value) {
          console.log(value)

          if (value == '' || !value) {
            value = '../statics/img/pic_bg@2x.png'
          }
          return transImg(value, 100, 'auto')
        },
      },
      {
        label: '场景链接',
        name: 'sceneUrl',
        width: 100,
      },
      {
        label: '已绑定员工',
        name: 'bindShowerNameList',
        width: 100,
        sortable: false,
        hidden: true,
      },
      {
        label: '是否显示',
        name: 'isShow',
        align: 'center',
        width: 20,
        sortable: false,
        formatter: function (value) {
          return transIsNot(value)
        },
      },
      {
        label: '操作',
        width: 20,
        align: 'center',
        sortable: false,
        hidden:
          JSON.parse(localStorage.getItem('userInfo')).roleIdList[0] == 5 ||
          (JSON.parse(localStorage.getItem('userInfo')).roleIdList[0] == 8 &&
            JSON.parse(localStorage.getItem('userInfo')).isPlatformStreamer),
        formatter: function (value, col, row) {
          let sceneUrl = row.sceneUrl
          let lived = row.lived
          let sceneNum = row.num
          sceneUrl = sceneUrl.replace('smobile', 'epc')
          // let sceneNum = row.sceneNum
          var str = ``
          str += `<a style="color: #2db7f5;"  onclick="open_4dkankan('${sceneUrl}','${sceneNum}')" target="_blank">打开编辑器</a><br/><br/>`

          if (!lived) {
            str += `<a v-if="lived" style="color: #2db7f5;"  onclick="createdLiveRoom('${sceneNum}')" target="_blank">生成直播间</a>`
          }
          return str
        },
      },
    ],
  })
})

function createdLiveRoom(sceneNum) {
  confirm('是否要生成直播间？', function () {
    vm.loading = true
    let t = setTimeout(() => {
      // 用户点击时执行
      Ajax.request({
        url: '../scene/generateDefaultLiveRoom',
        type: 'POST',
        params: JSON.stringify({
          sceneNum: sceneNum,
          token: localStorage.getItem('token'),
        }),
        contentType: 'application/json',

        successCallback: function (r) {
          vm.loading = false
          alert('生成直播间成功', function (index) {
            vm.reload()
          })
        },
        failCallback: function (err) {
          vm.loading = false
        },
      })
      clearTimeout(t)
    }, 100)
  })
}

function open_4dkankan(url, sceneNum) {
  // 用户点击时执行
  let newTab = window.open('about:blank')

  let token = localStorage.getItem('token')
  console.log()
  let mobile = JSON.parse(localStorage.getItem('userInfo')).mobile
  Ajax.request({
    url: '../token/renewToken',
    type: 'POST',
    params: JSON.stringify({
      token: token,
      userName: mobile,
      sceneNum: sceneNum,
      sceneUrl: url,
    }),
    contentType: 'application/json',

    successCallback: function (r) {
      // 获取start_url成功后执行
      newTab.location.href = url + '&menu=business&token=' + r.data
      // window.open(url.toString())
    },
  })
}
var setting = {
  data: {
    simpleData: {
      enable: true,
      idKey: 'deptId',
      pIdKey: 'parentId',
      rootPId: -1,
    },
    key: {
      url: 'nourl',
    },
  },
}
var ztree

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: {
    loading: false,
    modal1: false,
    q: {
      name: '',
      brandName: '',
      bindStatus: '',
    },
    // lessNum:0,
    showList: true,
    showInApp: false,
    appShow: {
      name: '',
      isShow: '',
      listPicUrl: '',
      appListPicUrl: '',
      id: '',
      num: '',
    },
    roleBangding: false,
    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',
        },
      ],
    },
    ruleValidate1: {
      name: [
        {
          required: true,
          message: '场景名称不能为空',
          trigger: 'blur',
        },
      ],

      listPicUrl: [
        {
          required: true,
          message: '图片不能为空',
          trigger: 'blur',
        },
      ],
    },
    brandsList: [],
    brandPage: 1,
    brandPerPage: 10,
    brandTotal: 0,
    brandSeleced: [],
    social: [],
    cacheData: {},
    cacheDataFirst: {},
  },
  watch: {
    brandPage: function name(newVal) {
      this.getBrandList()
    },
  },
  mounted() {
    // this.getLessNum()
    window.addEventListener(
      'message',
      function (e) {
        var data = e.data
        if (data === 'close') {
          layer.closeAll()
        }

        if (data === 'closeReload') {
          layer.closeAll()
          vm.reload()
        }

        if (data.website) {
          vm.brand.sceneUrl = data.website[0] || ''
          vm.brand.name = data.website[1] || ''
          layer.closeAll()
        }

        if (data.userId) {
          vm.brand.adminId = parseInt(data.userId) || ''
          vm.brand.adminName = data.nickname || ''
          layer.closeAll()
        }
      },
      false
    )
  },
  methods: {
    showYoN: function (event) {
      var id = getSelectedRow('#jqGrid')
      if (id == null) {
        return
      } else {
        var data = $('#jqGrid').jqGrid('getRowData', id)

        if (data == null) {
          return
        }

        this.appShow.name = data.name
        // this.appShow.listPicUrl = data.listPicUrl
        this.appShow.num = data.num
        this.appShow.id = data.id
        vm.getInfo(data.id, data.num)
        if (data.isShow.indexOf('是') != -1) {
          this.appShow.isShow = 1
        } else {
          this.appShow.isShow = 0
        }
        // vm.roleBangding = true;
        vm.showInApp = true
        vm.showList = false
        vm.title = '修改'
      }

      //vm.getInfo(id);
    },
    getInfo: function (id, sceneNum) {
      let params = {
        id: id,
        sceneNum: sceneNum,
        token: localStorage.getItem('token'),
      }
      Ajax.request({
        type: 'POST',
        url: '../scene/info',
        contentType: 'application/json',
        dataType: 'json',
        params: JSON.stringify(params),
        async: true,
        successCallback: function (r) {
          vm.appShow.appListPicUrl = r.brand.appListPicUrl
        },
      })
    },
    save_isShow() {
      let data = {
        name: this.appShow.name,
        isShow: this.appShow.isShow,
        id: this.appShow.id,
        appListPicUrl: this.appShow.appListPicUrl,
        sceneNum: this.appShow.num,
        token: localStorage.getItem('token'),
      }
      Ajax.request({
        type: 'POST',
        url: '../scene/update',
        contentType: 'application/json',
        dataType: 'json',
        // params: { "isShow": this.appShow.isShow, "id": this.appShow.id },
        params: JSON.stringify(data),
        successCallback: function () {
          alert('操作成功', function (index) {
            vm.reload()
          })
        },
      })
      // $.ajax({
      //     contentType: 'application/json',
      //    type: 'POST',
      //    url: "../brand/updateShowStatus",
      //    dataType: "json",
      //    data: JSON.stringify(data),
      //     success: function (message) {
      //         alert('操作成功', function (index) {
      //             vm.reload();
      //         })
      //     },
      //  });
    },
    clickCheck: function (item, idx) {
      item['checked'] = !item['checked']
      this.$set(this.brandsList, idx, item)
    },
    open: function () {
      var userId = getSelectedRow('#jqGrid')
      if (userId == null) {
        return
      } else {
        var data = getSelectedRowData('#jqGrid')
        openWindow({
          type: 2,
          title: '绑定员工',
          content: `../shop/selectUser.html?name=${data.name}&name=${data.name}&id=${data.id}&userName=${data.bindShowerNameList}`,
        })
      }
    },
    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 = '新增(默认密码：888888)'
      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
    },
    getBrandList: function () {
      this.modal1 = true
      if (this.cacheData[this.brandPage]) {
        let temp = this.cacheData[this.brandPage]
        this.brandsList = temp.page.list
        this.brandPage = temp.page.pageNum
        this.brandTotal = temp.page.total
        return
      }
      let that = this

      Ajax.request({
        url:
          '../scene/list?_search=false&pageSize=' +
          that.brandPerPage +
          '&pageNum=' +
          that.brandPage +
          '&sidx=&order=asc',
        // url: '../brand/list?_search=false&pageSize=' + limit + '&pageNum=' + page + '&sidx=&order=asc',
        async: true,
        successCallback: function (res) {
          res.page.list.forEach(function (item, index) {
            item['checked'] = false
            if (that.user.brandList) {
              that.user.brandList.forEach(function (sub) {
                // item['checked'] = false
                if (item.id === sub.brandId || item.id === sub.id) {
                  item['checked'] = true
                  return
                }
              })
            }
          })

          that.cacheData[res.page.currPage] = res
          that.brandsList = res.page.list
          that.brandPage = res.page.pageNum
          that.brandTotal = res.page.total
        },
      })
    },
    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()
            })
          },
        })
      })
    },
    syncScene: function () {
      Ajax.request({
        url: '../scene/sync4dkkSceneData',
        contentType: 'application/json',
        type: 'get',
        successCallback: function (res) {
          if (res.code == 0) {
            alert('同步成功', function (index) {
              vm.reload()
            })
          } else {
            alert(res.msg)
          }
        },
      })
    },
    saveOrUpdate: function (event) {
      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()
          })
        },
      })
    },
    handleSuccessListPicUrl: function (res, file) {
      vm.appShow.listPicUrl =
        file.response.url + window.fixImg + 'm_fixed,w_400,h_400'
      vm.appShow.appListPicUrl =
        file.response.url + window.fixImg + 'm_fixed,w_400,h_400'
      this.$refs.formValidate1.validate()
      //  vm.brand.listPicUrl = file.response.url;
      //  vm.brand.appListPicUrl = file.response.url ;
    },
    handleFormatError: function (file) {
      this.loading = false
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确。',
      })
    },
    handleMaxSize: function (file) {
      this.loading = false
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大。',
      })
    },
    // getLessNum: function () {
    //     Ajax.request({
    //         url: '../sys/dept/getLessNum?deptId='+userInfo.deptId,
    //         async: true,
    //         successCallback: function (r) {
    //             vm.lessNum = r.less
    //         }
    //     });
    // },
    getRoleList: function () {
      Ajax.request({
        url: '../sys/role/select',
        async: true,
        successCallback: function (r) {
          vm.roleList = r.list
        },
      })
    },
    reload: function (event) {
      vm.showList = true
      vm.showInApp = false
      var page = event ? 1 : $('#jqGrid').jqGrid('getGridParam', 'page')
      $('#jqGrid')
        .jqGrid('setGridParam', {
          postData: {
            name: vm.q.name,
            brandName: vm.q.brandName,
            bindStatus: vm.q.bindStatus,
          },
          page: page || 1,
        })
        .trigger('reloadGrid')
      // vm.getLessNum()
      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()
      })
    },
    handleSubmit1: function (name) {
      handleSubmitValidate(this, name, function () {
        vm.save_isShow()
      })
    },
    handleReset: function (name) {
      handleResetForm(this, name)
      this.cacheData = {}
      this.user = {
        status: 1,
        deptName: '',
        roleIdList: [],
        brandIdList: [],
        brandList: [],
      }
    },
  },
})
