<template>
  <el-dialog
      class="select-department"
      :width="width"
      :title="title"
      :visible.sync="openOrClose"
      >
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="请输入部门名称"
          style="width: 160px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission"></crudOperation>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="getDeptDatas"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="index" label="序号" width="120" align="center"/>
      <el-table-column
        v-for="item in selectDepartmentTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      ></el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <udOperation :data="scope.row" :permission="permission" /> -->
          <el-button type="primary" v-if="!buttonShow(scope.row)" @click="selectData(scope.row)">选择</el-button>
          <el-button type="warning" v-if="buttonShow(scope.row)"  @click="cancleData(scope.row)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="saveViewData()" >保 存</el-button>
    <el-button @click="openOrClose = false">关 闭</el-button>
  </span>
  </div>
  </el-dialog>
</template>

<script>
import permission from '@/directive/permission'
import crudDept from '@/api/system/dept'
import { getOptions } from '@/api/system/public'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'
import { selectDepartmentTableOptions } from '../tableConfig'
import { getToken } from '@/utils/auth'
import { initData } from '@/api/data'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

const defaultForm = {
  id: null,
  code: '',
  name: '',
  areaId: '',
  departmentId: '',
  userIds:[],
  
}

export default {
  name: 'selectDepartment',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps, DateRangePicker,Treeselect },
  cruds() {
    return CRUD({
      title: '选择部门',
      url: 'system/department/getList',
      listOrder: [],
      crudMethod: { ...crudDept },
      optShow: { add: false, edit: false, del: false, reset: true },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
  },
  props: {
    title: {
      type: String,
      default: '',
    },
    width: {
      type: String,
      default:'60',
    },
    dataType: {
      type: String,
      default: '',
    },
    checkFlag: {
      type: String,
      default: '1',
    },
    dataM: {
      type: Array,
      default: () => [],
    },
    openOrClose: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      mapData: [],
      buildFloor: {},
      selectDepartmentTableOptions,
      viewLoading: false,
      permission: {
        add: ['admin', 'selectDepartment : add'],
        edit: ['admin', 'selectDepartment : edit'],
        del: ['admin', 'selectDepartment : del'],
      },
      rules: {
        name: [{ required: true, message: '请输入检查点名称', trigger: 'blur' }],
        labelCode: [{ required: true, message: '请选择巡检标签', trigger: 'blur' }],
        areaId: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
      },
      optionsObj: {
        Department: [],
        Job: [],
      },
      token: getToken() ?? '',
      dataList:[],
    }
  },
  created() {
    // this.getOptions()
  },
  methods: {
    // // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      },
    [CRUD.HOOK.beforeToAdd]() {
      },
    [CRUD.HOOK.beforeToEdit]() {
     
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    buttonShow(row){

      if (this.dataList) {
        for (let i = 0; i < this.dataList.length; i++) {
          const u = this.dataList[i];
          if (row.id == u.id) {
            return true
          }
        }
      }
      return false
    },
    selectData(row){
      // console.log(row)
      if(this.checkFlag == '1'){
        this.dataList.splice(0,1,row)
        this.$emit('getData',this.dataList)
        console.log(this.dataList)
        this.openOrClose = false
      }
      if(this.checkFlag == '2'){
        this.dataList.push(row)
      }
    },
    cancleData(row){
      if(this.checkFlag == '1'){
        this.dataList.pop()
      }
      if(this.checkFlag == '2'){
        if(this.dataList) {
          for (let i = 0; i < this.dataList.length; i++) {
            const u = this.dataList[i];
            if (u.id == row.id) {
              this.dataList.splice(i,1)
            }
          }
        }
      }
    },
    saveViewData(){
      if(this.checkFlag == '2'){
        this.$emit('getData',this.dataList)
        // console.log(this.dataList)
      }
      this.openOrClose = false
    },
    getDeptDatas(tree, treeNode, resolve) {
      const params = { id: tree.id }
      setTimeout(() => {
        crudDept.getDepts(params).then(res => {
          resolve(res.data.content)
        })
      }, 100)
    },
    /**
     * 编辑时获取下拉框的菜单树
     * 接口获取的是完整数据（偷懒）
     */
    getSupDepts(id) {
      crudDept.getDeptsTree({ id: '0' }).then(res => {
        const date = res.data.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach(data => {
        // if (!data.hasChildren) {
        //   delete data.children
        // }
        if (data.children) {
          this.buildDepts(data.children)
        }
        // if (data.hasChildren && !data.children) {
        //   data.children = null
        // }
      })
    },
    getDepts() {
      crudDept.getDepts({ id: '0' }).then(res => {
        console.log(res)
        this.depts = res.data.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDept.getDepts({ enabled: true, id: parentNode.id }).then(res => {
          parentNode.children = res.data.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // async getItemOptions(id) {
    //   try {
    //     let res = await getOptions('Item', { id: id })
    //     if (res.code === 20000) this.optionsItem = res.data.content
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
    // //获取弹窗内的围栏信息
    // async getRailData() {
    //   try {
    //     const res = await initData('positioning/rail/getPageListJson', {
    //       PageIndex: 0,
    //       PageSize: 0,
    //     })
    //     const data = res.data.content
    //     this.personRailAlarmConfigList = data.map((item) => {
    //       return {
    //         railId: item.id,
    //         railName: item.railName,
    //         crossInAlarm: false,
    //         crossOutAlarm: false,
    //         overstayAlarm: false,
    //         actionlessAlarm: false,
    //       }
    //     })
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
    // //获取弹窗内的区域信息
    // async getAreaData() {
    //   try {
    //     const res = await initData('positioning/area/getPageListJson', {
    //       PageIndex: 0,
    //       PageSize: 0,
    //     })
    //     const data = res.data.content
    //     this.personAreaAlarmConfigList = data.map((item) => {
    //       return {
    //         areaId: item.id,
    //         areaName: item.areaName,
    //         crossInAlarm: false,
    //         crossOutAlarm: false,
    //         overstayAlarm: false,
    //         actionlessAlarm: false,
    //       }
    //     })
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
  }
}
</script>

<style lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
