<template>
  <van-nav-bar :title="title" safe-area-inset-top>
    <template #left>
      <van-icon
        :name="require('@/assets/arrow-left.svg')"
        size="24"
        @click="backPath"
      />
    </template>
  </van-nav-bar>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <div class="page_info">
      <div class="search_pannel">
        <van-tabs
          v-model:active="activeTab"
          title-active-color="#2E69EB"
          title-inactive-color="#0C1935"
          @change="handleChangeTab"
        >
          <van-tab name="bill" title="账单明细">
            <van-dropdown-menu active-color="#2E69EB">
              <van-dropdown-item
                v-model="dataForm.costCycle"
                @change="handelChange('costCycle', costCycle)"
                :title="costCycleTitle"
                :options="costCycleList"
              />
              <van-dropdown-item
                v-model="dataForm.costType"
                @change="handelChange('costType', dataForm.costType)"
                :title="costTypeTitle"
                :options="payTypeList"
              />
              <van-dropdown-item
                v-model="dataForm.status"
                @change="handelChange('status', dataForm.status)"
                :title="statusTitle"
                :options="payStatusList"
              />
            </van-dropdown-menu>
          </van-tab>
          <van-tab name="record" title="扣缴记录">
            <van-dropdown-menu active-color="#2E69EB">
              <van-dropdown-item
                v-model="dataForm.reduceDate"
                @change="handelChange('reduceDate', dataForm.reduceDate)"
                :title="reduceDateTitle"
                :options="reduceDateList"
              />
              <van-dropdown-item
                v-model="dataForm.type"
                @change="handelChange('type', dataForm.type)"
                :title="typeTitle"
                :options="payTypeList"
              />
              <van-dropdown-item
                v-model="dataForm.operator"
                @change="handelChange('operator', dataForm.operator)"
                :title="operatorTitle"
                :options="operatorList"
              />
            </van-dropdown-menu>
          </van-tab>
        </van-tabs>
      </div>
      <van-row align="center" class="list_total">
        <van-col>共有</van-col>
        <v-count-up
          :end-val="dataList.length"
          class="count_up"
          :options="{ separator: ',' }"
        />
        <van-col>条记录</van-col>
      </van-row>
      <template v-if="activeTab == 'bill'">
        <div class="info_list" key="bill">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            :error="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-checkbox-group
              ref="checkboxGroup"
              v-model="checkedCollapse"
              style="width: 100%"
            >
              <div
                v-for="item in dataList"
                :key="item.id"
                class="list_item"
                style="flex-direction: row; align-items: baseline"
              >
                <van-checkbox
                  :name="item.id"
                  :disabled="item.status == 1"
                  style="margin-left: 16px"
                ></van-checkbox>
                <van-collapse
                  v-model="activeCollapse"
                  :border="false"
                  style="flex: 1"
                  accordion
                >
                  <van-collapse-item :name="item.id">
                    <template #title>
                      <van-row class="collapse_title">
                        <van-col class="label"
                          >{{
                            `${
                              dict_filter(item.costType, "payTypeList")[
                                "dictLabel"
                              ]
                            }`
                          }}：</van-col
                        >
                        <van-col style="font-weight: 600; color: #fa5555"
                          >￥{{
                            (parseInt(item.amount * 100) / 100).toFixed(2)
                          }}</van-col
                        >
                      </van-row>
                    </template>
                    <div class="collapse_info">
                      <van-row
                        class="info_item"
                        v-for="ele in item.billLists"
                        :key="ele.id"
                      >
                        <template
                          v-if="
                            item.costType == 'Water' || item.costType == 'Elec'
                          "
                        >
                          <van-col
                            >{{ ele.equipName }}费用：￥{{
                              (parseInt(ele.amount * 100) / 100).toFixed(2)
                            }}</van-col
                          >
                        </template>
                        <template v-if="item.costType == 'PropertyFee'">
                          <van-col
                            >{{
                              `${
                                dict_filter(ele.costType, "propertyTypeList")[
                                  "dictLabel"
                                ]
                              }`
                            }}：￥{{
                              (parseInt(ele.amount * 100) / 100).toFixed(2)
                            }}</van-col
                          >
                        </template>
                      </van-row>
                    </div>
                  </van-collapse-item>
                </van-collapse>
              </div>
            </van-checkbox-group>
          </van-list>
        </div>
      </template>
      <template v-if="activeTab == 'record'">
        <div class="info_list" key="record">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            :error="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="item in dataList"
              :key="item.id"
              class="list_item reduce_record"
              style="padding: 12px 16px"
            >
              <van-row
                align="center"
                class="reduce_type"
                :style="{
                  'background-color': `${
                    dict_filter(item.type, 'payTypeList')['color']
                  }`,
                }"
              >
                <van-col>{{
                  `${dict_filter(item.type, "payTypeList")["dictLabel"]}`
                }}</van-col>
              </van-row>
              <van-row class="header">
                <van-col>{{ item.tenantInfo && item.tenantInfo.name }}</van-col>
              </van-row>
              <van-row>
                <van-col>扣缴金额：￥</van-col>
                <van-col style="color: #fa5555">{{
                  (parseInt(item.amount * 100) / 100).toFixed(2)
                }}</van-col>
              </van-row>
              <van-row>
                <van-col>账户余额：￥</van-col>
                <van-col>{{
                  (parseInt(item.surplus * 100) / 100).toFixed(2)
                }}</van-col>
              </van-row>
              <van-row>
                <van-col>租户电话：</van-col>
                <van-col>{{ item.tenantInfo && item.tenantInfo.tel }}</van-col>
              </van-row>
              <van-row>
                <van-col>操作人：</van-col>
                <van-col>{{ item.createName }}</van-col>
              </van-row>
              <van-row>
                <van-col>扣缴时间：</van-col>
                <van-col>{{ item.createDate }}</van-col>
              </van-row>
            </div>
          </van-list>
        </div>
      </template>
    </div>
  </van-pull-refresh>
  <template v-if="role == 'admin'">
    <van-tabbar v-model="activeTabBar" class="tab_bar">
      <van-tabbar-item @click="handleChangeTabBar(1)">预存</van-tabbar-item>
      <van-tabbar-item @click="handleChangeTabBar(2)">补助</van-tabbar-item>
      <van-tabbar-item @click="handleChangeTabBar(3)">退费</van-tabbar-item>
    </van-tabbar>
  </template>
  <template v-if="role == 'Tenant' && activeTab == 'record'">
    <van-submit-bar class="save_btn">
      <template #button>
        <van-button block type="primary" @click="handleClick('fee')">
          预存充值
        </van-button>
      </template>
    </van-submit-bar>
  </template>
  <template
    v-if="role == 'Tenant' && activeTab == 'bill' && checkedCollapse.length"
  >
    <van-submit-bar
      :price="parseInt(amount * 100)"
      button-text="立即支付"
      button-color="#2E69EB"
      @submit="handleClick('bill')"
    >
      <van-checkbox v-model="checkedAll" :disabled="disabledAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </template>
  <van-popup
    v-model:show="showPayPopup"
    position="bottom"
    :safe-area-inset-bottom="true"
    :overlay-style="{ background: 'unset' }"
    class="popup_info"
  >
    <component
      :is="currComponent"
      :pay-info="payInfo"
      @close="close"
      v-if="showPayPopup"
    ></component>
  </van-popup>
