<template>
  <basic-container v-loading="details.loadingObj.pageLoading">
    <div class="avue-crud">
      <el-tabs type="border-card" v-model="details.pageStatus" @tab-click="handleClickTab">
        <!-- toB -->
        <el-tab-pane
          v-for="(item, index) in details.pageInfo"
            :name="item.name" :label="item.title">
          <!-- 搜索模块 -->
          <div v-h5uShow="!search">
            <!-- 查询模块 -->
            <el-form :inline="true" :model="item.query" class="header_search">
              <!-- 查询按钮 -->
              <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">
            <!-- 头部左侧按钮模块 -->
            <div class="avue-crud__left">
              <!-- 审核 -->
              <el-button type="primary" icon="Stamp" @click="handleConfirm">生成对账单</el-button>

              <!-- 导出 -->
              <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(item, true)" circle></el-button>
              <el-button icon="Search" @click="searchHide" circle></el-button>
            </div>
          </div>

          <!-- 表格 -->
          <tablecmt
            ref="tableNodeRef"
            :columnList="item.columnList"
            :tableData="details.data"
            :loading="details.loadingObj.list"
            @inputTxt="(val, col)=> inputsc(val, col, item)"
            @timeCheck="timesc"
            @selectCheck="(val, col)=> selectsc(val, col, item)"
            @selection="selectionChange"
          >
            <template #default="slotProps">
              <template v-if="slotProps.scope.column.label === '操作'">
                <el-text @click="() => handleComputedPrice(slotProps.scope)">计算费用</el-text>
              </template>
            </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]"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
            >
            </el-pagination>
          </div>
          <!-- 列表配置显示 -->
          <edittablehead
            @closce="(flag)=> showdrawer(item, flag)"
            :drawerShow="item.drawerShow"
            v-model="item.columnList"
          ></edittablehead>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        destroy-on-close
        :modal-append-to-body="false"
        :append-to-body="false"
        class="confirmVisited"
        width="80%"
        v-model="details.popUpShow.confirmVisited"
        :fullscreen="details.fullscreenObj.confirmVisited"
        :show-close="false"
        draggable
      >
        <!-- 标题 -- 头部控件区 -->
        <template #header="{ close, titleId, titleClass }">
          <div class="my-header flex-c-sb" draggable>
            <div class="fwb" :id="titleId" :class="titleClass">开标签</div>
            <div class="flex-c-c">
              <!-- 全屏显示按钮 -->
              <el-button
                type="text"
                @click="handleFullScrean('open', 'confirmVisited')"
                v-if="!details.fullscreenObj.confirmVisited"
              >
                <el-icon class=""><FullScreen /></el-icon>
              </el-button>

              <el-button type="text" @click="handleFullScrean('close', 'confirmVisited')" v-else>
                <el-icon class=""><CopyDocument /></el-icon>
              </el-button>

              <!-- 弹窗关闭按钮 -->
              <el-button type="text">
                <el-icon class="" @click="close"><Close /></el-icon>
              </el-button>
            </div>
          </div>
        </template>

        <tablecmt
          :columnList="details.confirmColumnList"
          :tableData="details.selectionList"
        >
        </tablecmt>

        <div class="flex-c-c dialog-footer">
          <el-button icon="Close" @click="details.popUpShow.confirmVisited = false">
            取 消
          </el-button>

          <!-- 提交 -->
          <el-button
            icon="Position"
            type="primary"
            :loading="details.loadingObj.addTagLoading"
            @click="handleSubmitConfrim"
          >
            提 交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </basic-container>

</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 { postPageList, postCheckBalance, postReal,postOrderInfoListExport } from '@/api/finance/ReconciliationDepositSlip';
import {
  downloadXls,
  setNodeHeight,
  getHtmls,
  handleClearTableQuery,
  handleInputQuery,
  handleSelectQuery,
  handleTranslationDataSeclect,
  getObjType
} from '@/utils/util';
import { columnListByToB, columnListByToC,confirmColumnList } from '@/option/finance/ReconciliationDepositSlip';
import { useRouter } from 'vue-router';
import { deepClone } from '@/utils/util';
import { ElMessage, ElMessageBox } from 'element-plus';

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

const details = reactive<any>({
  /** 是否开启搜索 */
  search: true,
  pageInfo: [
    {
      title: 'toB',
      columnList: deepClone(columnListByToB),
      query: {},
      name: 1
    },
    {
      title: 'toC',
      columnList: deepClone(columnListByToC),
      query: {},
      name: 2
    }
  ],
  /** 表格搜索条件 */
  /** 时间快捷选择设置 */
  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];
      },
    },
  ],
  /** 列表数据 */
  data: [],
  /** 页面loading */
  loadingObj: {
    /** 列表加载loading */
    list: false,
    pageLoading: false,
  },
  /** 全屏 */
  fullscreenObj: {
    /** 开标签 */
    confirmVisited: false,
  },
    /** 弹出层显示 */
  popUpShow: {
    /** 新增标签 */
    confirmVisited: false,
  },
  /** 列表复选框选中的数据 */
  selectionList: [],
  /** 生成对账单表头 */
  confirmColumnList: deepClone(confirmColumnList),
  /** 分页参数 */
  page: {
    pageNum: 1,
    pageSize: 30,
    total: 0,
  },
  form: {},
  /** 页面激活状态 : 1 -- toB; 2 -- toC */
  pageStatus: 1 as 1 | 2,
});

