<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="cdCarNo">
            <div style="width: 180px">
              <el-input v-model="querySelect.cdCarNo" clearable />
            </div>
          </el-form-item>
          <el-form-item label="车辆类型" prop="cdMotorCarTypeCode">
            <div style="width: 180px">
              <MOSTY.DictTree :zdbh="'D_TB_CLLX'" @onChange="onChangesblx" placeholder="请选择车辆类型" style="width: 180px;"
                clearable filterable v-model="querySelect.cdMotorCarTypeCode" />
            </div>
          </el-form-item>
          <el-form-item label="车辆使用状态" prop="cdMotorCarUseStateCode">
            <div style="width: 180px">
              <el-select v-model="querySelect.cdMotorCarUseStateCode" style="width: 180px" @change="changeStatus">
                <el-option label="在用" value="1" />
                <el-option label="已报废" value="2" />
              </el-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-form-item>
        </el-form>
      </div>
      <div class="top-button-right">
        <el-button @click="searchs" class="mr10">
          <el-icon>
            <Search />
          </el-icon>搜索</el-button>
        <el-button @click="onRest" class="mr10">
          <el-icon>
            <Refresh />
          </el-icon>重置</el-button>

        <el-button class="mr10" v-if="dataTable.length > 0 && props.rowItem.status == '2' && isAuth"
          @click="onStagingReport" :disabled="gDisabled">
          <el-icon>
            <Upload />
          </el-icon>暂存上报</el-button>
        <el-button @click="onAdd" class="mr10">新增</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">
        <template #default="{ row }" v-if="item.prop == 'cdMotorCarNewEnergyCarFlag'">
          <span>{{ row.cdMotorCarNewEnergyCarFlag == '1' ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onView(row)">查看</el-link>
          <!--  :disabled="gDisabled" -->
          <el-link type="primary" @click="onEdit(row)">编辑</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>
  <DetailJsy @close="detailClose" :title="dialogTitle" v-if="detailVisible" :detail="detail" :rowItem="props.rowItem" />
</template>

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

const { proxy } = getCurrentInstance()
const { D_TB_CLLX } = proxy.$dict("D_TB_CLLX");
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  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: 'orgName' },
  { label: '车牌号码', prop: 'cdCarNo' },
  { label: '资产权属', prop: 'cdMotorCarOwnershipName' },
  { label: '车辆类型', prop: 'cdMotorCarTypeName' },
  { label: '车辆用途', prop: 'cdMotorCarUsageName' },
  { label: '机动车辆新能源车标识', prop: 'cdMotorCarNewEnergyCarFlag' },
  { label: '车辆使用状态', prop: 'cdMotorCarUseStateName' },
  { label: '车辆安全智能化', prop: 'cdCarSafeIntelligentName' },
  { label: '采购时间', prop: 'cdMotorCarProcurementDate' },
  { label: '行驶里程', prop: 'cdMotorCarMileageTraveled' },
])
//县级账号
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(() => {
  if (props.orgCode.includes("XN")) {
    return false
  } else if (isTown.value) {
    return props.rowItem.status === "2" ? false : true
  } else return true
})
const total = ref(0)
const dataTable = ref([])
const querySelect = reactive({
  pageCurrent: 1,
  pageSize: 10,
  cdCarNo: "",
  cdMotorCarTypeCode: '',
  cdMotorCarUseStateCode: '',
  year: props.params.year,
  orgCode: props.orgCode,
  jd: props.params.jd,
  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)
  }
}
const tableLoading = ref(false)
onMounted(() => {
  getDataList()
})

// 获取表格数据
const getDataList = () => {
  dataTable.value = []
  pageData.ids = []
  let _sex = querySelect.bbEmpSexName
  postApi({ ...querySelect }, "/mosty-jcgl/data/Car/queryDriverData").then(res => {
    if (res) {
      dataTable.value = res.records
      nextTick(() => {
        dataTable.value.forEach(item => {
          if (item.status === "1") {
            multipleTableRef.value.toggleRowSelection(item)
            pageData.ids.push(item.sourceId)
          }
        })
      })

      tableLoading.value = false
      total.value = res.total
    }
  })
}
// 点击操作
const onView = data => {
  detail.value = data
  dialogTitle.value = `车辆管理详情`
  detailVisible.value = true
}
const onAdd = (data) => {
  detail.value = {}
  dialogTitle.value = `车辆管理新增`
  detailVisible.value = true
}
const onEdit = data => {
  detail.value = data
  dialogTitle.value = `车辆管理编辑`
  detailVisible.value = true
}
const onDelete = row => {
  postApi([row.sourceId], `/mosty-jcgl/data/Car/delCar`).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 = 10
  total.value = 0
  getDataList()
}
// 重置
const onRest = () => {
  querySelect.pageCurrent = 1
  querySelect.pageSize = 10
  querySelect.cdCarNo = ""
  querySelect.cdMotorCarTypeCode = ""
  querySelect.cdMotorCarUseStateCode = ""
  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/Car/stagingReportData").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;
}

.top-button-right {
  width: 345px;
  white-space: nowrap;
}

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