</template>
<script>
import Api from "@/utils/api";
import { isEmpty, getDictDataList } from "@/utils/index";
import VCountUp from "../CountUp";
import payFee from "./fee.vue";
import payBill from "./pay.vue";
export default {
  components: {
    "v-count-up": VCountUp,
    "pay-fee": payFee,
    "pay-bill": payBill,
  },
  data() {
    return {
      showPayPopup: false,
      payInfo: {},
      currComponent: "",
      role: "",
      title: "",
      disabledAll: false,
      showPopup: false,
      popupTitle: "",
      flag: false,
      checkedAll: false,
      checkedCollapse: [],
      amount: 0,
      activeTab: "",
      activeTabBar: 0,
      activeCollapse: "",
      costCycleTitle: "计费周期",
      costTypeTitle: "缴费类型",
      statusTitle: "支付状态",
      reduceDateTitle: "扣缴时间",
      typeTitle: "扣缴类型",
      operatorTitle: "操作人",
      costCycleList: [],
      payStatusList: [],
      reduceDateList: [],
      payTypeList: [],
      operatorList: [],
      propertyList: [],
      dataForm: {
        tenantId: "",
        costCycle: "2022-08",
        costType: "",
        status: "",
        type: "",
        reduceDate: "",
        operator: "",
        page: 1,
        limit: 10,
      },
      dataList: [],
      loading: false,
      refreshing: false,
      finished: false,
    };
  },
  watch: {
    checkedCollapse: {
      handler(newval, oldval) {
        if (newval.length == this.dataList.length) {
          if (this.dataList.length) {
            this.checkedAll = true;
          }
        } else {
          this.checkedAll = false;
        }
        this.amount = 0;
        this.checkedCollapse.forEach((item) => {
          this.amount += this.dataList.find((ele) => ele.id == item).amount;
        });
      },
      deep: true,
    },
    checkedAll: {
      handler(newval, oldval) {
        if (newval) {
          this.checkedCollapse = [];
          this.dataList.forEach((item) => {
            this.checkedCollapse.push(item.id);
          });
        } else {
          if (this.checkedCollapse.length == this.dataList.length) {
            this.checkedCollapse = [];
          }
        }
      },
      deep: true,
    },
  },
  created() {
    this.role = localStorage.getItem("role");
    this.title = this.$route.query.tenantName;
    this.dataForm.tenantId = this.$route.query.tenantId;
    this.dataForm.costCycle =
      this.$route.query.costCycle || this.dataForm.costCycle;
    this.activeTab = this.$route.query.activeTab;
    this.getPayStatusList();
    this.getPayTypeList();
    this.getPropertyTypeList();
  },
  methods: {
    getPayStatusList() {
      this.payStatusList = getDictDataList("PayStatus");
      this.payStatusList.forEach((item) => {
        item.text = item.dictLabel;
        item.value = item.dictValue;
      });
    },
    getPayTypeList() {
      this.payTypeList = getDictDataList("PayType");
      this.payTypeList.forEach((item) => {
        item.text = item.dictLabel;
        item.value = item.dictValue;
        if (item.value == "PreStorage") {
          item.color = "#30D3A2";
        }
        if (item.value == "Subsidy") {
          item.color = "#09C700";
        }
        if (item.value == "Refund") {
          item.color = "#FA5555";
        }
        if (item.value == "Water") {
          item.color = "#FF9C27";
        }
        if (item.value == "Elec") {
          item.color = "#FF9C27";
        }
        if (item.value == "PropertyFee") {
          item.color = "#FF9C27";
        }
        if (item.value == "CancelSubsidy") {
          item.color = "#ED3A25";
        }
      });
    },
    getPropertyTypeList() {
      this.propertyTypeList = getDictDataList("PropertyType");
    },
    dict_filter(val, list) {
      if (isEmpty(val)) {
        return "";
      }
      return this[list].find((item) => item.dictValue == val);
    },
    onLoad() {
      setTimeout(async () => {
        if (this.refreshing) {
          this.dataList = [];
          this.refreshing = false;
        }
        await this.getDataList();
        this.dataForm.page++; // 分页数加一
      }, 100);
    },
    onRefresh() {
      // 清空列表数据
      this.checkedAll = false;
      this.checkedCollapse = [];
      this.activeCollapse = "";
      this.amount = 0;
      this.finished = false;
      this.dataList = [];
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.dataForm.page = 1; // 分页数赋值为1
      this.onLoad();
    },
    // 获取列表数据方法
    getDataList() {
      if (this.activeTab == "bill") {
        this.getRentBillList();
      }
      if (this.activeTab == "record") {
        this.getReduceRecordList();
      }
    },
    getRentBillList() {
      Api.rentBillDetail(this.dataForm).then((res) => {
        if (res.code == 0) {
          if (res.data) {
            if (res.data.length == 0) {
              // 判断获取数据条数若等于0
              this.dataList = []; // 清空数组
              this.finished = true; // 停止加载
            }
            res.data.forEach((item, index) => {
              item.id = "index_" + index;
            });
            // 若数据条数不等于0
            this.dataList.push(...res.data); // 将数据放入list中
            this.loading = false; // 加载状态结束
            this.disabledAll = this.dataList.every((item) => item.status == 1);
            // 如果list长度大于等于总数据条数,数据全部加载完成
            if (this.dataList.length >= res.data.length) {
              this.finished = true; // 结束加载状态
            }
          } else {
            // 判断获取数据条数若等于0
            this.dataList = []; // 清空数组
            this.finished = true; // 停止加载
          }
        } else {
          this.loading = false; // 加载状态结束
          this.finished = true; // 停止加载
        }
      });
    },
    getReduceRecordList() {
      Api.reduceRecordList(this.dataForm).then((res) => {
        if (res.code == 0) {
          if (res.data) {
            if (res.data.list.length == 0) {
              // 判断获取数据条数若等于0
              this.dataList = []; // 清空数组
              this.finished = true; // 停止加载
            }
            // 若数据条数不等于0
            this.dataList.push(...res.data.list); // 将数据放入list中
            this.loading = false; // 加载状态结束

            // 如果list长度大于等于总数据条数,数据全部加载完成
            if (this.dataList.length >= res.data.total) {
              this.finished = true; // 结束加载状态
            }
          } else {
            // 判断获取数据条数若等于0
            this.dataList = []; // 清空数组
            this.finished = true; // 停止加载
          }
        } else {
          this.loading = false; // 加载状态结束
          this.finished = true; // 停止加载
        }
      });
    },
    handelChange(type, val) {
      if (type == "costType") {
        // 这里打印出来的值就是我们想要的text
        this.costTypeTitle = this.payTypeList.filter(
          (item) => item.value === val
        )[0].text;
      }
      if (type == "type") {
        // 这里打印出来的值就是我们想要的text
        this.typeTitle = this.payTypeList.filter(
          (item) => item.value === val
        )[0].text;
      }
      if (type == "status") {
        // 这里打印出来的值就是我们想要的text
        this.typeTitle = this.payStatusList.filter(
          (item) => item.value === val
        )[0].text;
      }
      this.onRefresh();
    },
    handleChangeTab() {
      this.onRefresh();
    },
    handleChangeTabBar(val) {
      let popupTitle = "";
      let payType = "";
      if (val == 1) {
        popupTitle = "预存";
        payType = "PreStorage";
      }
      if (val == 2) {
        popupTitle = "补助";
        payType = "Subsidy";
      }
      if (val == 3) {
        popupTitle = "退费";
        payType = "Refund";
      }
      this.currComponent = "pay-fee";
      this.payInfo = {
        payType: payType,
        tenantId: this.dataForm.tenantId,
        popupTitle: popupTitle,
      };
      this.showPayPopup = true;
    },
    handleClick(type) {
      if (type == "fee") {
        this.currComponent = "pay-fee";
        this.payInfo = {
          payType: "PreStorage",
          tenantId: this.dataForm.tenantId,
          popupTitle: "预存",
        };
      }
      if (type == "bill") {
        let billIds = [];
        this.checkedCollapse.forEach((item) => {
          let tempBillList = [];
          tempBillList = this.dataList.find((ele) => ele.id == item).billLists;
          tempBillList.forEach((bill) => {
            billIds.push(bill.id);
          });
        });
        this.currComponent = "pay-bill";
        this.payInfo = {
          tenantId: this.dataForm.tenantId,
          amount: this.amount,
          billIds: billIds,
        };
      }
      this.showPayPopup = true;
    },
    close() {
      this.payInfo = {};
      this.showPayPopup = false;
    },
    backPath() {
      this.$router.back();
    },
  },
};
</script>
<style lang="scss" scoped>
.page_info {
  height: 100%;
  .search_pannel {
    background: #ffffff;
    /deep/ {
      .van-tabs__line {
        --van-tabs-bottom-bar-color: #2e69eb;
      }
      .van-dropdown-menu__bar {
        --van-gray-4: #999999;
        --van-dropdown-menu-title-font-size: 15px;
        --van-dropdown-menu-title-text-color: #0c1935;
        --van-dropdown-menu-box-shadow: 0;
      }
      .van-dropdown-item__option {
        .van-cell__title,
        .van-cell__value {
          font-size: 14px;
        }
      }
    }
  }
  .list_total {
    padding: 0 16px;
    margin: 8px 0;
    display: flex;
    text-align: left;
    .van-col {
      height: 16px;
      font-size: 12px;
      font-weight: 400;
      color: #999999;
      line-height: 16px;
    }
    .count_up {
      font-size: 16px;
      font-weight: 500;
      color: #fa5555;
      margin: 0 2px;
    }
  }
  .info_list {
    padding: 0 16px;
    .list_item {
      background: #ffffff;
      box-shadow: 0px 0px 10px 0px rgba(153, 153, 153, 0.15);
      border-radius: 4px;
      margin-bottom: 12px;
      padding: 6px 0;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      position: relative;
      &:nth-last-child(1) {
        margin-bottom: 0;
      }

      .list_btn {
        position: absolute;
        bottom: 15px;
        right: 12px;
        .van-button {
          &:nth-child(2) {
            margin: 0 12px;
          }
        }
      }
      .collapse_title {
        .label {
          font-size: 16px;
          font-weight: 500;
          color: #666666;
        }
      }
      .collapse_info {
        .info_item {
          text-align: left;
          margin-bottom: 2px;
          .van-col {
            height: 20px;
            font-size: 14px;
            color: #9da0ac;
            line-height: 20px;
          }
          &:nth-last-child(1) {
            margin: 0;
          }
        }
      }
      /deep/ {
        .van-cell:after {
          border-bottom: 0;
        }
        .van-collapse-item__content {
          padding: 0 16px;
        }
      }
    }
    .reduce_record {
      .van-col {
        height: 18px;
        font-size: 14px;
        color: #999999;
        line-height: 18px;
        margin-bottom: 4px;
        &:nth-last-child(1) {
          margin-bottom: 0;
        }
      }
      .header {
        .van-col {
          font-size: 16px;
          color: #0c1935;
          line-height: 22px;
          margin-bottom: 8px;
        }
      }
    }
    .reduce_type {
      position: absolute;
      top: 0;
      right: 0;
      height: 24px;
      padding: 0 12px;
      border-radius: 0px 4px 0px 10px;
      .van-col {
        font-size: 12px;
        font-weight: 400;
        color: #ffffff;
        line-height: 16px;
      }
    }
  }
}
</style>
<style lang="scss">
.tab_bar {
  /deep/ {
    .van-tabbar-item {
      color: #2e69eb;
      font-size: 14px;
      font-weight: 600;
    }
  }
}
.popup_info {
  height: auto;
  box-shadow: 0px -10px 20px 0px rgba(27, 32, 38, 0.1);
  border-radius: 20px 20px 0px 0px;
}
</style>