<template>
  <div>
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <div class="bigBoxs">
          <!--  -->
          <div class="left">
            <div class="title">变动记录</div>
            <div class="tabBox">
              <el-table ref="multipleTableRef" v-loading="tableloading" stripe :data="tableData" row-style="height:32px"
                style="width: 100%;height: 100%;" @selection-change="handleSelectionChange" border>
                <el-table-column label="车牌号" show-overflow-tooltip property="carNumber"></el-table-column>
                <el-table-column label="开始时间 " show-overflow-tooltip prop="startDate">
                </el-table-column>
                <el-table-column label="结束时间 " show-overflow-tooltip prop="endDate">
                </el-table-column>
                <el-table-column label="状态" show-overflow-tooltip prop="status">
                  <template #default="{ row }">
                    <span v-if="row.endDate">已解绑</span>
                    <span style="color: green" v-else>绑定中</span>
                  </template>
                </el-table-column>
                <el-table-column label="变动原因" show-overflow-tooltip property="reason"></el-table-column>
                <el-table-column label="操作" v-if="isAdmin">
                  <template #default="{ row }">
                    <div v-if="!row.endDate">
                      <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要解绑?"
                        @confirm="unBindByCarRelevance(row.id)">
                        <template #reference>
                          <span class="operesee">
                            <el-button>解绑</el-button>
                          </span>
                        </template>
                      </el-popconfirm>
                    </div>
                    <div v-else>
                      <span>已解绑</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="fenye">
                <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                  :current-page="listQuery.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.pageSize"
                  layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
              </div>
            </div>
          </div>
          <div class="right">
            <!-- 头部 -->
            <!-- 表格 -->
            <div class="box_cont" style="margin-top: 25px">
              <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="FromData" :inline="false"
                :rules="rules">
                <el-row>
                  <el-col :span="24" v-if="props.title == '绑定'">
                    <el-form-item label="绑定车辆牌号:" prop="nobindcarnumber">
                      <el-select v-model="FromData.nobindcarnumber" style="width: 500px" @change="changenonumber"
                        clearable>
                        <el-option v-for="item in nobindcarlist" :key="item" :label="item.carnumber" :value="item.id" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24" v-if="props.title == '解绑'">
                    <el-form-item label="解绑车辆牌号:" prop="bindcarnumber">
                      <el-select v-model="FromData.bindcarnumber" style="width: 500px" @change="changenumber" clearable>
                        <el-option v-for="item in bindcarlist" :key="item" :label="item.carnumber" :value="item.id" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="变动原因:" prop="reason">
                      <el-input v-model="FromData.reason" style="width: 500px" type="textarea" clearable
                        maxlength="200" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>

            </div>
          </div>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="CloseEvent">
            关闭
          </el-button>
          <el-button @click="submit(ruleFormRef)">
            保存
          </el-button>
        </span>
      </template>
    </MOSTY.FromPage>


  </div>
</template>

<script setup>
// 引入
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  watchEffect,
  getCurrentInstance
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["close"]);
// 数据
const { D_TB_DRIVELEVEL, D_BZ_XB, D_BZ_AQRYZZMM } =
  proxy.$dict("D_TB_DRIVELEVEL", "D_BZ_XB", "D_BZ_AQRYZZMM");
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  binddingobj: {
    type: Object,
    default: () => { }
  },
  offbinddingobj: {
    type: Object,
    default: () => { }
  }
});
const data = ref({})
//规则校验
const rules = reactive({
  nobindcarnumber: [{ required: true, message: "绑定车辆牌号不能为空", trigger: "blur" }],
  bindcarnumber: [{ required: true, message: "解绑车辆牌号不能为空", trigger: "blur" }],
  reason: [{ trigger: "blur", required: true, message: "变动原因不能为空" }],
});
const FromData = ref({});
watchEffect(() => {
  if (props.editObj) {
  }
});
onMounted(() => { });
const ruleFormRef = ref();
const CloseEvent = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits("close");
    })
    .catch(() => {
      // catch error
    })

};
const tableData = ref([]);
const total = ref(0);
//获取数据
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  driverId: ""
});
const tableloading = ref(false);
function getListData() {
  if (props.binddingobj) {
    listQuery.driverId = props.binddingobj.id;
  }
  if (props.offbinddingobj) {
    listQuery.driverId = props.offbinddingobj.id;
  }
  tableloading.value = true;
  getApi(listQuery, `/mosty-jcgl/driver/getCarRelevancePage`).then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      total.value = res.total;
    } else {
      tableData.value = [];
      tableloading.value = false;
    }
  });
}
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  getListData();
};
onMounted(() => {
  getListData();
  getbindcar();
  getoffbindcar();
});
const bindcarlist = ref([]);
//获取驾驶员已绑定车辆
function getbindcar() {
  if (props.title == "解绑") {
    if (props.offbinddingobj.id) {
      getApi(
        { driverId: props.offbinddingobj.id },
        `/mosty-jcgl/driver/getCarBand`
      ).then((res) => {
        bindcarlist.value = res;
      });
    }
  }
}
const bindcarnumber = ref();
function changenumber(val) {
  FromData.value.carId = val;
}
const nobindcarlist = ref();
//获取单位未绑定车辆
function getoffbindcar() {
  if (props.title == "绑定") {
    if (props.binddingobj.id) {
      getApi(
        { driverId: props.binddingobj.id },
        `/mosty-jcgl/driver/getCarNoBand`
      ).then((res) => {
        nobindcarlist.value = res;
      });
    }
  }
}
const nobindcarnumber = ref();
function changenonumber(val) {
  FromData.value.carId = val;
}
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (FromData.value) {

        if (props.title == "绑定") {
          FromData.value.drivermsgId = props.binddingobj.id
          postApi(FromData.value, "/mosty-jcgl/driver/bind")
            .then((res) => {
              ElMessage.success("绑定成功");
              emits("close");
            })

        }
        if (props.title == "解绑") {
          FromData.value.drivermsgId = props.offbinddingobj.id
          postApi(FromData.value, "/mosty-jcgl/driver/unbind")
            .then((res) => {
              ElMessage.success("解绑成功");
              emits("close");
            })

        }
      }
    } else {
      ElMessage.error("表单验证失败，请检查输入内容");
    }
  });
};

const isAdmin = ref(getItem('USERID') == '000000')

const unBindByCarRelevance = (id) => {
  getApi({ id: id }, `/mosty-jcgl/driver/unBindByCarRelevance`).then(() => {
    ElMessage.success("解绑成功！");
  })
}
</script>

<style lang="scss" scoped>
.bigBoxs {
  display: flex;

  .left {
    background-color: #fff;
    width: 49%;

    .title {
      color: black;
      height: 40px;
      font-size: 25px;
      text-align: center;
    }
  }

  .right {
    width: 49%;
    margin-left: 1%;

    .box_cont {
      margin-top: 40px;
    }

    .searchBox {
      width: 800px;
      margin: 20px auto;
    }
  }
}

.tabBox {
  height: calc(100vh - 390px);
}
</style>
