<template>
  <MOSTY.PageTree :pageTitle="'车辆信息管理列表'" :searchType="'03'" :carInfo="true" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
    </template>
    <template #table>
      <el-divider />
      <section class="button">
        <el-button @click="toAdd">
          <el-icon size="small">
            <!-- v-if="(ssdept.ssdwid == listQuery.orgid) || (ssdept.ssdwid + 'XN' == listQuery.orgid)" -->
            <CirclePlus />
          </el-icon>
          新增
        </el-button>
        <el-button type="primary" @click="export2Excel" v-loading="loadingShow">
          <el-icon>
            <Download />
          </el-icon>
          <span>导出</span>
        </el-button>
      </section>
      <section class="eltab3">
        <MOSTY.Table :table-columns="data.tableColumn" :tableData="data.tableData" :tableloading="tableloading"
          :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false" actionsW="300">
          <template #sign="{ row }">
            <p style=" width: 12px; height: 12px;border-radius: 50%;margin: 0 auto"
              :style="{ 'background-color': row?.sign ? '#33CC00' : '#FC5F76' }"></p>
          </template>
          <template #useStatus="{ row }">
            <span style="color:green" v-if="row.useStatus === '1'">在用</span>
            <span style="color:orange" v-else-if="row.useStatus === '2'">闲置</span>
            <span style="color:red" v-else-if="row.useStatus === '3'">报废</span>
            <span v-else>-</span>
          </template>
          <template #actions="{ row }">
            <!-- v-if="row.orgid == ssdept.ssdwid" -->
            <span class="operecopy" @click="copyInfo(row)" size="small">
              <el-icon>
                <CopyDocument />
              </el-icon>复制</span>
            <span class="operedit" @click="xiugai(row)" size="small">
              <el-icon>
                <EditPen />
              </el-icon>修改</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="del(row)">
              <!-- v-if="ssdept.ssdwid == row.orgid" -->
              <template #reference>
                <span span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="edit(row)" size="small">
              <el-icon>
                <View />
              </el-icon>查看</span>
            <span class="operedown" @click="danbtn(row)" size="small">
              <el-icon>
                <FolderOpened />
              </el-icon>档案</span>
          </template>
        </MOSTY.Table>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="listQuery" @changeNo="changeNo" @changeSize="changeSize"></MOSTY.Pages>
        </div>
      </section>
    </template>
  </MOSTY.PageTree>
  <el-dialog v-model="shownewwb" :title="'车辆信息填报'" width="600px" :before-close="closeaddwb">
    <div>
      <el-form class="mosty-from-wrap" ref="FormRef" label-width="130px" :model="carInfoCopy" :inline="true"
        :rules="rules2" style='display:flex;justify-content:space-between;flex-wrap:wrap;width:500px;'>
        <el-form-item label="车牌号:" prop="carnumber">
          <el-input v-model="carInfoCopy.carnumber" placeholder="请输入车牌号" style="width: 250px"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="savewbobj(FormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>保存</el-button>
        <el-button @click="closeaddwb"><el-icon>
            <DocumentDelete />
          </el-icon>关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import * as MOSTY from "@/components/MyComponents/index"
import { exportXlsx } from "@/excel/Export2Excel.js"
import { ElMessage } from "element-plus"
import { reactive, ref, onMounted, getCurrentInstance } from "vue"
import { getItem } from "@/utils/storage"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import { singleObjectCheck, haveIntersection } from "@/utils/tools.js"
const { proxy } = getCurrentInstance();

const emit = defineEmits("changePage")
const tableloading = ref(false)
const loadingShow = ref(false)
// 树的展开与折叠
const iconChange = ref(true)
// 公共属性
const commonMark = ["carnumber", "cartype", "zcqs", "environmental", "purchasedate", "auto", "runDate", "useterm", "managedeptname"]
// 新能源
const newEnergyLabeling = ["displacement", "environmentalStandards", "assetOwnership", "purchasingDate"]
// 载货
const activeMark = ["zhlx", ...commonMark]
// 载客
const guestMark = ["zklx", ...commonMark]

