<template>
  <el-dialog :title="props.title" width="95%" v-model="dialogVisible" @close="onClose">
    <el-form ref="formRef" label-width="130px" label-align="left" :model="querySelect" label-suffix=":"
      style="flex-wrap: wrap">
      <el-row>
        <el-col :span="5">
          <!-- <section class="mb12" style="display: flex;align-items: center;justify-content: space-between;">
          <section v-if="props.isSfsb">
            <el-button type="primary" :style="{'background':querySelect.type == '-1' ? '#67c23a' : ''}" @click="handleQuery('-1')">全部数据</el-button>
            <el-button type="primary" :style="{'background':querySelect.type == '1' ? '#67c23a' : ''}" style="margin: 0 6px;" @click="handleQuery('1')">已选择上报数据</el-button>
            <el-button type="primary" :style="{'background':querySelect.type == '2' ? '#67c23a' : ''}" @click="handleQuery('2')">已选择未上报数据</el-button>
          </section>
          <section v-else>
            <el-button type="primary" :style="{'background':querySelect.type == '-1' ? '#67c23a' : ''}" @click="handleQuery('-1')">全部数据</el-button>
            <el-button type="primary" :style="{'background':querySelect.type == '4' ? '#67c23a' : ''}" style="margin:0 6px;" @click="handleQuery('4')">暂存已选择数据</el-button>
            <el-button type="primary" :style="{'background':querySelect.type == '5' ? '#67c23a' : ''}" @click="handleQuery('5')">暂存未选择数据</el-button>
          </section>
        </section> -->
          <!-- </el-col>
        <el-col :span="5"> -->
          <el-form-item label="姓名" prop="name">
            <el-input v-model="querySelect.employeeName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="擅长领域" prop="value">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYSCLY" @onChange="handleScly"
              v-model="querySelect.areasExpertiseCode" selectType="select" :multiple="false" placeholder="请选择" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="上报状态" prop="status">
            <el-select v-model="querySelect.status" @change="changeStatus">
              <el-option label="全部" value="" />
              <el-option label="已上报" value="1" />
              <el-option label="未上报" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button style="margin-left: 10px;" type="primary" @click="onSearch">
            <el-icon>
              <Search />
            </el-icon>搜索
          </el-button>
          <el-button @click="onRest"><el-icon>
              <Refresh />
            </el-icon>重置</el-button>
        </el-col>
        <el-col :span="4">
          <span class="fr">
            <!-- <el-button type="primary" @click="handleCache" v-if="!props.isSfsb && props.isEdit && !props.isProvinces" :disabled="isShowBtn">暂存数据</el-button> -->
            <el-button type="primary" @click="onAdd">新增</el-button>
            <el-button @click="onStagingReport" :disabled="gDisabled">
              <el-icon>
                <Upload />
              </el-icon>暂存上报</el-button>
          </span>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-wrapper-content">
      <el-table ref="multipleTableRef" :row-key="keyid" border :data="dataTable"
        style="width: 100%; margin-bottom: 10px" v-loading="tableLoading" :header-cell-style="{ background: '#F6F6F6' }"
        height="100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" fixed />
        <el-table-column :prop="item.prop" :label="item.label" v-for="(item, index) in columnTable" :key="index">
          <template v-if="item.prop == 'safetyMemberFlag'" #default="{ row }">
            <span>{{ row.safetyMemberFlag === "1" ? "是" : "否" }}</span>
          </template>
          <template v-if="item.prop == 'seFlag'" #default="{ row }">
            <span>{{ row.seFlag === "1" ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <el-button type="link" @click="handleChange(row, 'view')">查看</el-button>
            <!-- :disabled="gDisabled" -->
            <el-button class="mr10" type="link" @click="handleChange(row, 'edit')">编辑</el-button>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="onDelete(row)">
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="querySelect.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="querySelect.pageSize"
      layout="total, prev, pager, next, sizes, jumper" :total="querySelect.total"></el-pagination>
  </el-dialog>
  <Detail :isEdit="isEdit" :isAdd="isAdd" @close="detailClose" :title="dialogTitle" :rowItem="rowItem"
    v-if="detailVisible" :detailId="detailId" />
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, computed, nextTick } from "vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index"
import { Delete, Edit, Search, Share, Upload } from "@element-plus/icons-vue"
import Detail from "./Detail.vue"
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
const { proxy } = getCurrentInstance()
const { D_BZ_AQRYSCLY } = proxy.$dict("D_BZ_AQRYSCLY")
import { filterqx } from "@/utils/auth.js"
import { filter, set } from "lodash"

const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  isEdit: {
    type: Boolean,
    default: true
  },
  isProvinces: Boolean,
  params: Object,
  orgCode: String,
  reportStatus: String,
  rowItem: Object
})
const emits = defineEmits(["close"])
const dialogVisible = ref(true)
const detailVisible = ref(false)
const detailId = ref("")
const dialogTitle = ref("")
const formRef = ref()
const multipleTableRef = ref(null)
const isShowBtn = ref(true)
const columnTable = ref([
  { label: "企业名称", prop: "baOrgName" },
  { label: "姓名", prop: "employeeName" },
  { label: "性别", prop: "sexName" },
  { label: "政治面貌", prop: "politicalAffiliation" },
  { label: "出生年月", prop: "birthDate" },
  { label: "岗位名称", prop: "postName" },
  { label: "职务", prop: "dutiesName" },
  { label: "最高专业技术资格名称", prop: "proQualifiedName" },
  { label: "擅长领域", prop: "areasExpertiseName" },
  { label: "累计从事专职安全管理年限", prop: "safetyManageYear" },
  { label: "注册安全工程师级别", prop: "cseLevelName" },
  { label: "注册消防工程师级别", prop: "fireEngineerLevelName" },
  { label: "是否为安技委成员", prop: "safetyMemberFlag" },
  { label: "是否评聘为安全工程师", prop: "seFlag" }
])
const dataTable = ref([])
const isEdit = ref(true)
const isAdd = ref(false)
const querySelect = reactive({
  employeeName: "",
  pageCurrent: 1,
  pageSize: 5,
  total: 0,
  areasExpertiseCode: "",
  // type: "-1",
  status: props.reportStatus
})
const pageData = reactive({
  ids: []
})
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const currentCode = getItem("deptId").ssdwid

