<template>
  <div id="chart-card">
    <div class="amount">
      <div style="background-color: rgb(85, 85, 85)">
        <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 6 }" />
        <div
          v-show="!skeletonIsShow"
          v-if="$access('ENT_AGENT_MAIN_PAY_DAY_COUNT')"
          class="amount-top"
        >
          <div class="amount-date">
            <div
              :class="{ 'amount-date-active': amountDate === 'today' }"
              @click="amountDateHandle('today')"
            >
              今日交易
            </div>
            <div
              :class="{ 'amount-date-active': amountDate === 'yesterday' }"
              @click="amountDateHandle('yesterday')"
            >
              昨日交易
            </div>
          </div>
          <p>成交金额(元)</p>
          <a-tooltip placement="top" color="#fff">
            <template #title>
              <p style="font-size: 20px; margin-bottom: 0; color: #000">
                {{ payAmountDataAll.payAmount }}
              </p>
            </template>
            <p
              style="
                font-size: 40px;
                margin-bottom: 35px;
                color: #fff;
                width: max-content;
              "
            >
              {{ amountHandle(payAmountDataAll.payAmount)
              }}<span
                v-if="payAmountDataAll.payAmount >= 100000000"
                style="
                  font-size: 20px;
                  font-weight: 600;
                  margin-left: 5px;
                  vertical-align: middle;
                "
                >亿</span
              ><span
                v-else-if="payAmountDataAll.payAmount >= 10000000"
                style="
                  font-size: 20px;
                  font-weight: 600;
                  margin-left: 5px;
                  vertical-align: middle;
                "
                >万</span
              >
            </p>
          </a-tooltip>
          <div class="amount-list">
            <div>
              <p>交易笔数</p>
              <span>{{ payAmountDataAll.payCount }}</span>
            </div>
            <div>
              <p>退款金额(元)</p>
              <span>{{ payAmountDataAll.refundAmount }}</span>
            </div>
            <div>
              <p>退款笔数</p>
              <span>{{ payAmountDataAll.refundCount }}</span>
            </div>
          </div>
        </div>
        <div class="amount-line" />
        <a-skeleton v-show="skeletonIsShow" active :paragraph="{ rows: 6 }" />
        <div
          v-show="!skeletonIsShow"
          v-if="$access('ENT_AGENT_MAIN_PAY_TREND_COUNT')"
          class="amount-bottom"
          style="width: 100%"
        >
          <div class="echart-title">
            <div style="display: flex">
              <b style="color: #fff">趋势</b>
              <a-tooltip class="tooltip">
                <template #title>近期成交金额</template>
                <i
                  class="bi bi-info-circle"
                  style="color: rgba(255, 255, 255, 0.6)"
                />
              </a-tooltip>
            </div>
            <!--  -->
            <a-select
              v-model:value="amountSelectDate"
              class="date amount-date"
              placeholder="近30天"
              @change="amountSelectHandle"
            >
              <a-select-option value="30">近30天</a-select-option>
              <a-select-option value="7">近7天</a-select-option>
            </a-select>
          </div>
          <div v-show="!payAmountEmpty" id="pay-amount" style="width: 100%" />
          <a-empty v-show="payAmountEmpty" :image="emptyImg" />
        </div>
      </div>
    </div>
    <div class="personal">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 5 }" />
      <div v-show="!skeletonIsShow">
        <div class="before-msg">
          <p> <span>预留信息：</span >
            <a  style="color: #2691ff; margin-right: 5px"  @click="setSafeWord" >{{ safeWord ? safeWord : "未设置" }}</a >
            <a-tooltip  placement="right"  title="此信息为你在本站预留的个性信息，用以鉴别假冒、钓鱼网站。如未看到此信息，请立即停止访问并修改密码。如需修改内容请前往个人中心">
              <question-circle-outlined />
            </a-tooltip>
          </p>
          <p><span>服务商简称：</span ><span>{{ shortName ? shortName : "服务商" }}</span></p>
          <p><span>服务商邀请码：</span ><span>{{ inviteCode ? inviteCode : "" }} <copy-outlined  style="color: #2691ff;" @click="getCopy()"/></span></p>
          <p><span>拓展商户：</span >
            <QrcodeOutlined  style="color: #2691ff;" @click="getVisibleAdd(0)" />
            <copy-outlined  style="color: #2691ff;padding-left: 5px" @click="getCopyCode(0)"/>
          </p>
          <p><span>拓展代理：</span >
            <QrcodeOutlined  style="color: #2691ff;" @click="getVisibleAdd(1)"  />
            <copy-outlined  style="color: #2691ff;padding-left: 5px" @click="getCopyCode(1)"/>
          </p>
        </div>
        <div class="personal-line" />
        <div class="latest-post">
          <div class="title">
            <span>最新公告</span>
            <a style="color: #2691ff" @click="toList"
              >更多
              <right-outlined :style="{ fontSize: '12px', color: '#2691ff' }"
            /></a>
          </div>
          <div class="post-list">
            <div
              v-for="(item, index) in notice.noticeList"
              :key="index"
              class="post-item"
              @click="toDetail(item.articleId)"
            >
              <span class="title">{{ item.title }}</span>
              <span
                >{{ item ? item.createdAt.slice(0, 10) : "" }}
                <right-outlined :style="{ fontSize: '12px', color: '#707070' }"
              /></span>
            </div>
          </div>
        </div>
        <div class="personal-line" />
        <div class="quick-start">
          <p>快速开始</p>
          <ul>
            <li v-for="menu in quickMenuList" :key="menu.entId">
              <router-link :to="menu!.menuUri">{{ menu.entName }}</router-link>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="method">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 5 }" />
      <div
        v-show="!skeletonIsShow"
        v-if="$access('ENT_AGENT_MAIN_PAY_TYPE_COUNT')"
      >
        <div class="echart-title">
          <b>支付方式</b>
          <JeepayDateRangePicker
            v-model:value="payMethodDate"
            class="date"
            customDateRangeType="date"
            :allTimeIsShow="false"
            @update:value="payMethodDateHandle"
          />
        </div>
        <div
          v-show="!payMethodEmpty"
          id="pay-method"
          style="width: 100%; height: 100%"
        />
        <a-empty v-show="payMethodEmpty" :image="emptyImg" />
      </div>
    </div>
    <div class="pay-statistics">
      <a-skeleton :loading="skeletonIsShow" active :paragraph="{ rows: 5 }" />
      <div v-show="!skeletonIsShow" v-if="$access('ENT_AGENT_MAIN_PAY_COUNT')">
        <b>交易统计</b>
        <JeepayDateRangePicker
          v-model:value="payStatisticsDate"
          class="date"
          customDateRangeType="date"
          :statisticalTimeIsShow="true"
          @update:value="statisticsHandle"
        />
        <div
          v-show="!payStatisticsEmpty"
          id="pay-statistics"
          style="width: 100%; height: 100%"
        />
        <a-empty v-show="payStatisticsEmpty" :image="emptyImg" />
      </div>
    </div>
  </div>
  <a-modal
      v-model:visible="vdata.visibleAdd"
      :footer="null"
      @cancel="handleCancel"
      style="top: 30% !important;"
      wrap-class-name="full-modal"
      width="330px"
      :title="vdata.title"
      :maskClosable="false"
  >
    <div class="modal-body" style="height: 280px !important;">
      <div style="text-align: center">
        <img
            v-if="vdata.inviteUrl"
            :src='"https://api.pwmqr.com/qrcode/create/?url="+vdata.inviteUrl'
            alt=""
            style="width: 200px; height: 200px"
        >
        <div class="zfb-wx" style="margin: 10px 0">
