<!-- 徐晓菁 -->
<style scoped>
  .row {
    padding: 5px 0;
  }
</style>
<template>
  <div class="container-fluid">
    <el-row class="filter_style">
      <el-col :span="24" style="padding: 0 0">
        <_BTN_FILTER  @on-change="inputChange" :btnGroups="btnGroups" :fileName="fileName" @on-click="exportEve" :tableData="tableData" /></_BTN_FILTER>
      </el-col>
    </el-row>
    <div>
      <el-row class="el-row">
        <el-col :span="24">
          <tree-grid
            :dataSource='tableData'
            :columns='columns'
            :tree-structure="true"
            :tableType = 1
            :btns="btns"
            :selectAll="selectAll"
            :select="select"
            :defaultExpandAll="defaultExpandAll"
            ref="tableGrid"
          ></tree-grid>
        </el-col>
      </el-row>
    </div>
    <MY_POPUP_CONFIG :dialogObj='edit' @confirmBack="editEve"/>
    <_POPUP :dialogObj='logInvalid' @confirmBack="logEve" />
  </div>
</template>
<script>
  import _BTN_FILTER from '@/components/Template/Screen/btn&filterTemp.vue'
  import TreeGrid from '@/components/Template/TabPagin/TreeGrid'
  import _POPUP from '@/components/Template/Popup/Popup.vue'
  import MY_POPUP_CONFIG from './Popup.vue'
  import BasePath from '@/config/BasePath'
  import api from '@/api'
  import log from '@/log'
  import {getUser} from '@/config/info'
  export default {
    mounted () {
      this.queryUpper()
    },
    data () {
      return {
        open: true,
        isOpen: true, // 是否显示展开更多按钮
        isExport: true, // 是否显示导出elcx
        isMore: false, // 是否显示更多按钮
        btnGroups: [
//          {
//            name: '新增',
//            className: 'btn-info',
//            iconName: 'fa-plus',
//            event: this.addClk
//          }
        ], // 定义按钮
        filmode: 0,  // 过滤方式；0:代表本地过滤，1：服务器过滤,
        filType: 1, // 过滤类型；0：单列数据过滤，1：整条数据过滤
        fileName: ['placeCode', 'placeName'], // 过滤的字段
        defaultExpandAll: true,
        tableData: [],
        currentPage: 1, // 默认当前第一页
        pageSize: 10,  // 默认每页20条数据
        pageSizes: [2, 5, 10, 20, 40, 50], // 分页数选择项
        totalCount: 0, // 表格总记录数
        columns: [
          {
            label: '机构名称',
            value: 'label',
            sortable: true,
            align: 'left',
            width: '600px'
          },
          {
            label: '机构编码',
            value: 'unitCode'
          }
        ],
        btns: {
          // type: 'button', // 如果单元格类型是按钮，必须要写btns参数
          btnArr: [
            {
              label: '修改', // 按钮的名称
              value: 'modify', // 按钮的值
              functionName: this.modify, // 按钮的方法
              type: 'warning',
              icon: 'edit'
            },
            {
              label: '删除',
              value: 'delete',
              type: 'danger',
              functionName: this.delete,
              icon: 'delete'
            }
          ],
          value: 'operation',
          label: '操作'
        },
        unitDate: [],
        unitCodeDate: [],
        dataSource: [], // 当前页的数据
        /** 弹出层 **/
        edit: {
          title: '组织机构编辑',
          type: 'addOrgUnits',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              orgType: '',
              unitCode: '',
              unitName: '',
              shortCode: '',
              sortCode: '',
              shortName: '',
              address: '',
              url: '',
              corpCode: '',
              legalPerson: '',
              beginDate: '',
              unitLevel: '',
              permitNo: '',
              codeP1: '',
              entCulture: '',
              thesystem: '',
              companyId: '',
              virtualFlag: '',
              stopId: '',
              regionalism: '',
              remarks: '',
              status: '',
              originFlag: '',
              originApp: '',
              supplierCode: '',
              orgRoleTypId: '',  // 角色类型
              orgrelTypeId: '',  // 营销树
              relOrgRoleTypId: '', // 父节点角色类型
              relOrgUnitId: '', // 父节点id
              parentName: '' // 父节点名称
            }
          }
        },
        logInvalid: {
          title: '会话失效',
          type: 'sessionFailured',
          dialogVisible: false,
          size: 'tiny',
          data: {
            form: {
              userCode: '',
              password: ''
            }
          }
        }
      }
    },
    methods: {
      exportEve () {
        this.$refs.tableGrid.exportExcel()
      }, // 导出Elxc
      moreClk () {
        this.$message('更多click')
      }, // 更多查询条件
      queryData (page, size) {
        // 前段分页
        this.totalCount = this.tableData.length
        this.dataSource = this.tableData.filter((u, index) => index < size * page && index >= size * (page - 1))
      }, // 分页请求
      inputChange (val) {
        /** 搜索功能回调 **/
        let page = this.currentPage
        let size = this.pageSize
        this.dataSource = JSON.parse(val).filter((u, index) => index < size * page && index >= size * (page - 1))
      },
      exclClk () {
        this.$refs.tableGrid.exportExcel()
      }, // 导出excl
      addClk () {
        this.edit.dialogVisible = true
      },
      modify (index, row) {
        this.findByIdUpper(row)
        console.log('form', this.edit.data.form)
        this.edit.dialogVisible = true
      }, // 修改
      delete (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteUpper(row.rowId)
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除!' })
        })
      },
      onendChange (val) {},
      deleteUpper (val) {
        let params = {}
        params.rowId = val
        console.log('params', params)
        api.requestJava('POST', BasePath.ORGUNITS_DELETE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.$notify({title: '成功', message: request.data.message, type: 'success'})
              this.queryUpper()
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({title: '提示', message: request.data.message})
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      }, // 删除接口
      queryUpper () {
        let orgTreeparam = {}
        orgTreeparam.orgrelTypeId = 2
        orgTreeparam.treeRoot = getUser().companyId
        console.log('orgTreeparam:' + JSON.stringify(orgTreeparam))
        api.requestJava('POST', BasePath.ORGUNIT_TREE, orgTreeparam)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.tableData = []
              this.tableData.push(request.data.data)
              console.log('tableData', this.tableData)
//              this.currentPage = 1
//              this.queryData(this.currentPage, this.pageSize)
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({title: '提示', message: request.data.message})
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            this.$store.commit('TOGGLE_LOADING')
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      }, // 查询接口
      findByIdUpper (row) {
        let param = {}
        param.rowId = row.rowId
        api.requestJava('POST', BasePath.ORGUNITS_SELECT, param)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.unitDate = request.data.data
              Object.assign(this.edit.data.form, this.unitDate)
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({title: '提示', message: request.data.message})
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            let culprit = this.$route.name
            // this.toggleLoading()
            log.work(err, culprit)
          })
      }, // 查询接口
      editEve (msg) {
        if (msg === 'update') {
          if (this.edit.data.form.rowId === '') {
            this.findByCodeUpper()
          } else {
            this.findByPidUpper()
          }
        }
        this.unitCodeDate = []
        this.unitDate = []
        this.edit.dialogVisible = false
        let tmp = {
          title: '组织机构编辑',
          type: 'addOrgUnits',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              orgType: '',
              unitCode: '',
              unitName: '',
              shortCode: '',
              sortCode: '',
              shortName: '',
              address: '',
              url: '',
              corpCode: '',
              legalPerson: '',
              beginDate: '',
              unitLevel: '',
              permitNo: '',
              codeP1: '',
              entCulture: '',
              thesystem: '',
              companyId: '',
              virtualFlag: '',
              stopId: '',
              regionalism: '',
              remarks: '',
              status: '',
              originFlag: '',
              originApp: '',
              supplierCode: '',
              orgRoleTypId: '',  // 角色
              orgrelTypeId: '2',  // 营销树
              relOrgRoleTypId: '',
              relOrgUnitId: '',
              parentName: ''
            }
          }
        }
        Object.assign(this.edit, tmp)
      }, // 修改事件
      findByCodeUpper () {
        let param = {}
        param.unitCode = this.edit.data.form.unitCode
        api.requestJava('POST', BasePath.ORGUNITS_SELECT, param)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              if (Object.prototype.toString.call(request.data.data) !== '[object Array]') {
                this.$message({type: 'info', message: '机构编码重复!'})
              } else {
                this.findByPidUpper()
              }
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({title: '提示', message: request.data.message})
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            let culprit = this.$route.name
            // this.toggleLoading()
            log.work(err, culprit)
          })
      }, // 查询接口
      // 过滤器修改事件
      findByPidUpper () {
        let param = {}
        param.rowId = this.edit.data.form.relOrgUnitId
        api.requestJava('POST', BasePath.ORGUNITS_SELECT, param)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              let params = {}
              let units = this.edit.data.form
              let roles = {}
              roles.orgRoleTypId = this.edit.data.form.orgRoleTypId
              roles.status = 1
              let relations = {}
              relations.orgrelTypeId = 2
              relations.orgRoleTypId = this.edit.data.form.orgRoleTypId
              relations.relOrgRoleTypId = request.data.data.orgRoleTypId
              relations.relOrgUnitId = this.edit.data.form.relOrgUnitId
              relations.status = 1
              params.units = units
              params.roles = roles
              params.relations = relations
              console.log('params', params)
              console.log('params_s', JSON.stringify(params))
              this.saveUpper(params)
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({title: '提示', message: request.data.message})
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            let culprit = this.$route.name
            // this.toggleLoading()
            log.work(err, culprit)
          })
      }, // 查询接口
      saveUpper (params) {
        api.requestJava('POST', BasePath.ORGUNITS_INSERT, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.$notify({title: '成功', message: request.data.message, type: 'success'})
              this.queryUpper()
            } else if (Number(request.data.code) === 401) {
              this.$message('登录失效')
              this.logInvalid.dialogVisible = true
            } else {
              this.$notify.error({ title: '提示', message: request.data.message })
              throw new Error(JSON.stringify(request))
            }
          })
          .catch((err) => {
            let culprit = this.$route.name
            log.work(err, culprit)
          })
      }, // 保存
      handleQuery () {},
      select (selection, index) {
        this.selectSells = selection
      },
      selectAll (selection) {
        this.selectSells = selection
      },
      rowClick (data, index, event) {
        console.log('当前行数据:' + data)
        console.log('点击行号:' + index)
        console.log('点击事件:' + event)
      },
      selectionClick (arr) {
        console.log('选中数据id数组:' + arr)
      },
      sortClick (key, type) {
        console.log('排序字段:' + key)
        console.log('排序规则:' + type)
      },
      openClk (isTrue) {
        this.$refs.tableGrid.expand(isTrue)
      }, //  展开-收起
      handleSelect (item) {
        console.log(item)
      },
      querySearch (queryString, cb) {
        var restaurants = this.tableData
        var results = queryString ? restaurants.filter(this.createFilterLine(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
        console.log(results)
        if (results.length > 0) {
          let page = this.currentPage
          let size = this.pageSize
          this.dataSource = results.filter((u, index) => index < size * page && index >= size * (page - 1))
        } else {
          this.dataSource = []
        }
      },
      createFilterLine (queryString) {
        return (restaurant) => {
          this.isTrue = false
          this.tempMen(restaurant, queryString)
          return (this.isTrue === true)
        }
      }, // 过滤整条数据
      tempMen (obj, str) {
        for (let i in obj) {
          for (let j in this.fileName) {
            if (this.fileName[j] === i) {
              if (obj[i] !== undefined && obj[i].toString().toLocaleUpperCase().indexOf(str.toLocaleUpperCase()) === 0) {
                this.isTrue = true
              }
            }
          }
        }
      },
      logEve (msg) {
        let headers = {}
        headers.userCode = msg.data.form.userCode
        headers.password = msg.data.form.password
        let array = [headers, this]
        this.$store.dispatch('login', array)
          .then((msg) => {
            if (msg === 'success') {
              this.logInvalid.dialogVisible = false
              this.$router.go(0)  //  刷新父页面
            }
          })
          .catch((err) => { console.log(err) })
      } //  session 失效
    },
    components: {
      TreeGrid,
      _POPUP,
      MY_POPUP_CONFIG,
      _BTN_FILTER
    },
    watch: {
      filVal (val, oval) {
        if (val === '') {
          this.currentPage = 1
          this.queryData(this.currentPage, this.pageSize)
        }
      }
    }
  }
</script>