const gDisabled = computed(() => {
  return props.rowItem.status === "2" && props.orgCode.includes(currentCode) ? false : true
})
const typeList = {
  sb: [
    {
      label: "已上报数据",
      value: "1"
    },
    {
      label: "未上报数据",
      value: "2"
    }
  ],
  zc: [
    {
      label: "暂存已选数据",
      value: "4"
    },
    {
      label: "暂存未选数据",
      value: "5"
    }
  ]
}

const tableLoading = ref(false)
const multipleSelection = ref([])
const reportSore = ref([])
const reportChange = reactive({
  notReportIds: [],
  ids: []
})

// 点击操作
const handleChange = (data, type) => {
  isEdit.value = type == "view" ? false : true
  isAdd.value = false
  detailId.value = data.sourceId
  dialogTitle.value = `${type == "view" ? "查看" : "编辑"}安全管理队伍（${data.baOrgName}）`
  detailVisible.value = true
}
const onDelete = row => {
  postApi([row.sourceId], "/mosty-jcgl/data/safeManageTeam/delSafeManageTeam").then(res => {
    if (res) {
      ElMessage({
        message: "删除成功",
        type: "success"
      })
      getDataList()
    }
  })
}
// 选择领域
const handleScly = e => {
  querySelect.areasExpertiseCode = e
  getDataList()
}
//表格选择
const onTableChange = val => {
  isShowBtn.value = val.length >= 1 ? false : true
  pageData.ids = val
}
const onSelectionChange = val => {
  multipleSelection.value = val
}
const sorgeIds = () => {
  multipleSelection.value.forEach(item => {
    if (!reportChange.ids.includes(item.sourceId)) reportChange.ids.push(item.sourceId)
  })
  reportChange.notReportIds = reportSore.value.filter(item => !reportChange.ids.includes(item))
}
// 点击缓存数据
const onStagingReport = () => {
  sorgeIds()
  postApi({ ...reportChange, ...props.params, orgCode: props.orgCode }, "/mosty-jcgl/data/safeManageTeam/stagingReportData")
    .then(res => {
      if (res) {
        ElMessage({
          message: "暂存上报数据成功",
          type: "success"
        })
        onRest()
      }
    })
    .finally(() => {
      reportChange.ids = []
      reportChange.notReportIds = []
    })
}
const keyid = row => {
  return row.sourceId
}
//回显示  需要给出row-key相同的数据
const toggleSelection = rows => {
  if (rows) {
    rows.forEach(row => {
      if (row.status == "01") {
        multipleTableRef.value?.toggleRowSelection(row, true)
      } else {
        multipleTableRef.value?.clearSelection()
      }
    })
  } else {
    multipleTableRef.value?.clearSelection()
  }
}
const onAdd = () => {
  isAdd.value = true
  isEdit.value = false
  detailId.value = ""
  dialogTitle.value = `新增安全管理队伍`
  detailVisible.value = true
}
// 重置
const onRest = () => {
  querySelect.employeeName = ""
  querySelect.pageCurrent = 1
  querySelect.pageSize = 5
  querySelect.total = 0
  querySelect.status = ''
  querySelect.areasExpertiseCode = ""
  reportSore.value = []
  reportChange.ids = []
  reportChange.notReportIds = []
  // querySelect.type = "-1"
  getDataList()
}
const onSearch = () => {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 5
  querySelect.total = 0
  getDataList()
}
// 关闭弹窗
const onClose = () => {
  emits("close")
}
//关闭详情弹窗
const detailClose = val => {
  if (val) {
    getDataList()
  }
  detailVisible.value = false
}
// 切换条数
const handleSizeChange = val => {
  querySelect.pageSize = val
  sorgeIds()
  getDataList()
}
// 切换分页
const handleCurrentChange = val => {
  querySelect.pageCurrent = val
  sorgeIds()
  getDataList()
}
// 根据条件查询
const handleQuery = _id => {
  // querySelect.type = _id
  getDataList()
}
// 获取表格数据
const getDataList = () => {
  tableLoading.value = true
  dataTable.value = []
  querySelect.orgCode = props.orgCode
  querySelect.jd = props.params.jd
  querySelect.year = props.params.year
  postApi(querySelect, "/mosty-jcgl/data/safeManageTeam/querySafeManageTeamData").then(res => {
    if (res) {
      dataTable.value = res.records
      tableLoading.value = false
      querySelect.total = res.total

      nextTick(() => {
        dataTable.value.forEach(item => {
          if (item.status === "1") {
            multipleTableRef.value.toggleRowSelection(item)
            if (!reportSore.value.includes(item.sourceId)) reportSore.value.push(item.sourceId)
            // if(!reportChange.ids.includes(item.sourceId)) reportChange.ids.push(item.sourceId)
          }
        })
      })
    }
  })
}
const changeStatus = e => {
  getDataList()
}

onMounted(() => {
  getDataList()
})
</script>

<style lang="scss" scoped>
::v-deep .el-link.el-link--primary.is-disabled {
  color: #808596;
  cursor: not-allowed;
}

::v-deep .el-button--link {
  border: none;
  background: none;
  color: var(--el-color-primary);
  padding: 0;
  margin-left: 10px !important;

  &:hover,
  &:focus {
    background: none;
    border: none;
    opacity: 0.9;
  }
}

::v-deep .el-button--link.is-disabled {
  color: #808596;
  border: none;
  background: none;
}

.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
