<template>
  <basic-container>
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <el-row v-if="search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="el-fr-d">
          <div class="fo-fl">
            <el-form-item label="车次号:">
              <el-input
                v-model="query.serviceNumber"
                placeholder="请输入车次号"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="预计发车:" class="el-times">
              <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
              <el-date-picker
                v-model="stockupDate"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                clearable
              />
            </el-form-item>
            <el-form-item label="实际发车:" class="el-times">
              <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
              <el-date-picker
                v-model="stockupDate"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                clearable
              />
            </el-form-item>
            <el-form-item label="到车时间:" class="el-times">
              <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
              <el-date-picker
                v-model="stockupDate"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                clearable
              />
            </el-form-item>
          </div>
          <div class="fo-fl">
            <el-form-item label="创建时间:" class="el-times">
              <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
              <el-date-picker
                v-model="stockupDate"
                type="daterange"
                unlink-panels
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                clearable
              />
            </el-form-item>
            <!-- 查询按钮 -->
            <el-form-item class="el-btn">
              <el-button type="primary" icon="el-icon-search" @click="searchChange"
                >搜 索</el-button
              >
              <el-button icon="el-icon-delete" @click="searchReset()">清 空</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-row>

      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="el-icon-van" @click="searchChange">发车 </el-button>
            <el-button type="primary" icon="el-icon-close" @click="searchReset()"
              >网点取消发车</el-button
            >
            <el-button type="primary" icon="el-icon-printer" @click="searchReset()"
              >装载清单</el-button
            >
            <el-button type="primary" icon="el-icon-printer" @click="handleArrive">到达</el-button>
            <el-button type="primary" icon="el-icon-printer" @click="handleCloseArrive"
              >取消到达</el-button
            >
            <el-button type="primary" icon="el-icon-delete" @click="searchReset()">
              中途到达卸车
            </el-button>
            <el-button
              type="primary"
              icon="el-icon-delete"
              @click="handleShowComparativeStatement()"
            >
              对比报表
            </el-button>
            <el-button type="primary" icon="el-icon-document" @click="searchReset()">
              终点到达卸车
            </el-button>
            <el-button type="primary" icon="el-icon-document" @click="searchReset()">
              卸车报告
            </el-button>
            <el-button type="primary" icon="el-icon-document" @click="searchReset()">
              欧派TIMS数据关联
            </el-button>
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
            <el-button icon="Operation" @click="showdrawer(true)" circle></el-button>
            <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
          </div>
        </div>
      </el-row>

      <!-- 表格 -->
      <el-row>
        <!-- 列表模块 -->
        <tablecmt
          :columnList="details.columnList"
          :tableData="data"
          :loading="loadingObj.list"
          @inputTxt="inputsc"
          @timeCheck="timesc"
          @btnCheck="btnsc"
          @selectCheck="selectsc"
          @selection="selectionChange"
        >
          <template #default="slotProps">
            <template v-if="slotProps.scope.column.label === '批次号'">
              <el-text>{{ slotProps.scope.row.carsNo }}</el-text>
            </template>

            <template v-if="slotProps.scope.column.label === '路线'">
              <span
                v-for="(item, index) in slotProps.scope.row.carsLoadLineList"
                :key="item"
                class="flex-c-c carsLineName"
              >
                <el-tooltip placement="top" effect="dark">
                  <template #content>
                    <div>
                      <span class="mr-10">网点:</span>
                      <span>{{ item.nodeName }}</span>
                    </div>
                    <div>
                      <span class="mr-10">运单总件数:</span>
                      <span>{{ item.nodeName }}</span>
                    </div>
                    <div>
                      <span class="mr-10">实际装车件数:</span>
                      <span>{{ item.nodeName }}</span>
                    </div>
                    <div>
                      <span class="mr-10">操作人:</span>
                      <span>{{ item.nodeName }}</span>
                    </div>
                    <div>
                      <span class="mr-10">状态:</span>
                      <span>{{ item.nodeName }}</span>
                    </div>
                  </template>
                  <el-text style="margin: 0 !important">{{ item.nodeName }}</el-text>
                </el-tooltip>
                <!-- <el-text @click="handleGoWaybill(slotProps.scope)">
                {{ item.nodeName }}
              </el-text> -->
                <el-icon class="ml" v-if="index !== slotProps.scope.row.carsLoadLineList.length - 1"
                  ><Right
                /></el-icon>
              </span>
            </template>

            <template v-if="slotProps.scope.column.label === '操作'">
              <el-text @click="handleShowTruckLoadingDetails(slotProps.scope)">装车明细</el-text>
              <el-button
                type="text"
                :disabled="
                  Mydata.id !== slotProps.scope.row.nowWarehouseId ||
                  Number(slotProps.scope.row.loadStatus) === 40
                "
                @click="handleEditStowage(slotProps.scope)"
                >编辑</el-button
              >
            </template>
          </template>
        </tablecmt>
      </el-row>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div style="font-size: 14px">勾选数量: {{ selectionList.length }}</div>
          <!-- 分页模块 -->
          <el-pagination
            align="right"
            background
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page.pageNum"
            :page-sizes="[30, 50, 80, 120]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </el-row>
    </div>
  </basic-container>

  <!-- 装车详情弹窗 -->
  <el-dialog
    title="装车明细"
    v-model="details.popUpShow.truckLoadingDetailVisited"
    width="80%"
    :before-close="beforeClose"
    append-to-body
    class="truckLoadingDetailPopUp"
  >
    <el-form :inline="true" :model="query" class="el-fr-d">
      <div class="fo-fl">
        <el-form-item label="预计发车:" class="el-times">
          <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
          <el-date-picker
            v-model="stockupDate"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            clearable
          />
        </el-form-item>
        <el-form-item label="实际发车:" class="el-times">
          <!--            <el-input v-model="query.stockupArea" placeholder="请输入备货区"></el-input>-->
          <el-date-picker
            v-model="stockupDate"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-van" @click="searchChange">批量卸车</el-button>
          <el-button type="primary" icon="el-icon-search" @click="searchReset()">搜 索</el-button>
          <el-button icon="el-icon-printer" @click="searchReset()">二维码</el-button>
        </el-form-item>
      </div>
    </el-form>
    <tablecmt
      :columnList="details.detailsColumnList"
      :tableData="data"
      :loading="loadingObj.list"
      @inputTxt="inputsc"
      @timeCheck="timesc"
      @btnCheck="btnsc"
      @selectCheck="selectsc"
      @selection="selectionChange"
    >
      <template #default="slotProps"> </template>
    </tablecmt>

    <!-- 分页模块 -->
    <el-pagination
      align="right"
      background
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page="trickleLoadingPage.pageNum"
      :page-sizes="[30, 50, 80, 120]"
      :page-size="trickleLoadingPage.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="trickleLoadingPage.total"
    >
    </el-pagination>

    <!-- 表单按钮 -->
    <!--     <template #footer>
      <div v-if="!view" class="dialog-footer">
        <el-button type="primary" icon="el-icon-circle-check" @click="handleEditSubmit"
          >提 交</el-button
        >
        <el-button icon="el-icon-circle-close" @click="box = false">取 消</el-button>
      </div>
    </template> -->
  </el-dialog>

  <!-- 列表配置显示 -->
  <edittablehead
    @setcolum="setnewcolum"
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="columnList"
  ></edittablehead>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { downloadXls } from '@/utils/util';
