<template>
  <MOSTY.PageTree :pageTitle="'驾驶员信息管理列表'" :searchType="'03'" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" isEnterSubmit @submit="onSearch" />
    </template>
    <template #table>
      <el-divider />
      <section class="button">
        <el-button type="primary" @click="exportExcel" :loading="exportLoading">
          导出
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <CirclePlus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </section>
      <section :style="{ height: totalHeight }">
        <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="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 #sex="{ row }">
            <dict-tag v-if="row.sex" :options="D_BZ_XB" :value="row.sex" :tag="false" />
            <span v-else>-</span>
          </template>
          <template #carNumberArr="{ row }">
            <div style="display: flex;justify-content: center;flex-wrap: wrap;gap:3px">
              <el-tag type="info" v-for="item in row.carNumberArr">{{ item }}</el-tag>
            </div>
          </template>
          <template #drivelevel="{ row }">
            <span v-if="row.drivelevel" style="display: flex;justify-content: space-around;">
              <dict-tag v-for="value in row.drivelevel.split(',')" :options="D_TB_DRIVELEVEL" :value="value"
                :tag="false" />
            </span>
            <span v-else>-</span>
          </template>
          <template #driverState="{ row }">
            <span>{{ row.driverState === '1' ? '正常' : row.driverState === '2' ? '审验过期' : row.driverState === '3' ? '停职'
              : row.driverState === '4' ? '离职' : '-'
            }}</span>
          </template>
          <template #empnature="{ row }">
            <dict-tag v-if="row.empnature" :options="D_TB_EMPNATURE" :value="row.empnature" :tag="false" />
            <span v-else>-</span>
          </template>
          <template #actions="{ row }">
            <span class="operedit" @click="handleput(row)">
              <!-- v-if="row.deptcode == ssdept.ssbmid" -->
              <el-icon>
                <EditPen />
              </el-icon>修改</span>
            <!--
            "-->
            <span class="operesee" @click="handleoffbind(row)" v-if="row.countcar > '0'">
              <!-- row.deptcode == ssdept.ssbmid && -->
              <el-icon>
                <Compass />
              </el-icon>解绑</span>
            <!-- v-if=" row.deptcode==ssdept.ssbmid" -->
            <!-- v-if="row.countcar == '0'" -->
            <span class="operesee" @click="handlebind(row)"><el-icon>
                <!-- row.deptcode == ssdept.ssbmid &&  -->
                <Compass />
              </el-icon>绑定</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="changdelete(row)">
              <!-- v-if="row.deptcode == ssdept.ssbmid" -->
              <template #reference>
                <span span class="operdel" size="small">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除</span>
              </template>
            </el-popconfirm>
            <span class="operesee" @click="handlesee(row)">
              <el-icon>
                <View />
              </el-icon>查看</span>
          </template>
        </MOSTY.Table>
      </section>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
          @changeSize="handleSizeChange">
        </MOSTY.Pages>
      </div>
    </template>
  </MOSTY.PageTree>
  <div v-if="addDiaShow" class="dialog-box">
    <addjsyxx @close="closeChange" :title="title" :obj="rowxq" :zdlist='zdlist' :BtnShow="saveBtnShow" />
  </div>
  <div v-if="bindingShow" class="dialog-box">
    <binding @close="closeChange2" :title="title" :binddingobj="binddingobj" :offbinddingobj="offbinddingobj" />
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, getCurrentInstance } from "vue";
import binding from "@/views/yxkzgl/jsygl/binding.vue";
import addjsyxx from "@/views/yxkzgl/jsygl/addjsyxx.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { getItem } from "@/utils/storage";
import { ElMessage } from "element-plus";
import { arrayFiltering, getValByDic } from "@/utils/tools.js"
import { exportXlsx } from "@/excel/Export2Excel.js";

