<template>
  <basic-container v-loading="details.loadingObj.pageLoading">
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <template v-for="item in details.columnList" :key="item.prop">
            <el-form-item v-if="item.isTitleSearch" :label="item.label">
              <!-- 普通输入框 -->
              <template v-if="item.type === 2">
                <el-input
                  class="w100"
                  :placeholder="`请输入${item.label}`"
                  v-model="details.query[item.prop]"
                  clearable
                ></el-input>
              </template>

              <!-- 下拉框 -->
              <template v-else-if="item.type === 3">
                <el-select
                  v-model="details.query[item.prop.replace('Name', '')]"
                  :placeholder="`请选择${item.label}`"
                  class="w100"
                  clearable
                  filterable
                  :multiple="item.multiple || false"
                  @change="
                    val => {
                      !val && delete details.query[item.prop.replace('Name', '')];
                    }
                  "
                >
                  <el-option
                    v-for="val in item.checkarr"
                    :key="val.value"
                    :label="val.label"
                    :value="val.value"
                  />
                </el-select>
              </template>
            </el-form-item>
          </template>

          <!-- 查询按钮 -->
          <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>
        </el-form>
      </div>

      <!-- 控件模块 -->
      <div class="avue-crud__header">
        <!-- 头部左侧按钮模块 -->
        <div class="avue-crud__left">
          <!-- 导出 -->
          <el-button type="primary" icon="Download" @click="handleExport">导 出</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="Search" @click="searchHide" circle></el-button>
        </div>
      </div>

      <!-- 列表模块 -->
      <tablecmt
        ref="tableNodeRef"
        :columnList="details.columnList"
        :tableData="data"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @selectCheck="selectsc"
        @selection="selectionChange"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '操作'">
            <el-text @click="handleView(slotProps.scope)"> 查看配送详情 </el-text>
          </template>
        </template>
      </tablecmt>

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

  <!-- 上传 -->
  <MyUpload
    ref="myUpload"
    v-model="details.popUpShow.UploadPackageDelivery"
    templateSrc=""
    uploadAddress="/api/logpm-basicdata/vehicle/import-basicdataVehicle"
    isDefined
    :success="
      () => {
        details.popUpShow.UploadPackageDelivery = false;
        onLoad();
      }
    "
  >
    <!-- <el-button type="danger" icon="Download" @click="handleDownloadTemplate"> 下载模板 </el-button> -->
  </MyUpload>

  <!-- 列表配置显示 -->
  <edittablehead
    @closce="showdrawer"
    :drawerShow="drawerShow"
    v-model="details.columnList"
  ></edittablehead>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, getCurrentInstance } from 'vue';
import functions from '@/utils/functions.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  downloadXls,
  setNodeHeight,
  getHtmls,
  deepClone,
  handleClearTableQuery,
  debounce,
  handleSelectQuery,
  handleInputQuery,
  handleTranslationDataSeclect,
  getObjType,
} from '@/utils/util';
import columnList from '@/option/basicdata/BackStockTask.js';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { exportBlob } from '@/api/common';
import { dateNow } from '@/utils/date';
import { getNewPage } from '@/api/warehouse/warehouseRetentionRecord.js';
import { remove, getPage, getDictionary } from '@/api/basicdata/basicdataVehicle';

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

const $store = useStore();

const tableNodeRef = ref();

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  /** 表格搜索条件 */
  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];
      },
    },
  ],
  /** 列表 */
  columnList: deepClone(columnList),
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    /** 页面loading */
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    current: 1,
    size: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 图片预览 */
    abnormalVisited: false,
    /** 上传 */
    UploadPackageDelivery: false,
  },
  form: {},
  /** 全屏 */
  fullscreenObj: {
    /** 查看 */
    view: false,
  },
});

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

const instance = getCurrentInstance();

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

/** 请求页面数据 */
const onLoad = debounce(async () => {
  try {
    details.loadingObj.list = true;
    let _page = details.page;
    // 获取暂存单列表
    const res = await getNewPage({ ..._page, ...details.query });
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;

    handleTranslationDataSeclect(details.data, details.columnList);

    details.page.total = data.total;
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
}, 10);

const handleData = (key, res) => {
  const { code, data } = res.data;
  if (code !== 200) return;
  for (let i = 0; i < details.columnList.length; i++) {
    const value = details.columnList[i];

    if (value.label === key)
      return (value.checkarr =
        getObjType(data) === 'array'
          ? data.map(val => {
              val.label = val.dictValue;
              val.value = val.dictKey;
              return val;
            })
          : []);
  }
};

// 获取字典数据
const initData = async () => {
  try {
    details.loadingObj.pageLoading = true;

    await Promise.all([
      // 车辆来源
      getDictionaryBiz('basic_vehicle_source').then(res => handleData('车辆来源', res)),

      onLoad(false),
    ]);

    await nextTick();
    handleTranslationDataSeclect(details.data, details.columnList);
    console.log('details.columnList :>> ', details.columnList);
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.pageLoading = false;
  }
};

initData();

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

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.page.current = 1;
  handleClearTableQuery(details.columnList);
  onLoad();
};

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

/** 是否开启搜索区 */
const searchHide = () => {
  details.search = !details.search;

  setNodeHeight(tableNodeRef.value.$el, '', true);
};

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

/** 表格表头时间选择 */
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();
};

/** 表格表头下拉框选择 */
const selectsc = (index, row) => {
  handleSelectQuery(index, row, details.query);

  onLoad();
};

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

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

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

/** 查看 */
const handleView = ({ row }) => {
  $router.push({
    path: '/distribution/deliverylist/distributionDeliveryListedt',
    query: {
      id: row.deliveryId,
      name: row.trainNumber + '-查看配送',
    },
  });
};

/** 导出 */
const handleExport = () => {
  console.log('instance :>> ', instance);

  let downloadUrl = `/logpm-basicdata/vehicle/export-basicdataVehicle`;
  let submitData = {
    ids: '',
  };
  submitData.ids = details.selectionList.map(item => item.id).join(',') || '';
  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const res = await exportBlob(downloadUrl, submitData);
      const { status, data } = res;
      if (status !== 200) return;

      downloadXls(res.data, `车辆信息导出${dateNow()}.xlsx`);
    } catch (error) {
      console.log('error :>> ', error);
    } finally {
      details.loadingObj.pageLoading = false;
    }
  });
};
</script>

<style scoped lang="scss">
// 日期选择器
:deep(.el-date-editor.el-input) {
  height: 100% !important;
  width: 100% !important;
}

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

.mt20 {
  margin-top: 20px;
}

.fwb {
  font-weight: bold;
}
</style>