const tableNodeRef = ref();

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

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

onMounted(async () => {
  await nextTick();

  const node = details.pageStatus === 1 ? tableNodeRef.value[0].$el : tableNodeRef.value[1].$el;

  setNodeHeight(node, '', true);
});

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

    const {query, columnList}  = ( details.pageStatus  === 1 ?details.pageInfo[0]: details.pageInfo[1])

    const submitData = { query,  ...details.page };
    // listType 1 -- toB ; 2 -- toC
    submitData.listType = details.pageStatus;

    // 获取暂存单列表
    const res = await postPageList(submitData);
    console.log('res :>> ', res);
    const { code, data } = res.data;
    if (code !== 200) return;
    details.data = data.records;
    details.page.total = data.total;
    handleTranslationDataSeclect(
      details.data,
      columnList
    );

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

const initOnLoad = () => {
  details.page.pageNum = 1;
  details.page.total = 0;
  onLoad();
};

initOnLoad();

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

/** 清空表单 */
const searchReset = () => {
  // details.query = {};
  details.pageStatus === 1 ? (details.query1 = {}) : (details.query2 = {});
  details.page.pageNum = 1;
  handleClearTableQuery(details.pageStatus === 1 ? details.columnList1 : details.columnList2);
  initOnLoad();
};

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

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

  const node = details.pageStatus === 1 ? tableNodeRef.value[0].$el : tableNodeRef.value[1].$el;

  setNodeHeight(node, '', true);
};

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

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

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

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

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

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

const handleClickTab = async e => {
  console.log('e :>> ', e);

  await nextTick();

  const node = details.pageStatus === 1 ? tableNodeRef.value[0].$el : tableNodeRef.value[1].$el;

  setNodeHeight(node, '', true);
  console.log('details.pageStatus :>> ', details.pageStatus);
  initOnLoad();
};

/**
 * 是否开启全屏
 * @params(_type) 开启或关闭
 */
const handleFullScrean = (_type: 'open' | 'close', _name: string) => {
  let _node: any = '';
  if (_name) _node = document.querySelector(`.${_name} .maboxhi`);

  switch (_name) {
    case 'confirmVisited':
      details.fullscreenObj.confirmVisited =
        !details.fullscreenObj.confirmVisited;

      if (_type === 'close') {
        if (_node) setNodeHeight(_node, '500px', true);
      } else {
        if (_node) setNodeHeight(_node,'', true);
      }
      break;

    default:
      details.fullscreenObj[_name] = !details.fullscreenObj[_name];
      break;
  }
};

/** 生成对账单 */
const handleConfirm = async () => {
  if (details.selectionList.length === 0) return ElMessage.warning('请选择需要确认的数据');

  const _errorArr = [];
  const _arr = [];

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

    if (Number(value.confirmStatisticsOrder) === 1) _errorArr.push(value.orderNo);
    _arr.push(value.orderInfoId);
  }

  if (_errorArr.length > 0)
    return ElMessage.warning(`订单【 ${_errorArr.join('、')} 】-- 已确认，请勿重复确认`);

  details.popUpShow.confirmVisited =  true
  await nextTick()
  const _node = document.querySelector(`.confirmVisited .maboxhi`);
  setNodeHeight(_node, details.popUpShow.confirmVisited ?  '' : '500px', true);
};

const handleSubmitConfrim= ()=>{
  ElMessageBox.confirm('是否确认对账单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const submitData = {
        orderInfoIds: details.selectionList.map(val => val.orderInfoId),
      };

      const res = await postCheckBalance(submitData);
      const { code, msg } = res.data;

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

/** 计算仓储&配送费用 */
const handleComputedPrice = ({ row }) => {
  ElMessageBox.confirm('确认计算仓储&配送费用?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      details.loadingObj.pageLoading = true;

      const res = await postReal(row.orderInfoId);
      const { code, msg } = res.data;

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

/** 导出 */
const handleExport = () => {
  ElMessageBox.confirm('是否确认导出?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async() => {
    try {
      details.loadingObj.pageLoading = true

      const submitData=details.pageStatus  === 1 ?
        { ...details.pageInfo[0].query } :
        { ...details.pageInfo[1].query }
    
      submitData.listType = details.pageStatus;
 
      if (getObjType(submitData.createTimeArr) === 'array' && submitData.createTimeArr.length > 0){
        submitData.createTimeStartStr = submitData.createTimeArr[0]
        submitData.createTimeEndStr = submitData.createTimeArr[1]
      }

      if (getObjType(submitData.checkTimeArr) === 'array' && submitData.checkTimeArr.length > 0){
        submitData.checkTimeStartStr = submitData.checkTimeArr[0]
        submitData.checkTimeEndStr = submitData.checkTimeArr[1]
      }

      delete submitData.createTimeArr
      delete submitData.checkTimeArr

      const res = await postOrderInfoListExport(submitData)
      
      const {status, data} = res
      if (status !== 200) return
      downloadXls(data, details.pageStatus  === 1 ? '对账预存单toB.xlsx': '对账预存单toC.xlsx')

      ElMessage.success('导出成功!');
    } 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;
}

// 弹窗
:deep(.el-overlay) {
  position: absolute;
}

:deep(.el-overlay-dialog) {
  position: absolute;
}
</style>
