<template>
  <el-dialog :title="props.title" width="95%" v-model="dialogVisible" @close="onClose">
    <div class="flex just-between">
      <div>
        <el-form ref="formRef" label-width="110px" label-align="left" :model="querySelect" label-suffix=":"
          style="display: flex; flex-wrap: wrap">
          <el-form-item label="项目名称" prop="uimsProName">
            <div style="width: 180px">
              <el-input v-model="querySelect.uimsProName" type="text" style="width: 180px"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="施工状态" prop="ecpBuildStatusCode">
            <div style="width: 180px">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_XMSGZT" v-model="querySelect.ecpBuildStatusCode"
                :disabledItem="['1']" selectType="select" />
            </div>
          </el-form-item>
          <el-form-item label="上报状态" prop="status">
            <el-select v-model="querySelect.status" style="width: 180px" @change="changeStatus">
              <el-option label="全部" value="" />
              <el-option label="已上报" value="1" />
              <el-option label="未上报" value="2" />
            </el-select>
            <el-button @click="searchs" class="ml10 mr10">
              <el-icon>
                <Search />
              </el-icon>搜索</el-button>
            <el-button @click="onRest" class="ml10">
              <el-icon>
                <Refresh />
              </el-icon>重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button @click="onAdd" class="mr10">新增</el-button>
        <el-button v-if="dataTable.length > 0 && props.rowItem.status == '2' && isAuth" @click="onStagingReport"
          :disabled="gDisabled">
          <el-icon>
            <Upload />
          </el-icon>暂存上报</el-button>
      </div>
    </div>

    <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="50vh"
      @selection-change="onSelectionChange" @select="handleCheckBox" @select-all="handleCheckBox">
      <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">
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row)">查看</el-link>
          <el-link type="primary" @click="onEdit(row)" :disabled="gDisabled"
            v-if="props.rowItem.status == '2' && isAuth">编辑</el-link>
          <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 class="flex just-center">
      <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="total"></el-pagination>
    </div>
  </el-dialog>
  <Detailcc @close="detailClose" :rowItem="rowItem" :title="dialogTitle" v-if="detailVisible" :detail="detail" />
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, nextTick, computed } from "vue"
import { Delete, Edit, Search, Share, Upload } from "@element-plus/icons-vue"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import * as MOSTY from "@/components/MyComponents/index"
import Detailcc from "./Detailcc.vue"
import { getItem } from "@/utils/storage"
import { ElMessage } from "element-plus"
import { filterqx } from "@/utils/auth.js"

const { proxy } = getCurrentInstance()
const { D_BZ_XMSGZT } = proxy.$dict("D_BZ_XMSGZT")
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  // isProvinces: Boolean,
  params: Object,
  orgCode: String,
  reportStatus: String,
  rowItem: Object
})
const emits = defineEmits(["close"])
const dialogVisible = ref(true)
const detailVisible = ref(false)
const detail = ref(null)
const dialogTitle = ref("")
const formRef = ref()
const multipleTableRef = ref(null)
const columnTable = ref([
  { label: "企业名称", prop: "baOrgName" },
  { label: "所属单位/部门", prop: "orgName" },
  { label: "项目名称", prop: "uimsProName" },
  { label: "施工状态", prop: "ecProjBuildStatusName" },
  { label: "占地面积", prop: "totalLandArea" },
  { label: "建筑面积", prop: "totalBuildingArea" },
  { label: "总投资（万元）", prop: "proActualInvestmentAmount" },
])
//县级账号
const isTown = computed(() => {
  return filterqx("isaqbm") == "1" && filterqx("isgs") != "1" && filterqx("isSgs") != "1"
})
const isAuth = computed(() => {
  let code = props.orgCode
  return getItem("deptId").ssdwid == code.replace("XN", "")
})
const gDisabled = computed(() => {
  // return props.orgCode.includes("XN") || isTown.value ? false : true
  if (props.orgCode.includes("XN")) {
    return false
  } else if (isTown.value) {
    return props.rowItem.status === "2" ? false : true
  } else return true
})
const cklbList = ref([
  { label: "露天货场", value: "1" },
  { label: "洞库", value: "2" },
  { label: "单层仓库", value: "3" },
  { label: "多层仓库", value: "4" },
  { label: "立体仓库", value: "5" },
  { label: "停车场中转", value: "6" }
])
const total = ref(0)
const dataTable = ref([])
const querySelect = reactive({
  pageCurrent: 1,
  pageSize: 5,
  uimsProName: "",
  ecpBuildStatusCode: '',
  year: props.params.year,
  orgCode: props.orgCode,
  bn: props.params.bn,
  status: props.reportStatus || ''
})
const multipleSelection = ref([])
const currentCode = getItem("deptId").ssdwid
const pageData = reactive({
  ids: [],
  notReportIds: []
})
const handleCheckBox = (selection, row) => {
  if (row) {
    const index = pageData.ids.indexOf(row.sourceId)
    if (index === -1) {
      pageData.ids.push(row.sourceId)
      pageData.notReportIds.splice(pageData.notReportIds.indexOf(row.sourceId), 1)
    } else {
      pageData.notReportIds.push(row.sourceId)
      pageData.ids.splice(pageData.ids.indexOf(row.sourceId), 1)
    }
  } else {
    pageData.ids = selection.map(item => item.sourceId)
    pageData.notReportIds = dataTable.value.filter(item => !selection.some(s => s.sourceId === item.sourceId)).map(item => item.sourceId)
  }
  // if (row) {
  //   if (selection.indexOf(row) === -1) {
  //     // 取消勾选的操作
  //     if(pageData.ids.indexOf(row.sourceId) !== -1) {
  //       pageData.ids.splice(pageData.ids.indexOf(row.sourceId), 1)
  //     }
  //     pageData.notReportIds.push(row.sourceId)
  //   } else {
  //     if(pageData.notReportIds.indexOf(row.sourceId) !== -1) {
  //       pageData.notReportIds.splice(pageData.notReportIds.indexOf(row.sourceId), 1)
  //     }
  //     pageData.ids.push(row.sourceId)
  //   }
  // } else {
  //   if (selection.length) {
  //     selection.map(item => {
  //       pageData.ids.push(item.sourceId)
  //     })
  //     pageData.notReportIds = []
  //   } else {
  //     // 取消勾选的操作
  //     dataTable.value.map(item => {
  //       pageData.notReportIds.push(item.sourceId)
  //     })
  //     pageData.ids = []
  //   }
  // }
}
const tableLoading = ref(false)
onMounted(() => {
  // console.log('props: ', props);

  getDataList()
})