<!--          <img src="/src/assets/svg/alipay.svg" alt="">-->
<!--          <img-->
<!--              src="/src/assets/svg/wechatpay.svg"-->
<!--              alt=""-->
<!--              style="margin: 0 5px"-->
<!--          >-->
          <span style="color: grey">支持浏览器、微信、支付宝扫码</span>
        </div>
        <a-button
            type="primary"
            size="large"
            block
            @click="vdata.visibleAdd = false"
        >
          取消扫码
        </a-button>
      </div>


    </div>

  </a-modal>
  <JeepayNoticeViewer ref="noticeViewer" />
</template>
<script lang="ts" setup>
import {
  nextTick,
  ref,
  computed,
  watch,
  getCurrentInstance,
  onMounted,
  reactive,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import * as echarts from "echarts"; // 引入图标组件
import { useUserStore } from "@/store/modules/user";
import {
  $getPayTrendCount,
  $getNumCount,
  $getPayCount,
  $getPayType,
  $getUserInfo,
  API_URL_NOTICELIST,
  req,
} from "@/api/manage";
import {
  pieEcharts,
  statisticsEcharts,
  amountEcharts,
} from "./echartsConfig.js"; // 图标配置项组件
import { Empty } from "ant-design-vue"; // 缺省图
const { $infoBox, $access } =
  getCurrentInstance()!.appContext.config.globalProperties;
const userStore = useUserStore();
// 获取到路由对象
const router = useRouter(); //这是全部路由
const safeWord = ref(); //预留信息
const shortName = ref(); //服务商简称
const inviteCode = ref(); //服务商简称
const inviteCodeUrl = ref(); //服务商简称
const agtInviteCodeUrl = ref(); //服务商简称

const vdata =  reactive({
  title:"",
  inviteUrl:"" as any,
  visibleAdd: false,
  qrCodeUrl:"" as any,
})
//公告列表页
const toList = () => {
  router.push({
    path: "/notices",
  });
};
const notice = reactive({
  noticeList: [] as any,
});
const noticeViewer = ref(); //公告详情
//设置信息
const setSafeWord = () => {
  router.push({
    path: "/currentUserinfo",
    query: { type: "msg" },
  });
};

// $data['url']='https://api.pwmqr.com/qrcode/create/?url='.urlencode($url);
// $data['downUrl']='https://api.pwmqr.com/qrcode/create/?url='.urlencode($url)."&down=1";
onMounted(() => {
  $getUserInfo().then((res) => {
    safeWord.value = res.safeWord;
    shortName.value = res.shortName;
    inviteCode.value = res.inviteCode;
    agtInviteCodeUrl.value = res.agtInviteCodeUrl;
    inviteCodeUrl.value = res.inviteCodeUrl;
  });
  reqTableDataFunc({
    pageSize: 3,
    pageNumber: 1,
  }).then((res) => {
    console.log(res);
    notice.noticeList = res.records;
  });
});
function reqTableDataFunc(params: any) {
  // 请求table接口数据
  return req.list(
    API_URL_NOTICELIST,
    Object.assign(params, { articleType: 1 })
  );
}
function handleCancel(e) {
  vdata.visibleAdd = false;
}
// 切换今日昨日金额数据
let amountDate = ref("today"); // 默认为今日
const amountDateHandle = (param) => {
  amountDate.value = param;
  numCountHandle(); // 切换后调用请求
};
let payAmountDataAll: any = ref({}); // 成交金额总数据（今天和昨天）
const payAmountGetDateData = (res) => {
  //数据赋值
  // 分转元显示
  Object.keys(res.dayCount).forEach((item) => {
    if (item == "payCount" || item == "refundCount") {
      return;
    } else {
      res.dayCount[item] = (res.dayCount[item] / 100).toFixed(2);
    }
  });
  payAmountDataAll.value = res.dayCount;
};
// 成交金额请求数据
const numCountHandle = () => {
  $getNumCount({ queryDateRange: amountDate.value })
    .then((res) => {
      payAmountGetDateData(res);
    })
    .then((err) => {
      console.log(err);
    });
};

let payMethod; // 支付方式饼图
let payMethodEmpty = ref(false); // 支付方式饼图缺省图
let payMethodDate = ref("near2now_30"); // 饼图日期查询
// 当支付方式自定义日期格式中不包含N ，则代表选择了正确的日期格式
const payMethodDateHandle = () => {
  let flag = payMethodDate.value.indexOf("N") === -1;
  if (payMethodDate.value && flag) {
    payMethodHandle(payMethodDate.value);
  }
};
// 饼图数据赋值
const payMethodGetData = (res) => {
  let payTypeData = [];
  res[0].length === 0
    ? (payMethodEmpty.value = true)
    : (payMethodEmpty.value = false);
  res[0].forEach((item) => {
    payTypeData.push({
      value: (item.typeAmount / 100).toFixed(2), // 分转元
      name: item.name,
    } as never);
  });
  pieEcharts.series[0].data = payTypeData; // 饼图数据赋值
  nextTick(() => {
    payMethod = echarts.init(
      document.getElementById("pay-method") as HTMLElement
    );
    payMethod.setOption(pieEcharts); // 数据填充
  });
};
// 饼图请求数据
const payMethodHandle = (data) => {
  $getPayType(data)
    .then((res) => {
      payMethodGetData(res);
    })
    .catch((err) => {
      console.log(err);
    });
};

let payStatistics; // 交易统计折线图
let payStatisticsDate = ref("near2now_30"); // 交易统计折线图日期查询
let payStatisticsEmpty = ref(false); // 交易统计折线图缺省图
const statisticsHandle = () => {
  let flag = payStatisticsDate.value.indexOf("N") === -1;
  if (payStatisticsDate.value && flag) {
    payStatisticsHandle(payStatisticsDate.value);
  }
};
const promise = new Promise((resolve, reject) => {});
// 交易统计折线图数据赋值
const payStatisticsGetData = (res) => {
  Object.keys(res).length === 0
    ? (payStatisticsEmpty.value = true)
    : (payStatisticsEmpty.value = false);
  statisticsEcharts.xAxis.data = res.resDateArr; // x轴日期
  let payAmountArr = [];
  res.resPayAmountArr.forEach((item) =>
    payAmountArr.push((item / 100).toFixed(2) as never)
  ); // 成交金额分转元
  statisticsEcharts.series[0].data = payAmountArr; // 成交金额
  statisticsEcharts.series[1].data = res.resPayCountArr; // 订单笔数
  let refAmountArr = [];
  res.resRefAmountArr.forEach((item) =>
    refAmountArr.push((item / 100).toFixed(2) as never)
  ); // 退款金额分转元
  statisticsEcharts.series[2].data = refAmountArr; // 退款金额
  nextTick(() => {
    payStatistics = echarts.init(
      document.getElementById("pay-statistics") as HTMLElement
    );
    payStatistics.setOption(statisticsEcharts); //  数据填充
  });
};
// 交易统计折线图请求数据
const payStatisticsHandle = (data) => {
  $getPayCount(data)
    .then((res) => {
      payStatisticsGetData(res);
    })
    .catch((err) => {
      console.log(err);
    });
};

// 今日金额折线图日期选择
const amountSelectHandle = (value: string) => {
  payAmountHandle(value);
};
let payAmount; // 金额板块折线图
let payAmountEmpty = ref(false); // 金额折线图缺省图是否展示
let amountSelectDate = ref("近30天"); // 交易统计折线图日期查询
// 成交金额 数据赋值
const payAmountGetData = (res) => {
  amountEcharts.xAxis.data = res.dateList;
  res.dateList.length === 0
    ? (payAmountEmpty.value = true)
    : (payAmountEmpty.value = false);
  let payAmountList = [];
  res.payAmountList.forEach((item) => {
    payAmountList.push((item / 100).toFixed(2) as never);
  });
  amountEcharts.series[0].data = payAmountList; // 数据赋值
  nextTick(() => {
    payAmount = echarts.init(
      document.getElementById("pay-amount") as HTMLElement
    );
    payAmount.setOption(amountEcharts);
  });
};
// 金额板块折线图请求数据
const payAmountHandle = (date) => {
  $getPayTrendCount(date)
    .then((res) => {
      payAmountGetData(res);
    })
    .catch((err) => {
      console.log(err);
    });
};

// 缺省图片的样式
const emptyImg = Empty.PRESENTED_IMAGE_SIMPLE;

// 骨架屏是否展示
let skeletonIsShow = ref(true);

// 首页骨架屏隐藏采用 promise all,只有本页面5个请求全部获得数据才会隐藏， 请求顺序依次为：成交金额， 趋势折线图， 支付方式， 交易统计
Promise.all([
  $getNumCount({ queryDateRange: amountDate.value }),
  $getPayTrendCount(30),
  $getPayType(payMethodDate.value),
  $getPayCount(payStatisticsDate.value),
])
  .then((res) => {
    skeletonIsShow.value = false; // 骨架屏取消
    payAmountGetDateData(res[0]); // 成交金额
    payAmountGetData(res[1]); // 趋势折线图
    payMethodGetData(res[2]); // 饼图
    payStatisticsGetData(res[3]); // 交易统计
  })
  .catch((error) => {
    console.log(error);
  });

// 所有图表根据屏幕大小 图表自适应
window.addEventListener("resize", () => {
  payMethod.resize();
  payStatistics.resize();
  payAmount.resize();
});

// 问候语句
const nextAge = computed(() => {
  const time = new Date();
  const hour = time.getHours();
  return hour < 9
    ? "早上好"
    : hour <= 11
    ? "上午好"
    : hour <= 13
    ? "中午好"
    : hour < 20
    ? "下午好"
    : "晚上好";
});

// 快速菜单集合
const quickMenuList: any = computed(() => {
  const result = [];

  const putResult = function (item) {
    for (let i = 0; i < item.length; i++) {
      if (item[i].menuUri && item[i].quickJump === 1) {
        result.push(item[i] as never);
      }
      if (item[i].children) {
        putResult(item[i].children);
      }
    }
  };

  putResult(userStore.userInfo["allMenuRouteTree"]);
  return result;
});

// layout传过来的值，用于监听菜单的收起与展开，此时折线图板块应跟随宽度进行变化
const props = defineProps({
  proLayoutObject: { type: Object, default: () => {} },
});

// 因为菜单的收起与展开有一定的过渡时间，所以采用了定时器
watch(
  () => props.proLayoutObject.collapsed,
  () => {
    setTimeout(() => {
      payStatistics.resize();
      payAmount.resize();
    }, 350);
  }
);
//公告详情
function toDetail(articleId) {
  noticeViewer.value.showDrawer(articleId);
}
// 金额处理 超过1000万时拼接万 超过亿时 拼接亿
const amountHandle = (amount) => {
  if (amount >= 100000000) {
    return parseFloat((amount / 100000000).toFixed(2));
  } else if (amount >= 10000000) {
    return parseFloat((amount / 10000).toFixed(2));
  } else {
    return amount;
  }
};
function getCopyCode(type = 0){

  const textarea = document.createElement('textarea');
  let  text = "拓展商户链接复制成功"
  if(type == 1){
    text = '拓展服务商链接复制成功'
    textarea.value = agtInviteCodeUrl.value;
  }else{
    textarea.value = inviteCodeUrl.value;
  }
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
  $infoBox.message.success(text)
}
function getVisibleAdd(type = 0){
    if(type == 1){
      vdata.title="拓展代理"
      vdata.inviteUrl = agtInviteCodeUrl.value
    }else{
      vdata.title="拓展商户"
      vdata.inviteUrl = inviteCodeUrl.value
    }
    console.log(vdata.inviteUrl,'vdata.inviteUrl')
  vdata.visibleAdd = true
}
async function getCopy(){
  console.log(inviteCode.value)
  // var textarea= document.createElement("textarea"); // 创建textarea对象
  // document.body.appendChild(inviteCode.value); // 添加临时实例
  // textarea.select(); // 选择实例内容
  // document.execCommand("Copy"); // 执行复制
  // document.body.removeChild(textarea); // 删除临时实例

  const textarea = document.createElement('textarea');
  textarea.value = inviteCode.value;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
  $infoBox.message.success('复制成功')
}
</script>
<style lang="less" scoped>
@import "./index.less"; // 响应式布局
// 成交金额折线图 日期选择器样式
// /deep/ .ant-select-selector {
//   background: rgba(255, 255, 255, 0.05) !important;
//   color: rgba(255, 255, 255, 0.7) !important;

// }
// /deep/ .ant-select-arrow {
//     color: rgba(255, 255, 255, 0.7) !important;
//   }
// 个人信息页标题
.personal-title {
  display: flex;
  img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 15px;
  }
  & > div {
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    p {
      font-size: 15px;
      font-weight: 600;
      margin: 0;
    }
  }
}
// 个人信息 快速开始
.quick-start {
  p {
    margin: 0;
    font-weight: bold;
    font-size: 14px;
  }
  ul {
    margin: 0;
    padding: 0;
  }
  li {
    display: inline-block;
    margin-right: 20px;
    margin-top: 20px;
  }
}

// 通用图表标题
.echart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  b {
    font-size: 14px;
    font-weight: 600;
    margin-right: 10px;
  }
  .date {
    width: 215px;
  }
}

// 交易统计图表标题
.pay-statistics {
  & > div {
    position: relative;
    & > b,
    & > .date {
      position: absolute;
      top: 30px;
      z-index: 9;
    }
    & > b {
      font-size: 14px;
      font-weight: 600;
      margin-right: 10px;
      top: 36px;
    }
    & > .date {
      width: 215px;
      right: 30px;
    }
  }
}

.tooltip {
  &:hover {
    cursor: pointer;
  }
}

// 缺省图的样式
/deep/ .ant-empty-normal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}
#chart-card .amount > div .amount-line[data-v-5391d79e] {
  border-left: none !important;
}
</style>
