<template>
  <!-- 订单分析 -->
  <div class="orderExpotPage flex-col">
    <s-header :name="$t('orderExport.orderAnalysis')" :noback="false"></s-header>
    <div class="Body flex-col">
      <div class="mod3 flex-col">
        <div class="group1 flex-col">
          <div class="titleBox flex-col">
            <div class="layer2 flex-row">
              <div class="section5 flex-col"></div>
              <div class="TextGroup2 flex-col">
                <span class="txt4">{{ $t("orderExport.dataOverview") }}</span>
              </div>
            </div>
          </div>
          <div class="dateSelectBox">
            <dateSelectList @update="update($event)"></dateSelectList>
          </div>
          <div class="l-f l-flex-e o-plr-15 o-pt-10">
            <span class="o-mr-6 c-text-13 c-text-color">{{ $t("orderExport.groupType") }}:</span>
            <kTabs @tabchg="tabChg" :tabList="tabList"></kTabs>
          </div>
          <div class="mod7 flex-col">
            <div class="box1 flex-col justify-between">
              <div class="group4 l-flex-between">
                <div class="ImageText2 l-flex-RC">
                  <div class="mod8 l-flex-RC">
                    <div class="group5 flex-col"></div>
                    <div class="TextGroup2 flex-col">
                      <span class="txt1 c-text-w6">{{
                        $t("orderExport.orderDetails")
                      }}</span>
                    </div>
                  </div>
                </div>
                <div class="l-flex-RC">
                  <div class="c-text-13 l-flex-RC text5">
                    <span @click="noticeClk" class="">{{
                      $t("orderExport.clickFilter")
                    }}</span>
                    <div class="outer4 flex-col o-ml-6"></div>
                  </div>
                  <div @click="exportOrder()" class="c-text-13 l-flex-RC o-ml-20 c-text-color">
                    <span class="">{{
                      $t("orderExport.exportToExcel")
                    }}</span>
                    <div class="outer4 flex-col o-ml-6"></div>
                  </div>
                </div>
              </div>
              <img class="img2" referrerpolicy="no-referrer"
                src="../../assets/line.png" />
            </div>
          </div>
          <!-- <van-pull-refresh disabled v-model="refreshing" @refresh="onRefresh"> -->
          <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
            :finished="finished" :finished-text="$t('public.noMore')" @load="onLoad" :immediate-check="false">
            <div v-for="(item, index) in tableData" :key="index" class="orderItem">
              <div class="mod9 flex-row">
                <!-- <span class="info7">&yen;</span> -->
                <span class="word9">{{ $t("orderExport.totalSales") }}</span>
                <span class="info7">{{ currencySymbol }}</span>
                <span class="info8">{{ item.priceTotal }}</span>
              </div>
              <div class="mod10 flex-row">
                <span class="txt3 o-mr-10">{{ item.username }}</span>
                <span class="txt4 c-text-line1">{{ item.name }}</span><span class="txt4 c-text-line1">，{{ item.phone
                }}</span>
              </div>
              <span class="info9">{{ $t("orderExport.address") }}：{{ item.address }}</span>
              <div class="mod11 flex-col">
                <span v-if="type == 2" class="txt5">{{ item.equipmentTotal }}{{ $t("orderExport.machines") }}，{{
                  $t("orderExport.superior")
                }}：{{ item.lastUsername }}</span>
                <div v-else class="txt5 l-flex-RC">
                  <div>{{ item.equipmentType }}</div>
                  <div class="lineCon o-mlr-6"></div>
                  <div>{{ item.clientId }}</div>
                </div>
              </div>
            </div>
          </van-list>
          <!-- </van-pull-refresh> -->
        </div>
      </div>
    </div>
    <!-- 筛选弹窗 -->
    <kDialog :dialogTitle="$t('orderExport.searchPop.title')" :cancelBtnTxt="$t('orderExport.searchPop.clearFilter')"
      :confirmBtnTxt="$t('orderExport.searchPop.filter')" ref="kDialogRef" @confirmclk="confirmClk"
      :isCloseForCancel="false" @cancelclk="cancelClk">
      <template #content>
        <div class="cust_vantBorder">
          <van-field clearable v-model="searchForm.orderNo" :placeholder="$t('orderExport.searchPop.orderNoPlace')"
            :label="$t('orderExport.searchPop.orderNo')" />
          <van-field clearable v-model="searchForm.busiName" :placeholder="$t('orderExport.searchPop.busiNamePlace')"
            :label="$t('orderExport.searchPop.busiName')" />
          <van-field @click-input="changeTypeInpClk" readonly clearable v-model="searchForm.ifForeignName"
            :placeholder="$t('orderExport.searchPop.mainOverPlace')" :label="$t('orderExport.searchPop.mainOver')">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="searchForm.ifForeignName" @click="searchForm.ifForeignName = '';
                searchForm.ifForeign = '';" class="o-mr-6" name="clear" />
                <van-icon @click="changeTypeInpClk" name="arrow-down" />
              </div>
            </template>
          </van-field>
          <van-field v-if="isAdmin()" @click-input="companyTypeInpClk" readonly clearable
            v-model="searchForm.companyTypeName" :placeholder="$t('orderExport.searchPop.companyTypePlaceholder')"
            :label="$t('orderExport.searchPop.companyTypeLabel')">
            <template #right-icon>
              <div class="l-flex-RC">
                <van-icon v-if="searchForm.companyTypeName" @click="
                  searchForm.companyTypeName = '';
                searchForm.companyType = '';
                " class="o-mr-6" name="clear" />
                <van-icon @click="companyTypeInpClk" name="arrow-down" />
              </div>
            </template>
          </van-field>
        </div>
      </template>
    </kDialog>
    <!-- 大陆或海外弹窗 -->
    <van-popup v-model:show="changeTypeShow" position="bottom">
      <van-picker :title="$t('orderExport.searchPop.mainOverPlace')" :columns="changeTypePopList"
        :columns-field-names="changeTypePopFieldName" @confirm="changeTypePopConfirm" @cancel="changeTypeShow = false" />
    </van-popup>
    <!-- 公司平台弹窗 -->
    <van-popup v-model:show="companyTypeShow" position="bottom">
      <van-picker :title="$t('orderExport.searchPop.companyTypePlaceholder')"
        :columns="companyTypePopList" :columns-field-names="changeTypePopFieldName" @confirm="companyTypePopConfirm"
        @cancel="companyTypeShow = false" />
    </van-popup>
  </div>