const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  total: 0
})
const ssdept = getItem("deptId")
const searchArr = reactive([
  {
    showType: "input",
    prop: "carnumber",
    width: "250px",
    placeholder: "请输入车牌号"
  }
])
const data = reactive({
  searchObj: {},
  tableData: [],
  tableColumn: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      slot: true
    },
    {
      title: "车牌号",
      prop: "carnumber"
    },
    {
      title: "所属部门",
      prop: "managedeptname"
    },
    {
      title: "车辆厂牌",
      prop: "label"
    },
    {
      title: "车架号",
      prop: "vin"
    },
    {
      title: "发动机号",
      prop: "enginenum"
    },
    {
      title: "购置金额",
      prop: "gzje"
    },
    {
      title: "车辆使用状态",
      prop: "useStatus",
      slot: true
    },
    {
      title: "当年累计行驶里程",
      prop: "mileage"
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ]

})
// 初始化
onMounted(() => {

})

//获取部门数据
const getdeptId = (val) => {
  listQuery.orgid = val.id
  listQuery.pageCurrent = 1
  getTableData()
}
// 车辆复制信息
const carInfoCopy = reactive({
  tbSafeList: [],
  tbGoodsList: [],
  tbYearlyList: [],
  tbCarChangeList: [],
  tbMaintainList: [],
  tbScrapList: [],
  tbMoveList: [],
  tbMileageList: [],
  tbFuelDrainList: [],
  tbTireDrainList: [],
  auto: "",
  useterm: 0,
  carnumber: "",
  cartype: "",
  zklx: "",
  zcqs: "",
  environmental: "",
  purchasedate: "",
  jumpDate: "",
  runDate: "",
  managedeptname: "",
  managedeptid: "",
  picture: null,
  signfile: null,
  operatefile: null,
  photocopyId: null,
  photocopy2Id: null
})
const shownewwb = ref(false)
const FormRef = ref()
const rules2 = reactive({
  carnumber: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
})
const copyInfo = (row) => {
  carInfoCopy.auto = row.auto
  carInfoCopy.useterm = row.useterm
  carInfoCopy.carnumber = ''
  carInfoCopy.cartype = row.cartype
  carInfoCopy.environmental = row.environmental
  carInfoCopy.purchasedate = row.purchasedate
  carInfoCopy.runDate = row.runDate
  carInfoCopy.managedeptname = row.managedeptname
  carInfoCopy.managedeptid = row.managedeptid
  carInfoCopy.zklx = row.zklx
  carInfoCopy.zcqs = row.zcqs
  shownewwb.value = true
}
const savewbobj = async (FormRef) => {
  if (!FormRef) return;
  await FormRef.validate((valid) => {
    if (valid) {
      postApi(carInfoCopy, "/mosty-jcgl/car/addCarMsgOne").then(
        (res) => {
          ElMessage.success("新增成功");
          shownewwb.value = false;
          getTableData()
        }
      );
    }
  })
}
const closeaddwb = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      shownewwb.value = false;
      wbobj.value = {};
    })
    .catch(() => {
      // catch error
    })
};
function getTableData() {
  tableloading.value = true
  postApi(listQuery, "/mosty-jcgl/car/queryCarMsg").then(async (res) => {
    if (res.records) {
      tableloading.value = false
      let table_Data = []
      // 载客
      let guest_mark = ["11", "12", "13"]
      // 载货
      let active_mark = ["21", "22", "23"]
      for (let i = 0; i < res.records.length; i++) {
        // 载客非新能源
        if (haveIntersection(guest_mark, [res.records[i]["cartype"]]) && (res.records[i].environmental === "0" || res.records[i].environmental === null)) {
          table_Data.push(await singleObjectCheck(res.records[i], guestMark))
          continue
        }
        // 载客新能源
        if (haveIntersection(guest_mark, [res.records[i]["cartype"]]) && (res.records[i].environmental === "1" || res.records[i].environmental === null)) {
          table_Data.push(await singleObjectCheck(res.records[i], [...newEnergyLabeling, ...guestMark]))
          continue
        }
        // 载货新能源
        if (haveIntersection(active_mark, [res.records[i]["cartype"]]) && (res.records[i].environmental === "1" || res.records[i].environmental === null)) {
          table_Data.push(await singleObjectCheck(res.records[i], [...newEnergyLabeling, ...activeMark]))
          continue
        }
        // 载货非新能源
        if (haveIntersection(active_mark, [res.records[i]["cartype"]]) && (res.records[i].environmental === "0" || res.records[i].environmental === null)) {
          table_Data.push(await singleObjectCheck(res.records[i], [...activeMark]))
          continue
        }
        table_Data.push(await singleObjectCheck(res.records[i], commonMark))
      }
      data.tableData = table_Data.map(item => {
        return {
          ...item,
          mileage: item.mileage ? parseInt(item.mileage) : ''
        }
      })
      listQuery.total = res.total
      console.log("列表数据")
    } else {
      data.tableData = []
      tableloading.value = false
    }
  }).finally(() => {
    tableloading.value = false
  })
}

