<template>
  <basic-container>
    <div class="avue-crud">
      <!-- 搜索模块 -->
      <div v-h5uShow="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query" class="header_search" label-width="100px">
          <el-form-item label="运单号">
            <el-input v-model="query.waybillNo" placeholder="请输入运单号" clearable></el-input>
          </el-form-item>

          <el-form-item label="订单自编号">
            <el-input v-model="query.orderCode" placeholder="请输入运单号" clearable></el-input>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="details.timeQuery.createTimeArr"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
                      value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>

          <!-- 查询按钮 -->
          <el-form-item class="el-btn">
            <el-button type="primary" icon="el-icon-search" @click="handleFilterData">
              搜 索
            </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"></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="tableNode"
        :columnList="details.packageListColumnList"
        :tableData="details.renderData"
        :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 @click="handleShowPackageOrderList(slotProps.scope)"> 查看详情 </el-text>
            <!-- <el-button type="text" @click="handleShowFlowNode(slotProps.scope)">
              在库明细
            </el-button> -->
          </template>
        </template>
      </tablecmt>

      <div class="fz-0-9">勾选数量：{{ details.selectionList.length }}</div>
    </div>
  </basic-container>

  <!-- 打印二维码 -->
  <el-dialog
    class="el-dialog-QRCode"
    title="二维码"
    :visible.sync="details.popUpShow.QRCodeVisible"
    width="780px"
    v-model="details.popUpShow.QRCodeVisible"
  >
    <div>
      <div v-html="details.html"></div>
    </div>
    <span slot="footer" class="dialog-footer">
      <!--    <el-button type="primary" @click="ddd">导 出</el-button>-->
      <el-button type="primary" @click="printTemplate">打 印</el-button>
      <el-button @click="details.popUpShow.QRCodeVisible = false">取 消</el-button>
    </span>
  </el-dialog>

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

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick } from 'vue';
import functions from '@/utils/functions.js';
import dayjs from 'dayjs';
import { mapGetters } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { postFindListByWaybillId } from '@/api/waybill/orderDetails';
import {
  downloadXls,
  setNodeHeight,
  getHtmls,
  handleClearTableQuery,
  debounce,
  deepClone,
} from '@/utils/util';
import { packageListColumnList } from '@/option/waybill/orderDetails';
import { useRouter, useRoute } from 'vue-router';
import print from '@/utils/print';
import { ElMessage, ElMessageBox } from 'element-plus';

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

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

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  /** 表格搜索条件 */
  query: {},
  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: [],
  /** 数据 */
  data: [],
  renderData: [],
  /** 包明细表头 */
  packageListColumnList: deepClone(packageListColumnList),
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 包明细分页参数 */
  packageListPage: {
    currentPage: 1,
    pageSize: 30,
    total: 0,
  },
  /** 弹出层显示 */
  popUpShow: {
    /** 二维码 */
    QRCodeVisible: false,
  },
  /** 全屏 */
  fullscreenObj: {},
  /** 列表Dom节点 */
  listNode: '',
  form: {},
  html: '',
});

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

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

onMounted(async () => {
  await nextTick();
  setNodeHeight(tableNode.value.$el, '');
});

/** 请求页面数据 */
const onLoad = async () => {
  details.loadingObj.list = true;
  try {
    // 获取暂存单列表
    const response = await postFindListByWaybillId({ waybillId: $route.query.id });
    const { code, data } = response.data;
    if (code !== 200) return;

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

onLoad();

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

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.timeQuery = {};
  details.stockupDate = [];
  handleClearTableQuery(details.packageListColumnList);
  handleFilterData();
  // onLoad();
};

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

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

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

const handleFilterData = debounce(() => {
  let _filterArr = [];

  const _regArr = {};

  for (const key in details.query) {
    const value = details.query[key];

    if (value) _regArr[key] = new RegExp('^' + value);
  }

  if (Object.keys(_regArr).length === 0 && Object.keys(details.timeQuery).length === 0)
    return (details.renderData = details.data);

  for (let i = 0; i < details.data.length; i++) {
    const value = details.data[i];

    let _flag = true;
    for (let key in _regArr) {
      if (!_regArr[key].test(value[key])) _flag = false;
      if (!_flag) break;
    }

    if (!_flag) continue;

    for (let key in details.timeQuery) {
      const item = details.timeQuery[key];
      if (!item) continue;

      const _startTime = Date.parse(item[0]);
      const _endTime = Date.parse(item[1]) + 1000 * 60 * 60 * 24 - 1;

      const _time = Date.parse(value[key.replace('Arr', '')]);

      if (_time !== _time) _flag = false;
      else if (_time < _startTime || _time > _endTime) _flag = false;

      if (!_flag) break;
    }
    if (_flag) _filterArr.push(value);
  }

  details.renderData = _filterArr;
}, 10);

/** 表格表头输入框搜索 */
const inputsc = (index, row) => {
  details.query[row.prop] = index;
  if (!index && index !== 0) delete details.query[row.prop];

  handleFilterData();
};

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

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

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

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

/** 打印包条码 */
const printTemplate = () => {
  const orderNodeList = document.querySelectorAll('.el-dialog-QRCode .el-dialog__body>div>div>div');
  print(orderNodeList);
};

/** 查看包明细 */
const handleShowPackageOrderList = ({ row }) => {
  $router.push({
    path: '/waybill/orderPackageListDetails?name=包明细',
    query: {
      id: row.id,
      name: `订单 -- ${row.orderCode} 包明细`,
    },
  });
};
</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;
}

// 新增行
.add_row {
  display: flex;
  justify-content: space-between;
}

.add_row_title {
  text-align: center;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: bold;
}

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

  > div {
    margin-right: 20px;
  }
}

// 卡片容器
.crad_container {
  display: flex;

  .card_container_item {
    flex: 1;
    // padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 5px #ccc;

    &:first-child {
      margin-right: 20px;
    }

    .card_container_item_title {
      padding: 10px;
      border-bottom: 1px solid #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card_container_item_box {
      padding: 10px;
    }
  }
}
</style>
