<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      title="选择企业"
      :visible.sync="showTroubleshooting"
      width="70%"
      :before-close="handleClose"
      top="10vh"
    >
      <el-row :gutter="20">
        <el-col :span="16">
          <div ref="contentPanel">
            <el-form v-model="querys" :inline="true">
              <el-form-item label="项目编号">
                <el-input
                  size="small"
                  v-model="querys[0].value"
                  clearable
                  placeholder="请输入项目编号"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  size="small"
                  type="danger"
                  icon="el-icon-search"
                  @click="handleSearch"
                  >搜索</el-button
                >
                <el-button
                  size="small"
                  icon="el-icon-refresh"
                  @click="handleReset"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <el-table
            ref="multipleTable"
            row-key="id"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            size="mini"
            border
            height="380"
            @select="handleSelectionChange"
            @select-all="selectAll"
          >
            <el-table-column
              type="selection"
              reserve-selection
              width="55"
              align="center"
            />
            <el-table-column type="index" width="55" label="序号" />
            <el-table-column
              prop="name"
              min-width="10%"
              label="企业名称"
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="code"
              show-overflow-tooltip
              min-width="10%"
              align="center"
              label="企业编码 "
              resizable
            >
            </el-table-column>
          </el-table>
          <el-pagination
            ref="paginationPanel"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParam.pageBean.page"
            :page-sizes="[5, 20, 30, 40, 50]"
            :page-size="queryParam.pageBean.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParam.pageBean.total"
          >
          </el-pagination>
        </el-col>
        <el-col :span="8">
          <div style="font-size: 14px">
            已选中企业（{{ selectUsers.length }}）
          </div>
          <el-table
            :data="selectUsers"
            style="width: 100%"
            size="mini"
            border
            height="380"
          >
            <el-table-column type="index" width="55" label="序号" />
            <el-table-column
              prop="name"
              min-width="10%"
              label="企业名称"
              align="center"
              resizable
            >
            </el-table-column>
            <el-table-column
              prop="address"
              label="操作"
              align="center"
              width="80"
            >
              <template slot-scope="scope">
                <el-link
                  :underline="false"
                  @click.native.prevent="deleteUser(scope.row)"
                  >移除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import basicData from '@/api/basicData'
export default {
  name: 'CmgtSaftyDangerCheckplanFormDialogTroubleshooting', // 排查计划明细
  props: {
    title: String,
    useOrgList: Array,
    multiple: {
      type: Boolean,
      default: true,
    },
    needReturnKey: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      showTroubleshooting: false, // 控制弹层显示与隐藏
      multipleSelection: [],
      selectedValue: [],
      treeData: [],
      defaultProps: {
        id: 'code',
        label: 'name',
        isLeaf: 'leaf',
      },
      querys: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'name_',
          relation: 'AND',
          value: '',
        },
        {
          group: 'main',
          operation: 'NOT_EQUAL',
          parentGroup: '',
          property: 'grade_',
          relation: 'AND',
          value: '1003001',
        },
        {
          group: 'main',
          operation: 'NOT_EQUAL',
          parentGroup: '',
          property: 'id',
          relation: 'AND',
          value: '',
        },
      ],
      queryParam: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
      },
      currentUser: {},
      selectUsers: [],
    }
  },
  mixins: [TableMixin],
  created() {
    this.currentUser = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    this.querys[2].value = this.currentUser.org[0].orgId
  },
  methods: {
    // 对顶部选择框进行禁用
    headerCellClassName({row, column, rowIndex, columnIndex}) {
      if (!this.multiple && columnIndex == 0) {
        return 'is-disable'
      }
    },
    rowKey(row) {
      return row.id
    },
    //搜索
    handleSearch() {
      this.loadData()
    },
    //重置
    handleReset() {
      this.querys[0].value = ''
      this.querys[1].value = '1003001'
      this.querys[2].value = this.currentUser.org[0].orgId
      this.loadData()
    },
    //显示弹框
    add() {
      this.showTroubleshooting = true
      this.loadData()
      this.$nextTick(function () {
        this.selectedValue = this.useOrgList
        this.initTableSelection()
      })
    },
    // 初始化表格行的选中状态
    initTableSelection() {
      if (this.selectedValue.length) {
        this.selectedValue = this.selectedValue.filter((item, index) => {
          let selectItem = this.tableData.find((tItem) => tItem.id === item.id)
          if (!!selectItem) {
            this.$refs.multipleTable.toggleRowSelection(selectItem, true)
          }
          return !selectItem
        })
        this.selectedValue.forEach(item=>{
            this.selectUsers.push(item)
        })
       
      }
    },
    // 获取list
    loadData() {
      this.loading = true
      this.tableData = []
      this.queryParam.querys = []
      if (this.querys[0].value) {
        this.queryParam.querys.push(this.querys[0])
      }
      if (this.querys[1].value) {
        this.queryParam.querys.push(this.querys[1])
      }
      if (this.querys[2].value) {
        this.queryParam.querys.push(this.querys[2])
      }
      basicData.getOrgPage(this.queryParam).then((res) => {
        this.loading = false
        this.queryParam.pageBean.total = res.total
        this.tableData = res.rows
        this.initTableSelection()
        this.$set(this.tableData)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击关闭按钮
    handleClose() {
      this.$refs.multipleTable.clearSelection()
      this.selectUsers = []
      this.showTroubleshooting = false
    },
    // 保存按钮
    handleSave() {
      let list = []
      this.selectUsers.forEach((item) => {
        let obj = {name: item.name, id: item.id, code: item.code}
        this.needReturnKey.forEach((key) => {
          this.$set(obj, key, item[key])
        })
        list.push(obj)
      })
      list = Array.from(new Set(list.map(JSON.stringify)), JSON.parse)
      this.$emit('addDetail', list)
      this.handleClose()
    },
    handleCurrentChange(page) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, page}
      this.loadData()
    },
    handleSizeChange(pageSize) {
      this.queryParam.pageBean = {...this.queryParam.pageBean, pageSize}
      this.loadData()
    },
    selectAll(arr) {
      // 是否全选
      if (arr.length !== 0) {
        // 全选
        arr.forEach((item) => {
          const bool = this.selectUsers.some((user) => user.id === item.id) // 存在返回true 否则返回false
          if (!bool) {
            // 不存在添加
            this.selectUsers.push(item)
          }
        })
      } else {
        // 取消全选
        this.tableData.forEach((item) => {
          this.selectUsers = this.selectUsers.filter(
            (user) => user.id !== item.id
          )
        })
      }
    },
    handleSelectionChange(arr, row) {
      // 选择
      const bool = this.selectUsers.some((user) => user.id === row.id) // 存在返回true 否则返回false
      if (bool) {
        // 存在删除
        this.selectUsers = this.selectUsers.filter((user) => user.id !== row.id)
      } else {
        // 添加
        this.selectUsers.push(row)
      }
    },
    deleteUser(node) {
      // 移除
      this.selectUsers = this.selectUsers.filter((user) => user.id !== node.id)
      this.tableData.forEach((item) => {
        if (node.id === item.id) {
          // 存在添加
          this.$refs.multipleTable.toggleRowSelection(item, false)
        }
      })
    },
    echoSelected() {
      // 回显选中
      if (this.selectUsers.length > 0) {
        this.$nextTick(() => {
          this.tableData.forEach((item) => {
            if (this.selectUsers.some((user) => user.id === item.id)) {
              // 存在添加
              this.$refs.multipleTable.toggleRowSelection(item)
            }
          })
        })
      }
    },
  },
}
</script>

<style scoped
  lang="scss">
</style>