//获取详情
function gtdataxq(id, title, saveBtn) {
  getApi({ id: id }, `/mosty-jcgl/car/queryCarMsgDetail`).then((res) => {
    let obj = {
      title, //表单标题
      saveBtn, //是否展示保存按钮
      row: res //列表内容
    }
    emit("changePage", "Details", obj)
  })
}

//
//详情
const edit = (row) => {
  gtdataxq(row.id, "车辆信息详情", false)
}
//修改
const xiugai = (row) => {
  gtdataxq(row.id, "车辆信息修改", true)
}
//删除
const del = (val) => {
  postApi({}, `/mosty-jcgl/car/deleteCarMsgOne/${val.id}`).then((res) => {
    ElMessage.success("删除成功")
    getTableData()
  })
}
const toAdd = () => {
  let obj = {
    title: "车辆信息新增", //表单标题
    saveBtn: true, //是否展示保存按钮
    row: null //列表内容
  }
  emit("changePage", "Details", obj)
}
const changeNo = (val) => {
  listQuery.pageCurrent = val
  getTableData()
}
const changeSize = (val) => {
  listQuery.pageSize = val
  getTableData()
}
// 查询数据
const onSearch = (obj) => {
  listQuery.carnumber = obj.carnumber
  getTableData()
}

//查看档案
function danbtn(row) {
  let arr = {
    title: "车辆档案详情",
    saveBtnShow: false,
    wbjlShow: true,
    jcrzShow: true,
    id: row.id ? row.id : null
  }
  emit("changePage", "danDetails", arr)
}

//导出表格
const export2Excel = () => {
  loadingShow.value = true
  let title = {
    carnumber: "车牌号",
    managedeptname: "所属部门",
    label: "车辆厂牌",
    vin: "车架号",
    enginenum: "发动机号",
    gzje: "购置金额",
    mileage: "行驶里程"

  }
  const param = {
    pageCurrent: 1,
    pageSize: 10000,
    orgid: listQuery.orgid
  }
  postApi(param, "/mosty-jcgl/car/queryCarMsg").then((res) => {
    if (res.records) {
      let data = res.records
      if (data.length > 0) {
        let tablename = "车辆信息管理列表.xlsx"
        exportXlsx(title, data, "车辆信息管理列表", tablename)
      } else {
        ElMessage.warning("暂无数据")
      }
    }
  }).finally(() => {
    loadingShow.value = false
  })
}
</script>

<style lang="scss" scoped>
.eltab3 {
  height: calc(100vh - 380px - 34px);
}

.button {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-bottom: 12px;
}
</style>
