import {
  getAddressTxCountOrigin,
  getAddrTxList_another,
  getMakerAddr,
  getMakerAddrCount,
  getVoterAddr,
  getVoterAddrCount,
  yccApi,
} from "@/service/api";
import { iExecAccount, iPack, iVote } from "@/types/address";
import { icustomized2Tx } from "@/types/trade";
import Rpc from "@/utils/Rpc";
import Vue from "vue";
import { getTxByHashes } from "ycc-api/dist/cmjs/service/blockDetail";
import { getConsensusList } from "@/utils/consensus";

export default Vue.extend({
  data() {
    return {
      value: "",
      focusedTab: "txRecord",
      total1: 0,
      pages: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      pages3: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      pages2: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectedOption: "1",
      loadingTxRecordTable: false,
      txRecordList: [] as icustomized2Tx[],
      voteList: [] as iVote[],
      selectedExecer: "",
      execAccount: [] as iExecAccount[],
      packList: [] as iPack[],
      loadingVote: false,
      loadingPack: false,
      selectedTxRecordFilterValue: "all",
    };
  },
  watch: {
    "$route.query.address"() {
      this.getAllExecBalance();
      this.getTxList();
      this.getMaker();
      this.getVoter();
    },
    selectedTxRecordFilterValue(newValue) {
      this.pages.currentPage = 1;
      this.getTxList();
    },
  },
  mounted() {
    this.getAllExecBalance();
    this.getTxList();
    this.getMaker();
    this.getVoter();
  },
  computed: {
    txRecordFilterOptionList() {
      return [
        {
          name: this.$t("lang.trade.title"),
          value: "all",
        },
        {
          name: this.$t("lang.trade.filterSucceedTx"),
          value: "filterSucceedTx",
        },
        {
          name: this.$t("lang.trade.filterFailedTx"),
          value: "filterFailedTx",
        },
        {
          name: this.$t("lang.trade.filterSentTx"),
          value: "filterSentTx",
        },
        {
          name: this.$t("lang.trade.filterReceivedTx"),
          value: "filterReceivedTx",
        },
      ];
    },
    tabList() {
      return [
        {
          name: this.$t("lang.trade.txRecord"),
          value: "txRecord",
        },
        {
          name: this.$t("lang.address.votingRecord"),
          value: "votingRecord",
        },
        {
          name: this.$t("lang.address.packingRecord"),
          value: "packingRecord",
        },
      ];
    },
    optionList() {
      return [
        { name: this.$t("lang.trade.txRecord"), value: "1" },
        { name: this.$t("lang.trade.consensusNode"), value: "2" },
      ];
    },
    execerOptionsList(): { name: string; value: string }[] {
      return this.execAccount.map((i) => ({
        name: i.execer,
        value: i.execer,
      }));
    },
    balance(): number {
      return (
        this.execAccount.find((i) => i.execer === this.selectedExecer) || {
          account: {
            balance: 0,
          },
        }
      )?.account?.balance;
    },
    frozen(): number {
      return (
        this.execAccount.find((i) => i.execer === this.selectedExecer) || {
          account: {
            frozen: 0,
          },
        }
      )?.account?.frozen;
    },
    txRecordReqParams(): any {
      switch (this.selectedTxRecordFilterValue) {
        case "all":
          return [
            {
              match_one: [
                {
                  key: "from",
                  value: this.$route.query.address as string,
                },
                {
                  key: "to",
                  value: this.$route.query.address as string,
                },
              ],
              match: [],
            },
          ];
        case "filterSucceedTx":
          return [
            {
              match_one: [
                {
                  key: "from",
                  value: this.$route.query.address as string,
                },
                {
                  key: "to",
                  value: this.$route.query.address as string,
                },
              ],
              match: [
                {
                  query: {
                    match_one: [
                      {
                        key: "is_para",
                        value: true,
                      },
                      {
                        key: "success",
                        value: true,
                      },
                    ],
                  },
                },
              ],
            },
          ];
        case "filterFailedTx":
          return [
            {
              match_one: [
                {
                  key: "from",
                  value: this.$route.query.address as string,
                },
                {
                  key: "to",
                  value: this.$route.query.address as string,
                },
              ],
              match: [
                {
                  key: "success",
                  value: false,
                },
                {
                  key: "is_para",
                  value: false,
                },
              ],
            },
          ];
        case "filterSentTx":
          return [
            {
              match_one: [
                {
                  key: "from",
                  value: this.$route.query.address as string,
                },
              ],
              match: [],
            },
          ];
        case "filterReceivedTx":
          return [
            {
              match_one: [
                {
                  key: "to",
                  value: this.$route.query.address as string,
                },
              ],
              match: [],
            },
          ];
        default:
          return [];
      }
    },
  },
  methods: {
    getAllExecBalance() {
      Rpc.getAllExecBalance(this.$route.query.address as string).then((res) => {
        if (res.error === null) {
          this.execAccount = res.result.execAccount;
          this.selectedExecer = res.result.execAccount[0].execer;
        }
      });
    },
    checkGroup(arr: icustomized2Tx[]) {
      arr.map((current, index) => {
        if (current.group_count > 1) {
          current.tradeG = 1; //0-非交易组，1-交易组，3-交易组末条, 2-交易组首条
          // current.tradeG = (current.tx.fee === 0 && arr[index-1].tx.fee!==0)? 2 : 1
          if (current.fee !== 0) {
            current.tradeG = 2;
          } else {
            if (index < arr.length) {
              console.log(index);
              current.tradeG = arr[index].next === "" ? 3 : 1;
            } else {
              current.tradeG = 3;
            }
          }
        } else {
          current.tradeG = 0;
        }
      });
      return arr;
    },
    getTxList() {
      this.loadingTxRecordTable = true;
      getAddressTxCountOrigin(this.txRecordReqParams).then((res) => {
        if (res.error === null) {
          this.total1 = res.result;
          this.pages.total = res.result;
          // this.pages.total = res.result > 10000 ? 10000 : res.result;
          getAddrTxList_another(
            this.pages.currentPage,
            this.pages.pageSize,
            this.txRecordReqParams[0]
          ).then((res) => {
            if (res.error === null) {
              this.txRecordList = this.checkGroup(res.result);
              this.loadingTxRecordTable = false;
            }
          });
        }
      });
    },
    setValue(v: string) {
      this.value = v;
    },
    sizeChange3(size: number) {
      this.pages3.pageSize = size;
      this.pageChange3(1);
    },
    pageChange3(page: number) {
      this.pages3.currentPage = page;
      getMakerAddr(
        this.$route.query.address as string,
        this.pages3.currentPage,
        this.pages3.pageSize
      ).then((res) => {
        if (res.error === null) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          this.packList = res.result.map((i: any) => ({
            ...i,
            sender: i.from,
            receiver: i.to,
            time: i.block_time,
          }));
          const txHashes = res.result.map((i: any) => i.hash);
          this.setMakerReward(txHashes);
        }
      });
    },
    sizeChange2(size: number) {
      this.pages2.pageSize = size;
      this.pageChange2(1);
    },
    pageChange2(page: number) {
      this.pages2.currentPage = page;
      getVoterAddr(
        this.$route.query.address as string,
        this.pages2.currentPage,
        this.pages2.pageSize
      ).then((res) => {
        if (res.error === null) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          this.voteList = res.result.map((i: any) => ({
            ...i,
            sender: i.from,
            receiver: i.to,
            time: i.block_time,
          }));
        }
      });
    },
    sizeChange(size: number) {
      this.pages.pageSize = size;
      this.pageChange(1);
    },
    pageChange(page: number) {
      this.pages.currentPage = page;
      this.loadingTxRecordTable = true;
      getAddrTxList_another(
        this.pages.currentPage,
        this.pages.pageSize,
        this.txRecordReqParams[0]
      ).then((res) => {
        if (res.error === null) {
          this.txRecordList = this.checkGroup(res.result);
          this.loadingTxRecordTable = false;
        }
      });
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    groupCellName(val: any) {
      switch (val.row.tradeG) {
        case 0:
          return "";
        case 1:
          return "tx-middle";
        case 2:
          return "tx-start";
        case 3:
          return "tx-end";
        default:
          return "";
      }
    },
    setVoteReward(txHashes: string[]) {
      getTxByHashes("ycc", yccApi, txHashes).then((txRes) => {
        const list = txRes
          .map((i: any, index: number) => {
            return {
              txHash: txHashes[index],
              receipt: i.receipt,
            };
          })
          .map((i: any) => {
            const res = getConsensusList([i]);
            return {
              txHash: i.txHash,
              reward: res
                .filter((m) => m.type === "vote")
                .reduce((p, c) => {
                  return p + c.reward;
                }, 0),
            };
          });

        list.forEach((item: { txHash: string; reward: number }) => {
          const the = this.voteList.find((i) => i.hash === item.txHash);
          if (the) {
            the.reward = item.reward;
          }
        });
        this.voteList = [...this.voteList];
      });
    },
    setMakerReward(txHashes: string[]) {
      getTxByHashes("ycc", yccApi, txHashes).then((txRes) => {
        const list = txRes
          .map((i: any, index: number) => {
            return {
              txHash: txHashes[index],
              receipt: i.receipt,
            };
          })
          .map((i: any) => {
            const res = getConsensusList([i]);
            return {
              txHash: i.txHash,
              reward: res
                .filter((m) => m.type === "pack")
                .reduce((p, c) => {
                  return p + c.reward;
                }, 0),
            };
          });

        list.forEach((item: { txHash: string; reward: number }) => {
          const the = this.packList.find((i) => i.hash === item.txHash);
          if (the) {
            the.reward = item.reward;
          }
        });
        this.packList = [...this.packList];
      });
    },
    getMaker() {
      getMakerAddrCount(this.$route.query.address as string).then((res) => {
        if (res.error === null) {
          this.pages3.total = res.result;
          getMakerAddr(
            this.$route.query.address as string,
            this.pages3.currentPage,
            this.pages3.pageSize
          ).then((res) => {
            if (res.error === null) {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              const txHashes = res.result.map((i: any) => i.hash);
              this.packList = res.result.map((i: any) => ({
                ...i,
                sender: i.from,
                receiver: i.to,
                time: i.block_time,
              }));
              this.setMakerReward(txHashes);
            }
          });
        }
      });
    },
    getVoter() {
      getVoterAddrCount(this.$route.query.address as string).then((res) => {
        if (res.error === null) {
          this.pages2.total = res.result;
          getVoterAddr(
            this.$route.query.address as string,
            this.pages2.currentPage,
            this.pages2.pageSize
          ).then((res) => {
            if (res.error === null) {
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              this.voteList = res.result.map((i: any) => ({
                ...i,
                sender: i.from,
                receiver: i.to,
                time: i.block_time,
              }));
            }
          });
        }
      });
    },
  },
});
