<template>
  <basic-container>
    <div class="avue-crud" v-loading="details.loadingObj.pageLoading">
      <!-- 搜索模块 -->
      <div v-h5uShow="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search">
          <el-form-item label="搜索模式">
            <el-radio-group v-model="details.searchType" class="ml-4">
              <el-radio label="orderCode">订单号</el-radio>
              <el-radio label="carsNo">车次号</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="details.searchType === 'orderCode' ? '订单号' : '车次号'">
            <el-input
              v-model="query.incomingCode"
              :placeholder="`请输入${details.searchType === 'orderCode' ? '订单号' : '车次号'}`"
              clearable
            ></el-input>
          </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>
        </el-form>
      </div>

      <!-- 控件模块 -->
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="Van" @click="handleBatchPutInStorage"
              >批量入库</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>
      </el-row>

      <!-- 表格 -->
      <tablecmt
        ref="tableNodeRef"
        :columnList="details.columnList"
        :tableData="renderData"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @selectCheck="selectsc"
        @selection="selectionChange"
        :isselectfun="handleIsSelect"
      >
        <template #default="slotProps">
          <template v-if="slotProps.scope.column.label === '操作'">
            <el-text
              v-if="Number(slotProps.scope.row.isIncoming) === 1"
              @click="handlePutInStorage(slotProps.scope)"
            >
              入库
            </el-text>
            <el-text @click="handleGoDetails(slotProps.scope)">包明细</el-text>
          </template>
        </template>
      </tablecmt>

      <!-- 分页模块 -->
      <el-row class="el-fy">
        <div class="avue-crud__pagination flex-c-sb" style="width: 100%">
          <div style="font-size: 14px">勾选数量: {{ selectionList.length }}</div>
        </div>
      </el-row>
    </div>
  </basic-container>

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

<script setup lang="ts">
import { ref, reactive, toRefs, computed, shallowRef, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions.js';

import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import {
  postFindIncomingOrderList,
  postIncomingBatchOrder,
} from '@/api/distribution/WarehousingByTrainNumber';
import {
  setNodeHeight,
  deepClone,
  handleTranslationDataSeclect,
  handleFilterData,
  handleInputQuery,
  handleSelectQuery,
  handleTimeQuery,
} from '@/utils/util';
import { columnList } from '@/option/waybill/WarehousingByTrainNumber';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

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

// 表格实例
const tableNodeRef = ref();

const details = reactive<any>({
  /** 搜索模式 */
  searchType: 'orderCode',
  /** 是否开启搜索 */
  search: false,
  query: {},
  /** 表格搜索条件 -- 输入框 */
  inputQuery: {},
  /** 表格搜索条件 -- 下拉框 */
  selectQuery: {},
  /** 表格搜索条件 -- 时间选择 */
  timeQuery: {},
  /** 时间快捷选择设置 */
  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: deepClone(columnList),
  /** 包明细数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    pageLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    currentPage: 1,
    pageSize: 30,
    total: 0,
  },
  /** 包明细分页参数 */
  packageListPage: {
    currentPage: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {},
  /** 全屏 */
  fullscreenObj: {},
  /** 列表Dom节点 */
  listNode: '',
  form: {},
});
/** 渲染数据 */
const renderData = shallowRef([]);

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

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

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

    // 获取暂存单列表
    const submitData = {
      ...details.query,
      ...params,
    };

    // 按订单是5, 车次是4
    submitData.incomingType = details.searchType === 'orderCode' ? 5 : 4;

    const res = await postFindIncomingOrderList(submitData);

    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data;

    handleTranslationDataSeclect(details.data, details.columnList);
    handleFilterData(details.data, renderData, {
      inputQuery: details.inputQuery,
      selectQuery: details.selectQuery,
      timeQuery: details.timeQuery,
    });

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

/** 搜索 */
const searchChange = () => {
  if (!details.searchType) return ElMessage.error('请选择搜索模式');
  if (!details.query.incomingCode) return ElMessage.error('请输入搜索内容');
  for (let i = 0; i < details.columnList.length; i++) {
    details.columnList[i].values = '';
  }
  details.timeQuery = {};
  details.inputQuery = {};
  details.selectQuery = {};

  onLoad();
};

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.data = [];
  for (let i = 0; i < details.columnList.length; i++) {
    details.columnList[i].values = '';
  }
};

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

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

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

/** 表格表头输入框搜索 */
const inputsc = (index, col) => {
  handleInputQuery(index, col, details.inputQuery, true);

  handleFilterData(details.data, renderData, {
    inputQuery: details.inputQuery,
    selectQuery: details.selectQuery,
    timeQuery: details.timeQuery,
  });
};

/** 表格表头时间选择 */
const timesc = (index, col) => {
  handleTimeQuery(index, col, details.timeQuery);

  handleFilterData(details.data, renderData, {
    inputQuery: details.inputQuery,
    selectQuery: details.selectQuery,
    timeQuery: details.timeQuery,
  });
};

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

  handleFilterData(details.data, renderData, {
    inputQuery: details.inputQuery,
    selectQuery: details.selectQuery,
    timeQuery: details.timeQuery,
  });
};

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

/**
 * 设置列表 -- 固定函数
 * 弹窗的勾选回调，用于更改头部数组
 * 固定搭配，只需要更换   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 handlePutInStorage = ({ row }) => {
  ElMessageBox.confirm('确认批量入库吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        details.loadingObj.pageLoading = true;

        const res = await postIncomingBatchOrder({
          advanceIds: [row.id],
          incomingType: details.searchType === 'orderCode' ? 5 : 4,
        });

        const { code, msg } = res.data;
        if (code !== 200) return;
        ElMessage.success(msg);
        onLoad();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        details.loadingObj.pageLoading = false;
      }
    })
    .catch(() => {});
};

/** 批量入库 */
const handleBatchPutInStorage = () => {
  if (!details.selectionList.length) return ElMessage.error('请选择需要入库的数据');

  ElMessageBox.confirm('确认批量入库吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        details.loadingObj.pageLoading = true;

        const res = await postIncomingBatchOrder({
          advanceIds: details.selectionList.map(val => val.id),
          incomingType: details.searchType === 'orderCode' ? 5 : 4,
        });

        const { code, msg } = res.data;
        if (code !== 200) return;
        ElMessage.success(msg);
        onLoad();
      } catch (error) {
        console.log('error :>> ', error);
      } finally {
        details.loadingObj.pageLoading = false;
      }
    })
    .catch(() => {});
};

/** 详情 */
const handleGoDetails = ({ row }) => {
  $router.push({
    path: '/waybill/orderPackageListDetails?name=包明细',
    query: {
      id: row.id,
      name: `订单 -- ${row.orderCode} 包明细`,
    },
  });
};

const handleIsSelect = val => {
  if (Number(val.isIncoming) === 1) {
    return true;
  } else {
    return false;
  }
};
</script>

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

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

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

// 统计行
.statistics_row {
  margin: 10px 0;
  font-size: 14px;
  zoom: 0.9;
  display: flex;

  > div {
    margin-right: 20px;
  }
}
</style>