import { columnList, detailsColumnList } from '@/option/distribution/VehicleArrivalManagement';
import {
  postloadArriveCarsPageList,
  postloadArriveCarByLoadId,
  postloadCancelArriveCarByLoadId,
} from '@/api/distribution/VehicleArrivalManagement';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

// 获取路由实例
const $router = useRouter();

const Mydata = ref<any>({});

Mydata.value = JSON.parse(localStorage.getItem('my_data')); //获取本地仓库信息

const details = reactive({
  /** 是否开启搜索 */
  search: false,
  /** 表格搜索条件 */
  query: {},
  /** 时间快捷选择设置 */
  shortcuts: [
    {
      text: '最近一周',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      },
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      },
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      },
    },
  ],
  /** 时间选择器数据 */
  stockupDate: [],
  /** 列表 */
  columnList,
  detailsColumnList,
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 装车明细分页参数 */
  trickleLoadingPage: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 列表Dom节点 */
  listNode: '',
  /** 弹出层显示 */
  popUpShow: {
    /** 装车详情 */
    truckLoadingDetailVisited: false,
  },
  /** 弹出层表单 */
  form: {},
  /** 是否为查看模式 */
  view: false,
});

const {
  search,
  query,
  shortcuts,
  stockupDate,
  data,
  loadingObj,
  selectionList,
  drawerShow,
  page,
  trickleLoadingPage,
} = toRefs(details);

/** vuex */
const permission = computed(() => mapGetters(['permission', 'tagWel', 'tagList']));
console.log('permission :>> ', permission);

onMounted(() => {
  const timer = setTimeout(() => {
    details.listNode = document.querySelector('.maboxhi') as any;
    details.listNode.style.transition = 'all .5s ease-out';
    console.log('details.listNode :>> ', details.listNode);
    clearTimeout(timer);
  }, 100);
});