// 获取表格数据
const getDataList = () => {
  dataTable.value = []
  postApi(querySelect, "/mosty-jcgl/data/StsFileEscalation/queryStsFileEscalationData").then(res => {
    if (res) {
      dataTable.value = res.records
      nextTick(() => {
        dataTable.value.forEach(item => {
          if (item.status === "1") multipleTableRef.value.toggleRowSelection(item)
        })
      })

      tableLoading.value = false
      total.value = res.total
    }
  })
}
// 点击操作
const onView = data => {
  detail.value = data
  dialogTitle.value = `三同时管理详情`
  detailVisible.value = true
}
const onEdit = data => {
  detail.value = data
  dialogTitle.value = `三同时管理编辑`
  detailVisible.value = true
}
const onDelete = row => {
  postApi([row.id], "/mosty-jcgl/data/StsFileEscalation/delStsFileEscalation").then(res => {
    if (res) {
      ElMessage({
        message: "删除成功",
        type: "success"
      })
      getDataList()
    }
  })
}
// 选择锅炉类型
const onChangesblx = e => {
  getDataList()
}

const keyid = row => {
  return row.sourceId
}
//搜索
function searchs() {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 5
  total.value = 0
  getDataList()
}
const onAdd = () => {
  detail.value = {}
  dialogTitle.value = `三同时管理新增`
  detailVisible.value = true
}
// 重置
const onRest = () => {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 5
  querySelect.uimsProName = ""
  querySelect.ecpBuildStatusCode = ""
  querySelect.status = ""
  total.value = 0
  getDataList()
}
// 关闭弹窗
const onClose = () => {
  emits("close", true)
}
//关闭详情弹窗
const detailClose = val => {
  if (val) {
    getDataList()
  }
  detailVisible.value = false
}
// 切换条数
const handleSizeChange = val => {
  querySelect.pageSize = val
  getDataList()
}
// 切换分页
const handleCurrentChange = val => {
  querySelect.pageCurrent = val
  getDataList()
}
const onSelectionChange = val => {
  multipleSelection.value = val
}
const onStagingReport = () => {
  postApi({ ids: pageData.ids, notReportIds: pageData.notReportIds, ...props.params, orgCode: props.orgCode, status: querySelect.status }, "/mosty-jcgl/data/StsFileEscalation/stsFileReportData").then(res => {
    if (res) {
      ElMessage({
        message: "暂存上报数据成功",
        type: "success"
      })
      getDataList()
    }
  })
}
const changeStatus = e => {
  getDataList()
}
</script>

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

.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>