</template>
<script>
import { getOrderList, Api_getOrderExport } from "@/service/orderExport";
import { onMounted, reactive, toRefs, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getLoginUser, $M_ExportFile } from "@/common/js/utils";
import dateSelectList from "@/components/dateSelectList";
import dateUtil from "@/utils/dateUtil";
import kTabs from "@/components/commom/kTabs/index.vue";
import { useI18n } from "vue-i18n";
import kDialog from "@/components/commom/kDialog/index.vue";
import moment from 'moment';
import { styleUrl } from "../../common/js/utils";
import { showFailToast } from "vant";

export default {
  name: "orderExport",
  components: { sHeader, dateSelectList, kTabs, kDialog },
  setup() {
    // 分页
    const pageNo = ref(1);
    const pageSize = ref(10);
    // let ruleData = reactive({
    //   tableData: [],
    // });
    const tableData = ref([]);
    const orderTotal = ref(0);
    // 上拉刷新
    const loading = ref(true);
    const finished = ref(false);
    const error = ref(false);
    // 下拉刷新
    // const refreshing = ref(false);
    const user = getLoginUser();
    const companyTypeShow = ref(false);
    // 是否管理员
    const isAdmin = () => { return (user && user.type === 0); }
    // 公司平台弹窗
    const companyTypeInpClk = () => {
      companyTypeShow.value = true;
    };
    onMounted(() => {
      // 加载样式
      styleUrl('orderExport');
      // ruleData.tableData = [];
      tableData.value = [];
      pageNo.value = 1;
      pageSize.value = 10;
      // 今日
      searchParams.startDate = moment().format("YYYY-MM-DD") + " 00:00:00";
      searchParams.endDate = moment().format("YYYY-MM-DD") + " 23:59:59";
      if (user) {
        // onRefresh();
        finished.value = false;
        getList();
      }
    });
    // 上拉加载
    const onLoad = () => {
      if (!finished.value) {
        pageNo.value = pageNo.value + pageSize.value;
        getList();
      }
    };
    // 获取列表数据
    const getList = async () => {
      loading.value = true;
      finished.value = false;
      // 如果存在chartType去掉
      if (searchParams.chartType) {
        delete searchParams.chartType;
      }
      let param = {
        current: pageNo.value,
        size: pageSize.value,
      };
      const { data } = await getOrderList(Object.assign(param, searchParams));
      if (data.code === "00000") {
        if (data.data.total === 0) {
          finished.value = true;
        } else {
          if (param.current === 1) {
            tableData.value = [];
            orderTotal.value = 0;
          }
          // 列表值叠加
          if (data.data.records.length > 0) {
            tableData.value = tableData.value.concat(data.data.records);
            orderTotal.value = data.data.records.length + orderTotal.value;
            if (orderTotal.value === data.data.total) {
              finished.value = true;
            }
          } else {
            finished.value = true;
          }
        }
        loading.value = false;
      } else {
        loading.value = false;
        showFailToast("数据加载失败");
      }
    };
    // getOrderList(Object.assign(param, searchParams)).then((res) => {
    //   const { data } = res.data;
    //   console.log('data的值是 >>>', data)
    //   if (data) {
    //     // refreshing.value = false;
    //     ruleData.tableData.push(...data.records);
    //     console.log("数据长度：", ruleData.tableData.length);
    //     console.log("数据量：", data.total);
    //     // 加载状态结束
    //     loading.value = false;
    //     if (ruleData.tableData.length === data.total) {
    //       finished.value = true;
    //     }
    //   }
    // });
    // };
    // 引入语言
    const { t } = useI18n();
    // 大陆或海外弹窗
    // 控制显示
    const changeTypeShow = ref(false);
    // 点击显示弹窗
    const changeTypeInpClk = () => {
      changeTypeShow.value = true;
    };
    // 弹窗选中的值
    const changeTypePopFieldName = reactive({
      text: "name",
      value: "id",
    });
    // 弹窗选项
    const changeTypePopList = [
      {
        name: t('orderExport.searchPop.mainland'),
        id: "0",
      },
      {
        name: t('orderExport.searchPop.overseas'),
        id: "1",
      },
    ];
    // 点击弹窗的确定按钮
    const changeTypePopConfirm = ({ selectedOptions }) => {
      searchForm.ifForeign = selectedOptions[0].id;
      searchForm.ifForeignName = selectedOptions[0].name;
      changeTypeShow.value = false;
    };
    const companyTypePopConfirm = ({ selectedOptions }) => {
      searchForm.companyType = selectedOptions[0].id;
      searchForm.companyTypeName = selectedOptions[0].name;
      companyTypeShow.value = false;
    };
    // 点击导出按钮
    const exportOrder = async () => {
      const param = {
        current: pageNo.value,
        size: pageSize.value,
      };
      const { headers, data } = await Api_getOrderExport(Object.assign(param, searchParams));
      // console.log('headers', headers)
      // console.log('data', data)
      $M_ExportFile(data, headers);
    };
    // 筛选弹窗的元素
    const kDialogRef = ref(null);
    // 点击筛选
    const noticeClk = () => {
      kDialogRef.value.openDialog();
    };
    // 筛选弹窗
    const searchForm = reactive({
      orderNo: "",
      busiName: "",
      ifForeign: "0",
      ifForeignName: "大陆",
      companyType: "",
      companyTypeName: "全部",
    });
    // 点击筛选条件的清空条件按钮
    const cancelClk = () => {
      searchForm.orderNo = '';
      searchForm.busiName = '';
      searchForm.ifForeign = '0';
      searchForm.ifForeignName = '大陆';
      searchForm.companyType = "";
    };
    // 点击筛选条件的筛选按钮
    const confirmClk = () => {
      searchParams.clientId = searchForm.orderNo;
      searchParams.username = searchForm.busiName;
      searchParams.ifForeign = searchForm.ifForeign;
      searchParams.companyType = searchForm.companyType;
      tableData.value = [];
      getList();
    };
    // 商户设备tab栏
    const tabList = ref([
      {
        name: t("orderExport.merchant"),
        icon: "",
        id: 1,
      },
      {
        name: t("orderExport.equipment"),
        icon: "",
        id: 2,
      },
    ]);
    // 公司平台
    const companyTypePopList = [
      {
        name: t("orderExport.searchPop.whole"),
        id: "",
      },
      {
        name: t("orderExport.searchPop.sz"),
        id: "0",
      },
      {
        name: t("orderExport.searchPop.sc"),
        id: "1",
      },
    ];
    // 点击tab
    const tabChg = (e) => {
      pageNo.value = 1;
      pageSize.value = 10;
      // ruleData.tableData = [];
      tableData.value = [];
      if (e == 1) {
        searchParams.type = 1;
      } else {
        searchParams.type = 2;
      }
      getList();
    };
    let searchParams = reactive({
      type: "2", // 分组类型
      clientId: "", // 设备编号
      username: "",
      startDate: "",
      endDate: "",
      ifForeign: '0',
      adminId: user.id,
      companyType: "",
    });
    // 搜索点击
    const searchClick = () => {
      // console.log("searchClick");
    };
    // 今日、明日、本周、本月、其他时间选择回调
    const update = (uDate) => {
      // console.log("日期修改")
      pageNo.value = 1;
      pageSize.value = 10;
      // ruleData.tableData = [];
      tableData.value = [];
      searchParams = Object.assign(searchParams, uDate);
      searchParams.startDate = dateUtil.formateDate(
        new Date(searchParams.startDate),
        "yyyy-MM-dd hh:mm:ss"
      );
      searchParams.endDate = dateUtil.formateDate(
        new Date(searchParams.endDate),
        "yyyy-MM-dd hh:mm:ss"
      );
      getList();
      // onRefresh(1);
    };

    // 自定义货币符号
    const currencySymbol = ref('￥');
    const loginUserStr = localStorage.getItem('loginUser');
    const loginUser = JSON.parse(loginUserStr);
    if (loginUser.currencySymbol) {
      currencySymbol.value = loginUser.currencySymbol;
    } else {
      currencySymbol.value = '￥';
    }
    return {
      ...toRefs(searchParams),
      companyTypePopConfirm,
      companyTypePopList,
      searchClick,
      companyTypeInpClk,
      companyTypeShow,
      update,
      exportOrder,
      tabChg,
      tabList,
      confirmClk,
      searchForm,
      noticeClk,
      kDialogRef,
      cancelClk,
      changeTypePopList,
      changeTypePopConfirm,
      changeTypeShow,
      changeTypeInpClk,
      changeTypePopFieldName,
      pageNo,
      pageSize,
      loading,
      finished,
      // refreshing,
      // onRefresh,
      onLoad,
      getList,
      isAdmin,
      tableData,
      error,
      // ...toRefs(ruleData),
      currencySymbol,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "../../styles/orderExport/index.less";
</style>