/** 请求页面数据 */
const onLoad = async (params = {}) => {
  try {
    // 开启loading
    details.loadingObj.list = true;

    // 请求页面数据
    const res = await postloadArriveCarsPageList(details.page, { ...details.query, ...params });
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
};

onLoad(details.page);

/** 搜索 */
const searchChange = () => {
  onLoad(details.page);
};

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.stockupDate = [];
  details.page.pageNum = 1;
  onLoad(details.page);
};

/** 展开列表控件 */
const showdrawer = (_flag?: boolean) => {
  details.drawerShow = _flag;
};

/** 获取可视区高度 */
function getWinHight() {
  var windowHight = 0;
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    windowHight =
      document.body.clientHeight < document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight;
  } else {
  }
  return document.documentElement.clientHeight;
}

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;
  const timer = setTimeout(() => {
    details.listNode.style.height =
      getWinHight() - details.listNode.getBoundingClientRect().top - 70 + 'px';
    clearTimeout(timer);
  }, 10);
};

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  onLoad(details.page);
};

/** 表格表头时间选择 */
const timesc = (index, row) => {
  console.log(index, row);
  if (!!index) {
    index = dayjs(index).format('YYYY-MM-DD');
  }
  details.query[row.prop] = index;
  if (!index) {
    delete details.query[row.prop];
  }
  onLoad(details.page);
};

/** 表格表头输入框搜索 */
const btnsc = () => {};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index) delete details.query[row.prop];
  if (row.prop === 'certificateTypeName') {
    details.query['certificateType'] = index;
    if (!index) delete details.query['certificateType'];
  }
  onLoad(details.page);
};

/** 表格表头复选框选择 */
const selectionChange = (list: any) => {
  details.selectionList = list;
};

/** 每页数量改变执行的回调 */
const sizeChange = (pageSize: number) => {
  details.page.pageSize = pageSize;
  onLoad(details.page);
};

/** 页码改变执行的回调 */
const currentChange = () => {};

/**
 * 设置列表 -- 固定函数
 * 弹窗的勾选回调，用于更改头部数组
 * 固定搭配，只需要更换   columnList
 *  */
const setnewcolum = (newarr, headarr, type) => {
  if (type == 1) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'checkList', headarr);
  } else if (type == 2) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'flexList', headarr);
  } else if (type == 3) {
    details.columnList = newarr;
    functions.setStorage(window.location.pathname + 'sortlist', headarr);
  }
};

/** 弹出层开启前清除数据 */
const beforeClose = done => {
  done();
  details.form = {};
  details.view = false;
};

/** 显示装车详情 */
const handleShowTruckLoadingDetails = ({ row }) => {
  $router.push({
    path: '/distribution/artery/truckLoadingDetails',
    query: {
      loadId: row.id,
      name: row.carsNo + '--' + '装车明细',
    },
  });

  // details.popUpShow.truckLoadingDetailVisited = true;

  // nextTick(() => {
  //   // 获取弹窗内表格元素节点, 并设置高度
  //   const _node = document.querySelector('.truckLoadingDetailPopUp .maboxhi');
  //   _node.style.height = '550px';
  // });
};

/** 显示对比报表 */
const handleShowComparativeStatement = () => {
  $router.push('/waybill/ComparativeStatement');
};

/** 到车 */
const handleArrive = async () => {
  console.log(
    'details.selectionList.map(val => val.id) :>> ',
    details.selectionList.map(val => val.id)
  );
  const submitData = {
    loadId: details.selectionList.map(val => val.id).join(','),
    ...details.form,
  };

  const res = await postloadArriveCarByLoadId(submitData);
  const { code } = res.data;
  if (code !== 200) {
    return;
  }
  ElMessage({
    type: 'success',
    message: '到达成功',
  });

  onLoad();
};

/** 取消到车 */
const handleCloseArrive = async () => {
  console.log(
    'details.selectionList.map(val => val.id) :>> ',
    details.selectionList.map(val => val.id)
  );
  const submitData = {
    loadId: details.selectionList.map(val => val.id).join(','),
    ...details.form,
  };

  const res = await postloadCancelArriveCarByLoadId(submitData);
  const { code } = res.data;
  if (code !== 200) {
    return;
  }
  ElMessage({
    type: 'success',
    message: '取消成功',
  });

  onLoad();
};

/** 编辑配载信息 */
const handleEditStowage = ({ row }) => {
  $router.push({
    path: '/distribution/artery/AddVehicleStowage',
    query: { name: '编辑配载', type: 2, loadId: row.id },
  });
};
</script>

<style scoped lang="scss">
.fo-fl {
  display: flex;
}

// 日期选择器
:deep(.el-date-editor.el-input) {
  height: 100% !important;
  width: 100% !important;
}

:deep(.el-range-editor.el-input__wrapper) {
  height: 100% !important;
}

.ml {
  margin: 5px;
  color: var(--el-color-primary);
}
</style>
