<template>
  <!-- 订单中心 -->
  <div class="orderPage flex-col">
    <s-header :name="$t('orderCenter.orderCenter')" :noback="false"></s-header>
    <div class="orderBox">
      <van-list v-model:loading="loading" v-model:error="error" :error-text="$t('public.requestFailed')"
        :finished="finished" :finished-text="$t('public.noMore')" offset="300" :immediate-check="false" @load="onLoad">
        <div class="main3 flex-col justify-center">
          <div class="outer1 flex-col justify-between">
            <div class="group4 flex-row justify-between">
              <div class="ImageText1 flex-col">
                <div class="outer2 flex-row justify-between">
                  <div class="block1 flex-col"></div>
                  <div class="TextGroup1 flex-col">
                    <span class="txt1">{{ $t('orderCenter.dataOverview') }}</span>
                  </div>
                </div>
              </div>
              <div class="ImageText2 flex-col" @click="searchClick()">
                <div class="group5 flex-row justify-between">
                  <img class="icon2" src="../../assets/order/search.png" />
                  <div class="TextGroup2 flex-col">
                    <span class="txt2">{{ $t("common.search") }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <dateSelectList @update="update($event)"></dateSelectList>
        <typeSelectList @upselectdata="upselectdata($event)"></typeSelectList>
        <div v-if="!noData(salesVolume, salesNumber, orderNumber)" class="o-plr-8">
          <div class="outer5 flex-col">
          <div class="block5 flex-col">
            <div class="outerBox flex-row">
              <div class="main4 flex-col justify-between">
                <div class="main5 flex-row justify-center">
                  <span class="word8">&yen;</span>
                  <span class="word9">{{ salesVolume }}</span>
                </div>
                <span class="info5">{{ $t("home.totalIncome") }}</span>
              </div>
              <div class="TextGroup7 flex-col">
                <div class="mod3 flex-col justify-between">
                  <span class="txt8">{{ salesNumber }}</span>
                  <span class="info6">{{ $t("home.productNum") }}</span>
                </div>
              </div>
              <div class="TextGroup8 flex-col">
                <div class="outer6 flex-col justify-between">
                  <span class="txt9">{{ orderNumber }}</span>
                  <span class="word10">{{ $t("home.numberOfOrders") }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        </div>
        <kNoData v-else></kNoData>
        <div class="o-mtb-10" style="height: 10px; background: #f5f5f5"></div>
      <!-- 时间 -->
      <div class="c-text-c c-text-18">
        {{$M_FormatTime(searchParams.startDate,'YYYY-MM-DD')}}--{{$M_FormatTime(searchParams.endDate,'YYYY-MM-DD')}}
      </div>
        <div class="group7 flex-col justify-center">
          <div class="main9 flex-col justify-between">
            <div class="wrap1 flex-row justify-between">
              <div class="ImageText7 flex-col">
                <div class="mod5 flex-row justify-between">
                  <div class="block3 flex-col"></div>
                  <div class="TextGroup7 flex-col">
                    <span class="info3">{{ $t('orderCenter.orderDetails') }}</span>
                  </div>
                </div>
              </div>
              <div class="ImageText8 flex-col" @click="gotoOrderExcel()">
                <div class="bd3 flex-row justify-between">
                  <span class="info4 flex-col">{{ $t('orderCenter.exportToExcel') }}</span>
                  <div class="outer3 flex-col"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="section1 flex-col">
          <div class="group8 flex-col">
            <div class="section4 flex-col">
              <div v-for="(item, index) in orderList" :key="index">
                <div class="section5 flex-col" @click="orderClick(item)">
                  <div class="flex-row align-center">
                    <div class="sugerPhto" v-if="showSugerPhoto(item)">
                      <img class="sugerImg" :src="showSugerPhoto(item)" />
                    </div>
                    <div class="flex-col">
                      <div class="flex-row align-center">
                        <div class="main10 flex-col"></div>
                        <span class="txt11">{{ showOrderTime(item,1) }}</span>
                      </div>
                      <div class="flex-row align-center">
                        <span class="word11">{{ $t('orderCenter.equipmentNo') }}：{{ showClientId(item) }}</span>
                        <span class="word13">{{ $t('orderCenter.tradeName') }}：{{ item.productName }}</span>
                      </div>
					  <div class="flex-row align-center">
					    <span class="word11">{{ $t('orderCenter.equipmentName') }}：{{ item.es }}</span>
						<span class="word13"></span>
					  </div>
                      <div class="flex-row align-end">
                        <div class="pricBox flex-row align-end" :class="{ orderError: item.status === 0 }">
                          <span class="txt9">{{ item.statusText }}：</span>
                          <span class="info5">&yen;</span>
                          <span class="word12">{{ item.price }}</span>
                        </div>
                        <span class="word14">{{ $t('orderCenter.dividingDomesticService') }}：&yen;{{ showSubcom(item)
                        }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="typeof item.status === 'undefined'" class="main11 flex-col orderSuccess"></div>
                  <div v-else class="main11 flex-col" :class="{
                    orderSuccess: item.status === 1,
                    orderError: item.status === 0,
                    refunding: item.status === 2,
                    refunded: item.status === 3,
                  }"></div>
                </div>
                <div class="section6 flex-col"></div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <!-- 搜索弹出框 -->
    <orderSearch ref="searchRef" @search="search($event)"></orderSearch>
    <!-- 退款弹窗 -->
    <van-popup v-model:show="refundType" position="bottom" round>
      <div class="refundBox flex-col">
        <div class="section1 flex-col">
          <div class="group3 flex-col">
            <div class="TextGroup1 l-flex-center">
              <div class="outer1 flex-col">
                <!-- <span class="txt4">这里是设备名称</span> -->
                <span class="info1">{{ $t('orderCenter.business') }}</span>
                <span class="txt5">+{{ refundObject.price }}</span>
              </div>
            </div>
            <div class="layer1 flex-col"></div>
            <div class="layer2 flex-row justify-between">
              <span class="info2">{{ $t('orderCenter.accountBalance') }}</span>
              <span class="txt6">{{ accountDetail.altAvilBalance }}</span>
            </div>
            <div class="layer3 flex-row justify-between">
              <span class="word2">{{ $t('orderCenter.orderNo') }}</span>
              <span class="info3">{{ refundObject.sn }}</span>
            </div>
            <div class="layer3 flex-row justify-between">
              <span class="word2">{{ $t('orderCenter.commodity') }}</span>
              <span class="info3">{{ refundObject.productName }}</span>
            </div>
            <div class="layer4 flex-row justify-between">
              <span class="word3">{{ $t('orderCenter.distribution') }}</span>
              <span class="word4">{{ showSubcom(refundObject) }}</span>
            </div>
            <div class="layer5 flex-row justify-between">
              <span class="txt7">{{ $t('orderCenter.state') }}</span>
              <span class="word5">{{ showStatus(refundObject) }}</span>
            </div>
            <div class="layer6 flex-row justify-between">
              <span class="word6">{{ $t('orderCenter.paymentMethod') }}</span>
              <span class="word7">{{ showPayType(refundObject) }}</span>
            </div>
            <div class="layer6 flex-row justify-between">
              <span class="word6">{{ $t('orderCenter.creationTime') }}</span>
              <span class="word7">{{ showOrderTime(refundObject,2) }}</span>
            </div>
            <div v-if="refundObject.status === 3" class="layer7 flex-row justify-between">
              <span class="word8">{{ $t('orderCenter.refunded') }}</span>
              <span class="info4">{{ refundObject.refundAmount }}</span>
            </div>
            <van-button size="small" v-if="refundObject.status === 1" @click="noticeClk(refundObject)" round
              type="primary" style="margin-top: 20px;">
              {{ $t('orderCenter.initiateRefund') }}
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>
    <!-- 退款弹窗 -->
    <kDialog :isCloseForConfirm="false" :dialogTitle="$t('orderCenter.refundTip')"
      :confirmBtnTxt="$t('orderCenter.refundSubmit')" ref="kDialogRef" @confirmclk="confirmClk">
      <template #content>
        <div class="cust_vantBorder l-flex-RC">
          <van-field colon required type="number" clearable v-model="cofficentForm.price" class="inputAmount"
            :placeholder="$t('orderCenter.refundAmountPlace')" :label="$t('orderCenter.refundAmount')">
            <template #extra>
              {{$t('orderCenter.most')}}￥{{ cofficentForm.maxPrice }}
            </template>
          </van-field>
		  <div class="van-cell l-flex-RC">
			<div class="van-field__label van-field__label--required">
				<span>{{$t('orderCenter.refundQuantity')}}: </span>
			</div>
			<van-stepper v-model="cofficentForm.productNumber" theme="round" button-size="22"
			:max="cofficentForm.maxNumber" disable-input />
			<span class="o-pl-10">{{$t('orderCenter.most')+cofficentForm.maxNumber+$t('orderCenter.at')}}</span>
		  </div>
        </div>
      </template>
    </kDialog>
  </div>
</template>
<script>
import { Api_getOnlineExport } from "@/service/order";
// 导入接口
import { getAdminMch } from "@/service/merchantManage";
// 导入弹窗
import kDialog from "@/components/commom/kDialog/index.vue";
// 导入无数据组件
import { Dialog } from 'vant';
import kNoData from "@/components/commom/kNoData/index.vue";
import { onMounted, reactive, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import orderSearch from "./orderSearch.vue";
import { getOrderList, refundOrder } from "@/service/order/index";
import { Toast } from "vant";
import { getLoginUser, $M_IsDate,$M_FormatTime,$M_ExportFile } from "@/common/js/utils";
import dateUtil from "@/utils/dateUtil";
import dateSelectList from "@/components/dateSelectList";
import typeSelectList from "@/components/typeSelectList";
import { getStatistics } from "@/service/home";
import { useI18n } from "vue-i18n";
export default {
  name: "order",
  components: { sHeader, orderSearch, dateSelectList, typeSelectList, kNoData, kDialog },
  setup() {
    // 批量修改弹窗
    const kDialogRef = ref(null);
    // 点击批量修改
    const noticeClk = (row) => {
      console.log('row', row)
      cofficentForm.price = row.price;
      cofficentForm.maxPrice = row.price;
      cofficentForm.id = row.id;
	  cofficentForm.maxNumber = row.productNumber;
	  cofficentForm.productNumber = row.productNumber;
      kDialogRef.value.openDialog();
    };
    // 点击确定按钮
    const confirmClk = () => {
      if (!cofficentForm.price) {
        Toast(t('orderCenter.refundAmountPlace'));
      } else if (cofficentForm.price > cofficentForm.maxPrice) {
        Toast(t('orderCenter.most') + cofficentForm.maxPrice);
      } else {
		Dialog.confirm({
			// title: "提示",
			message: t('device.editCheck'),
		}).then(() => {
			refundAjax();
			kDialogRef.value.closeDialog();
		});
      }
    }
    // 退款操作
    const refundAjax = async () => {
      delete cofficentForm.maxPrice;
      const { data } = await refundOrder(cofficentForm);
      console.log('data', data)
      if (data.code && data.code !== 'B0001') {
        refundType.value = false;
		Dialog.alert({
		  message: t('orderCenter.refundSucceeded'),
		}).then(() => {
		  // on close
			orderList.value = [];
			search({});
		});
        // Toast.success(t('orderCenter.refundSucceeded'));
      } else {
        Toast.fail(data.message);
      }
    };
    // 修改的价格
    const cofficentForm = reactive({
      price: "",
      maxPrice: "",
	  maxNumber: "",
      id: "",
	  productNumber: ""
    });
    // 引入语言
    const { t } = useI18n();
    // 订单商品图片路径处理
    const showSugerPhoto = (row) => {
      let imgId = "";
      // 将note的字段拆解，默认第一个商品图片
      if (row.note) {
        const firstGood = row.note.split(",")[0];
        // 将商品id找出来
        // 有些商品没有这个id的
        // 有些商品没有“-”的
        if (firstGood.indexOf('-') !== -1) {
          const singleGood = firstGood.split("-");
          if (singleGood && singleGood.length > 0) {
            imgId = singleGood[0];
          }
        }
      }
      if (imgId) {
        return require(`../../assets/order/spunSugar/goods/${imgId}.png`);
      }
      return imgId;
    };
    // 如果是空数据
    const noData = (volumes, nums) => {
      if (!volumes && !nums) {
        return true;
      }
      return false;
    };
    const user = getLoginUser();
    const searchRef = ref(null);
    const orderList = ref([]);
    const orderTotal = ref(0);
    const loading = ref(true);
    const error = ref(false);
    const finished = ref(false);
    // 滚动加载
    const onLoad = () => {
      if (!finished.value) {
        searchParams.current = searchParams.current + 1;
        getList();
      }
    };
    // 页面列表查询参数
    let searchParams = reactive({
      adminId: "", // 用户账户id
      userName: "", // 用户名 String 没有值时传null
      adminType: "", // 判断是否查全部商户 当用户为商家时，“本商户”这个选项为“所有下级用户”传入一个“all”的值，其他情况传null
      type: user.ifForeign, // 订单类型 用来区分是线上、线下订单，0：线上，1：线下。默认值一般要根据当前登录用户的类型去选择。区分的参数是admin里ifForeign的值。ifForeign=0则type=0.
      payType: "", // 支付方式 全部时传null 0：无需支付 1：硬币 2：纸币 3：硬币+纸币 4：信用卡 5：电子支付 ALIPAY_NATIVE：支付宝主扫 WEIXIN_NATIVE：微信主扫 ALIPAY_CARD：支付宝反扫 WEIXIN_CARD：微信反扫
      productNo: "", // 商品的标识 全部时传null。 Tproductd对象的属性no的值。
      clientId: "", // 设备编号 String
      dateType: "0", // 所选时间类型 String 0：创建时间 1：退款时间
      startDate: "", // 开始时间 Date
      endDate: "", // 结束时间 Date
      current: 1, // 页数
      size: 20, // 页大小
      status:"",//支付状态
    });
    let chartType = "day";
    // 获取订单列表数据
    const getList = async () => {
 	  finished.value = false;
      getStatisticsFun();
      // 因为订单的时间格式不一样
      const params = Object.assign({}, searchParams);
      if ($M_IsDate(params.startDate)) {
        params.startDate = dateUtil.formateDate(
          new Date(params.startDate),
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        params.startDate = "";
      }
      if ($M_IsDate(params.endDate)) {
        params.endDate = dateUtil.formateDate(
          new Date(params.endDate),
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        params.endDate = "";
      }
      const { data } = await getOrderList(Object.assign({}, params));
      if (data.code === "00000") {
        if (params.current === 1) {
          orderList.value = [];
        }
        // 列表值叠加
        if (data.data) {
          orderList.value = orderList.value.concat(
            data.data.records.map((item) => {
              return {
                ...item,
                statusText:
					item.altInfo!=null
					  ? t('orderCenter.onlinePayment')
                      : t('orderCenter.offlinePayment'),
                  // item.status && item.status === 0
                  //   ? t('orderCenter.toBePaid')
                  //   : item.status
                  //     ? t('orderCenter.onlinePayment')
                  //     : t('orderCenter.offlinePayment'),
				// productName:
				// 	item.pr
              };
            })
          );
          orderTotal.value = data.data.total;
          if (
            data.data.total === 0 ||
            (data.data.total > 0 &&
              orderList.value.length === data.data.total) ||
            data.data.records.length === 0
          ) {
            finished.value = true;
          }
        } else {
          finished.value = true;
        }
        loading.value = false;
      } else {
        Toast.fail(data.message);
      }
    };
    // 搜索表单点击
    const searchClick = () => {
      searchRef.value.showSearch();
    };
    // 搜索表单初始化页面及状态查询列表
    const search = (data) => {
      searchParams = Object.assign(searchParams, data);
      // 这个会导致请求两次接口
      // finished.value = false;
	  orderList.value = [];
	  loading.value = true;
      searchParams.current = 1;
      getList();
    };
    // 今日、明日、本周、本月、其他时间选择回调
    const update = (uDate) => {
      chartType = uDate.chartType;
      searchParams = Object.assign(searchParams, uDate);
      search();
    };
    // 商户、支付方式、设备、商品选择回调
    const upselectdata = (uSData) => {
      console.log('uSData', uSData)
      searchParams = Object.assign(searchParams, uSData);
      console.log('searchParams', searchParams)
      search();
    };
    // 初始化页面获取列表
    onMounted(async () => {
      orderList.value = [];
      searchParams.current = 1;
      if (user) {
        // searchParams.adminType = isShowAdmin() ? 'all' : null;
        searchParams.adminId = user.id;
        searchParams.userName = user.username;
        // searchParams.startDate = dateUtil.formateDate(
        //   new Date(new Date(new Date().getTime()).setHours(0, 0, 0, 0)),
        //   "yyyy-MM-dd hh:mm:ss"
        // );
        // 这是获取本周的第一天
        // let dayInMs = 24 * 60 * 60 * 1000;
        // let now = new Date();
        // let firstDay = new Date(now.getTime() - (now.getDay() - 1) * dayInMs);
        // searchParams.startDate = dateUtil.formateDate(firstDay, "yyyy-MM-dd hh:mm:ss");

        // 获取当天
        let now = new Date();
        let startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
        searchParams.startDate = dateUtil.formateDate(startDate, "yyyy-MM-dd hh:mm:ss");

        // searchParams.endDate = dateUtil.formateDate(
        //   new Date(new Date(new Date().getTime()).setHours(23, 59, 59, 59)),
        //   "yyyy-MM-dd hh:mm:ss"
        // );
        // 这是获取本周的最后一天
        // let lastDay = new Date(now.getTime() + (7 - now.getDay()) * dayInMs);
        // searchParams.endDate = dateUtil.formateDate(lastDay, "yyyy-MM-dd hh:mm:ss");
        let endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
        searchParams.endDate = dateUtil.formateDate(endDate, "yyyy-MM-dd hh:mm:ss");

        finished.value = false;
        getList();
        // 获取账户详情
        getAccountDetail(user.id);
      }
    });
    // 跳转订单导出
    const gotoOrderExcel = async () => {
      // router.push({ path: "/orderExport" });
      const { headers, data } = await Api_getOnlineExport(searchParams);
      console.log('headers', headers)
      console.log('data', data)
      $M_ExportFile(data, headers);
    };
    // 订单详情-退款弹窗
    const refundType = ref(false);
    const refundObject = ref({});
    const orderClick = (item) => {
		//查询商户余额，要用admin的type去区分 TODO
      refundObject.value = item;
      refundType.value = true;
    };
    const accountDetail = ref({});
      // 获取账户详情
    const getAccountDetail = (id)=>{
      getAdminMch({id}).then(res=>{
        accountDetail.value = res.data.data;
      })
    };
    // 订单时间格式转换
    const showOrderTime = (item,idx) => {
      if(idx===1){
        switch(item.status){
          case 1:
            return dateUtil.formateDate(new Date(item.payDate), "yyyy-MM-dd hh:mm:ss");
          case 3:
            return dateUtil.formateDate(new Date(item.refundDate), "yyyy-MM-dd hh:mm:ss");
          default:
            return dateUtil.formateDate(new Date(item.createDate), "yyyy-MM-dd hh:mm:ss");
        }
      }else{
        return item && item.createDate
          ? dateUtil.formateDate(new Date(item.createDate), "yyyy-MM-dd hh:mm:ss")
          : "";
      }
    };
    // 设备编号格式转换
    const showClientId = (item) => {
      return item && item.clientId
        ? item.clientId.substring(item.clientId.length - 6)
        : "";
    };
    // 计算分佣
    const showSubcom = (item) => {
      let subcom = "0";
      if(item.altInfo){
        const altInfo = JSON.parse(item.altInfo);
        if(altInfo&&altInfo.length>0){
          // altInfo这个属性里，最后一个实体的altAmount的值就是他的分佣。
          subcom = altInfo[altInfo.length-1 ]['altAmount'];
        }
      }
      // switch (item.type) {
      //   case 2:
      //     subcom = (item.price * item.agencyProportion).toFixed(2);
      //     break;
      //   case 3:
      //     subcom = (item.price * item.merchantProportion).toFixed(2);
      //     break;
      //   case 4:
      //     subcom = (item.price * item.personageProportion).toFixed(2);
      //     break;
      // }
      return subcom;
    };
    // 弹窗订单状态
    const showStatus = (item) => {
      if (typeof item.status === "undefined") {
        return t('orderCenter.paymentSucceeded');
      } else {
        if (item.status === 0) {
          return t('orderCenter.unpaid');
        }
        if (item.status === 1) {
          return t('orderCenter.paid');
        }
        if (item.status === 2) {
          return t('orderCenter.refundInProgress');
        }
        if (item.status === 3) {
          return t('orderCenter.refunded');
        }
      }
      return item;
    };
    const paySouerList = [
      { text: t('orderCenter.whole'), values: null },
      { text: t('orderCenter.noPaymentRequired'), values: 0 },
      { text: t('orderCenter.coin'), values: 1 },
      { text: t('orderCenter.notes'), values: 2 },
      { text: t('orderCenter.coinsNotes'), values: 3 },
      { text: t('orderCenter.creditCard'), values: 4 },
      { text: t('orderCenter.electronicPayment'), values: 5 },
      { text: t('orderCenter.mainSweepOfAlipay'), values: "ALIPAY_NATIVE" },
      { text: t('orderCenter.weChatScanning'), values: "WEIXIN_NATIVE" },
      { text: t('orderCenter.antiScanningOfAlipay'), values: "ALIPAY_CARD" },
      { text: t('orderCenter.weChatBackScanning'), values: "WEIXIN_CARD" },
    ];
    // 弹窗支付上述
    const showPayType = (item) => {
      const payType = user.ifForeign === "0" ? item.frpCode : item.payType;
      const paySoure = paySouerList.filter((i) => i.values === payType);
      if (paySoure.length > 0) {
        return paySoure[0].text;
      } else {
        return "";
      }
    };
    const salesVolume = ref(0);
    const salesNumber = ref(0);
	const orderNumber = ref(0);
    // 查询图表
    const getStatisticsFun = async () => {
      console.log('searchParams',searchParams)
      const params = {
        adminId: user.id,
        chartType: chartType,
        endDate:searchParams.endDate,
        ifForeign: user.ifForeign,
        startDate:searchParams.startDate,
        userName: searchParams.userName,
        clientId:
          searchParams.clientId === "" ? null : searchParams.clientId,
        equipmentId:
          searchParams.equipmentId === "" ? null : searchParams.equipmentId,
        payType:
          searchParams.payType === "" ? null : searchParams.payType,
      };
      const { data } = await getStatistics(params);
      if (data.code && data.data) {
        salesVolume.value = 0;
        salesNumber.value = 0;
		orderNumber.value = 0;
        data.data.series[0].data.forEach((item) => {
          salesNumber.value = parseInt(salesNumber.value + item);
        });
        data.data.series[1].data.forEach((item) => {
          salesVolume.value = parseInt(salesVolume.value + item);
        });
		data.data.series[2].data.forEach((item) => {
		  orderNumber.value = parseInt(orderNumber.value + item);
		});
      }
    };
    return {
      loading,
      error,
      finished,
      onLoad,
      orderList,
      orderTotal,
      searchRef,
      searchClick,
      search,
      update,
      upselectdata,
      gotoOrderExcel,
      refundType,
      refundObject,
      orderClick,
      showSugerPhoto,
      showOrderTime,
      showClientId,
      showSubcom,
      showStatus,
      showPayType,
      salesVolume,
      salesNumber,
	  orderNumber,
      noData,
      kDialogRef,
      noticeClk,
      confirmClk,
      cofficentForm,
      accountDetail,
      $M_FormatTime,
      searchParams,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "./index.less";
</style>