<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" label-width="100px">
          <el-form-item label="品牌" prop="brandId">
            <el-select
              class="w100"
              v-model="query.brandList"
              filterable
              placeholder="请选择"
              default-first-option
              multiple
              clearable
            >
              <el-option
                v-for="item in details.brandOptions"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="导入时间">
            <el-date-picker
              v-model="query.timeArr"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              @change="
                () => {
                  delete details.query.year;
                  delete details.query.month;
                }
              "
            />
          </el-form-item>

          <el-form-item label="事业线">
            <el-select
              class="w100"
              v-model="query.businessLineList"
              filterable
              placeholder="请选择"
              default-first-option
              multiple
              clearable
            >
              <el-option
                v-for="item in details.businessLineOption"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="导入仓库">
            <el-select
              class="w100"
              v-model="query.warehouseIds"
              filterable
              placeholder="请选择"
              default-first-option
              multiple
              clearable
            >
              <el-option
                v-for="value in details.warehouseOption"
                :key="value.dictKey"
                :label="value.dictValue"
                :value="value.dictKey"
              />
            </el-select>
          </el-form-item>

          <!-- 查询按钮 -->
          <el-form-item>
            <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 flex-c-sb">
        <!-- 头部左侧按钮模块 -->
        <div class="avue-crud__left">
          <el-button type="primary" icon="Download" @click="ExportData"> 导出 </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="details.data"
        :loading="loadingObj.list"
        @inputTxt="inputsc"
        @timeCheck="timesc"
        @btnCheck="btnsc"
        @selectCheck="selectsc"
        @selection="selectionChange"
      >
        <template #default="{ scope: { row, column } }">
          <div>
            {{ row[column.property] + '%' }}
          </div>
        </template>
      </tablecmt>

      <!-- 分页模块 -->
      <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, 500]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>
  </basic-container>

  <edittablehead
    @closce="showdrawer"
    :drawerShow="drawerShow"
    :columnList="details.columnList"
    v-model="details.columnList"
  ></edittablehead>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, computed, onMounted, nextTick, defineAsyncComponent } from 'vue';
import functions from '@/utils/functions.js';
import dayjs from 'dayjs';
import { mapGetters, useStore } from 'vuex';
/** 获取字典 */
import { getDictionaryBiz } from '@/api/system/dict';
import { postFindBrandList } from '@/api/waybill/TemporaryStorageList';
import { postFindbusinessLine } from '@/api/reportforms/SalesDepartmentIncomeReport';
import {
  postOpenTimePage,
  postOpenTimeExport,
} from '@/api/reportforms/CreateOrderTimelinessRatioReport';
import { getListName } from '@/api/basicdata/basicdataVehicle';
import {
  setNodeHeight,
  getHtmls,
  deepClone,
  getObjType,
  handleTranslationDataSeclect,
  handleClearTableQuery,
  handleSelectQuery,
  handleInputQuery,
  downloadXls,
} from '@/utils/util';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { columnList } from '@/option/reportforms/CreateOrderTimelinessRatioReport';

// 获取路由实例
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: [],
  /** 头部搜索配置 */
  titleSearchOption: [],
  /** 流转节点数据 */
  flowNodeData: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    packageListLoading: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 是否显示设置表格 */
  drawerShow: false,
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  /** 品牌 */
  brandOptions: [],
  /** 事业线 */
  businessLineOption: [],
  /** 仓库 */
  warehouseOption: [],
  /** 弹出层显示 */
  popUpShow: {},
  /** 全屏 */
  fullscreenObj: {},
});

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

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

/** 权限按钮 */
const permissionObj = reactive({});

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

    const submitData = { ...details.page, ...details.query, ...params };

    for (const key in submitData) {
      const element = submitData[key];

      if (!element && element !== 0) delete submitData[key];
    }

    // 时间周期
    if (getObjType(submitData.timeArr) === 'array' && submitData.timeArr.length > 0) {
      submitData.startTimeStr = submitData.timeArr[0];
      submitData.endTimeStr = submitData.timeArr[1];
    }

    if (getObjType(submitData.timeArr) !== 'array' || submitData.timeArr.length === 0) {
      details.data = [];
      return ElMessage.warning('请选择时间');
    }

    delete submitData.timeArr;
    delete submitData.total;

    const res = await postOpenTimePage(submitData);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = getObjType(data.records) === 'array' ? data.records : [];
    details.page.total = data.total;

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

const init = () => {
  const time = new Date().getTime();

  details.query.timeArr = [
    dayjs(time - 1000 * 60 * 60 * 24 * 7).format('YYYY-MM-DD'),
    dayjs(time).format('YYYY-MM-DD'),
  ];

  onLoad();
};

init();

/** 查询品牌 */
const handleFindBrand = async () => {
  try {
    const res = await postFindBrandList();
    console.log('res :>> ', res);
    const { data, code } = res.data;
    if (code !== 200) return;
    console.log('data :>> ', data);
    details.brandOptions = data || [];
  } catch (error) {
    console.log('error :>> ', error);
  }
};

/** 初始化请求仓库数据 */
getListName({ name: '' }).then(res => {
  const { code, data } = res.data;
  if (code !== 200 || getObjType(data) !== 'array') return;
  details.warehouseOption = data.map(val => {
    return {
      dictKey: val.id,
      dictValue: val.name,
    };
  });
});

/** 查询事业线 */
const handleFindbusinessLine = async () => {
  try {
    const res = await postFindbusinessLine();
    console.log('res :>> ', res);
    const { data, code } = res.data;
    if (code !== 200) return;
    console.log('data :>> ', data);
    details.businessLineOption = data || [];
  } catch (error) {
    console.log('error :>> ', error);
  }
};
handleFindbusinessLine();

handleFindBrand();

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

/** 清空表单 */
const searchReset = () => {
  details.query = {};
  details.page.pageNum = 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 btnsc = () => {};

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

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

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

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

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

// 导出
const ExportData = async () => {
  try {
    details.loadingObj.list = true;

    const submitData = { ...details.page, ...details.query };

    for (const key in submitData) {
      const element = submitData[key];

      if (!element && element !== 0) delete submitData[key];
    }

    // 月
    if (submitData.month) {
      const _arr = submitData.month.split('-');
      submitData.year = _arr[0];
      submitData.month = _arr[1];
    }

    // 时间周期
    else if (getObjType(submitData.timeArr) === 'array' && submitData.timeArr.length > 0) {
      submitData.startTimeStr = submitData.timeArr[0];
      submitData.endTimeStr = submitData.timeArr[1];
    }

    if (
      (getObjType(submitData.timeArr) !== 'array' || submitData.timeArr.length === 0) &&
      !submitData.year &&
      !submitData.month
    ) {
      return ElMessage.warning('请选择时间');
    }

    delete submitData.timeArr;
    delete submitData.total;

    const res = await postOpenTimeExport(submitData);
    const { status, data } = res;
    if (status !== 200) return;
    const time = new Date().getTime();
    downloadXls(data, '开单及时率报表 -' + time + '.xlsx');
  } catch (error) {
    console.log('error :>> ', error);
  } finally {
    details.loadingObj.list = false;
  }
};
</script>

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

:deep(.el-form-item__content) {
  height: fit-content;
}
.el_div_input {
  width: 100%;
  display: flex;
  align-items: center;
  .el_dy_icon {
    font-size: 1.5em;
  }
}
</style>