const { proxy } = getCurrentInstance();
// 数据
const { D_BZ_XB, D_TB_DRIVELEVEL, D_TB_EMPNATURE, D_TB_DRIVERTYPE } = proxy.$dict(
  "D_BZ_XB",
  "D_TB_DRIVELEVEL",
  "D_TB_EMPNATURE",
  "D_TB_DRIVERTYPE",
);
const zdlist = ref({ D_BZ_XB, D_TB_DRIVELEVEL, D_TB_EMPNATURE })
const saveBtnShow = ref(true);
const ssdept = getItem("deptId");
const tableloading = ref(false);
const exportLoading = ref(false)
const totalHeight = ref()
const title = ref("");
const rowxq = ref(null);
/** 左侧选中的部门名称 */
const currOrgName = ref('')
let driversMark = ['drivername', 'driverfileno', 'sex', 'idcard', 'drivenumber', 'drivelevel', 'drivertype', 'empnature', 'initgetlicensedate']
//查询条件
const tableData = ref([]);
// 分页
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  drivername: ""
});
const addDiaShow = ref(false);
const searchArr = reactive([
  {
    showType: "input",
    prop: "drivername",
    width: '250px',
    placeholder: '请输入驾驶员名称进行查询'
  },
  {
    showType: "select",
    prop: "empnature",
    width: '250px',
    options: D_TB_EMPNATURE,
    placeholder: '请选择'
  }
])
const pageData = reactive({
  tableColumns: [
    {
      title: "标记",
      prop: "sign",
      sortable: false,
      width: 60,
      slot: true
    },
    {
      title: "驾驶员状态",
      prop: "driverState",
      slot: true
    },
    {
      title: "驾驶员姓名",
      prop: "drivername"
    },
    {
      title: "所属部门",
      prop: "deptname"
    },
    {
      title: "驾驶档案号",
      prop: "driverfileno"
    },
    {
      title: "性别",
      prop: "sex",
      width: 60,
      slot: true
    },
    // {
    //   title: "身份证号",
    //   prop: "idcard"
    // },
    {
      title: "驾驶级别",
      prop: "drivelevel",
      slot: true
    },
    {
      title: "职工类型",
      prop: "empnature",
      width: 130,
      slot: true
    },
    {
      title: "车辆数",
      prop: "countcar",
      width: 80,
    },
    {
      title: "驾驶车辆",
      prop: "carNumberArr",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
})
onMounted(() => {
  totalHeight.value = `calc(100vh - 380px)`
});
//选择右侧部门
const getdeptId = (val) => {
  currOrgName.value = val.orgname || ''
  listQuery.nameaffiliationid = val.id;
  listQuery.pageCurrent = 1;
  getTableData();
};
//查询
function onSearch(boj) {
  listQuery.pageCurrent = 1;
  listQuery.drivername = boj.drivername;
  listQuery.empnature = boj.empnature;

  getTableData();
}
// 获取表格数据
const getTableData = () => {
  tableloading.value = true;
  postApi(listQuery, "/mosty-jcgl/driver/queryDriver").then(async (res) => {
    tableloading.value = false;
    if (res.records) {
      tableData.value = await arrayFiltering(res.records, driversMark);
      tableData.value = tableData.value.map(item => {
        return {
          ...item,
          carNumberArr: item.carNumber ? item.carNumber.split(',') : []
        }
      })
    }
    pageData.pageConfiger.total = res.total
  }).finally(() => {
    tableloading.value = false;
  });
};
//获取详情
function getRowxq(id) {
  getApi({ id }, "/mosty-jcgl/driver/queryDriverById").then((res) => {
    rowxq.value = res;
    addDiaShow.value = true;
  });
}
/** 获取车辆信息 */
const getCarById = (id) => {
  //查看 驾驶员对应的车辆信息
  return new Promise((resolve, reject) => {
    getApi({ driverId: id }, '/mosty-jcgl/driver/getCarRelevancePage').then((res) => {
      let tableData3 = []
      if (res.records?.length) {
        tableData3 = res.records.filter(item => { return item.xtScbz == '0' })
      }
      resolve(tableData3)

    }).catch(err => {
      reject(err)
    })
  })
};
/** 导出 */
function exportExcel() {
  // 姓名	性别	所属部门	驾驶级别
  // 	驾驶员类别	正式或聘用职工	车辆数	驾驶车辆
  //   出生日期	驾驶证号	初次领证时间	驾驶工龄
  let titleObj = {
    drivername: "姓名",
    sex: "性别",
    deptname: "所属部门",
    drivelevel: "驾驶级别",

    drivertype: '驾驶员类别',
    empnature: "职工类型",
    countcar: "车辆数",
    carNumber: "驾驶车辆",

    birth: "出生日期",
    drivenumber: "驾驶证号",
    initgetlicensedate: "初次领证时间",
    driveage: "驾驶工龄",
  };
  const params = {
    ...listQuery,
    pageSize: 1000000,
    pageCurrent: 1,
  }
  exportLoading.value = true;
  postApi(params, "/mosty-jcgl/driver/queryDriver").then(async (res) => {
    if (res?.records?.length) {
      let tableName = currOrgName.value + "驾驶员信息";
      const data = res.records.map(async item => {
        let sexObj = { 1: '男', 2: '女' }
        return {
          ...item,
          sex: sexObj[item.sex] || '',
          drivelevel: getValByDic(item.drivelevel, D_TB_DRIVELEVEL.value),
          empnature: getValByDic(item.empnature, D_TB_EMPNATURE.value),
          drivertype: getValByDic(item.drivertype, D_TB_DRIVERTYPE.value),
        }
      })
      exportLoading.value = true
      Promise.all(data).then(dataArr => {
        exportLoading.value = false
        exportXlsx(titleObj, dataArr, tableName, tableName + '.xlsx');
      })
    } else {
      ElMessage.warning('没有数据');
    }
  }).finally(() => {
    exportLoading.value = false;
  });
}
//新增
function handleAdd() {
  tableloading.value = false;
  rowxq.value = null;
  saveBtnShow.value = true;
  title.value = "驾驶员信息新增";
  addDiaShow.value = true;
}
//查看
function handlesee(row) {
  title.value = "驾驶员信息详情";
  saveBtnShow.value = false;
  getRowxq(row.id);
}
//修改
function handleput(row) {
  title.value = "驾驶员信息修改";
  saveBtnShow.value = true;
  getRowxq(row.id);
}
//删除
function changdelete(row) {
  postApi({}, `/mosty-jcgl/driver/deleteDriverOne/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
}
const binddingobj = ref()
const offbinddingobj = ref()
const bindingShow = ref(false)
//绑定
function handlebind(row) {
  binddingobj.value = row
  title.value = "绑定";
  bindingShow.value = true;
}
//解绑
function handleoffbind(row) {
  offbinddingobj.value = row
  title.value = "解绑";
  bindingShow.value = true;
}
function closeChange2() {
  bindingShow.value = false;
  binddingobj.value = null
  offbinddingobj.value = null
  getTableData();
}
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val;
  pageData.pageConfiger.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.pageSize = val;
  pageData.pageConfiger.pageSize = val;
  getTableData();
};

function closeChange() {
  addDiaShow.value = false;
  getTableData();
}
</script>

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