<template>
  <!-- <div class="mySubsidies">mySubsidies</div> -->

  <view class="page mySubsidies" @click="clickMySubsidies">
    <view class="top_view">
      <view class="del_view" v-if="isDel">
        <view class="del del_fixed">
          <uni-row :gutter="20" class="buttom_row">
            <uni-col :span="0.5">
              <button @click="isDel = !isDel">
                <uni-icons :type="'closeempty'" size="15" />
              </button>
            </uni-col>
            <uni-col :span="0.5">
              <button type="primary" size="mini" @click="selectAll">
                <text>
                  {{ "全 选" }}
                </text>
              </button>
            </uni-col>
            <uni-col :span="0.5">
              <button type="default" size="mini" @click="unSelectAll">
                <text>
                  {{ "全不选" }}
                </text>
              </button>
            </uni-col>
            <uni-col class="confirm_del" :span="0.5" :push="confirmDelPush">
              <button type="warn" size="mini" @click="confirmDel">
                <text>
                  {{ "确认删除" }}
                </text>
              </button>
            </uni-col>
          </uni-row>
        </view>
        <view class="del" />
      </view>
      <view class="tip" v-else-if="subsidyList.length !== 0">
        <uni-notice-bar :showIcon="false" :scrollable="false" :showClose="true" text="点击以查看及更改补贴记录，长按以删除补贴记录" />
      </view>
    </view>
    <view class="page-body">
      <view v-if="subsidyList.length !== 0">
        <uni-list class="uset-apply-list">
          <uni-list-item class="arctile-list" ellipsis="1" v-for="(subsidiesItem, subsidiesIndex) in subsidyList"
            :clickable="true" :showSwitch="isDel" :key="'arct-' + subsidiesIndex"
            :title="dictLists['subsidy_type'][subsidiesItem.typeId]" :note="'受助主体: ' + subsidiesItem.baseName"
            :rightText="'补贴金额: ' + subsidiesItem.amoun + ' /元'" :data-subsidiesitemx="subsidiesItem" :switchChecked="switchedList[subsidiesItem.id] !== undefined &&
              switchedList[subsidiesItem.id] !== null &&
              switchedList[subsidiesItem.id] === true
              " @touchstart.native="switchTrue()" @touchend.native="checked()" @mousedown.native="switchTrue()"
            @mouseup.native="checked()" @click.native="clicked" @switchChange="switchChange">
          </uni-list-item>
          <uni-load-more v-if="loadMoreIf && subsidyList.length > 18" :style="style" iconType="auto" :status="status"
            :contentText="contentText" />
        </uni-list>
      </view>
      <view v-else class="empty">
        <text>暂无补贴数据</text>
      </view>
    </view>
  </view>
</template>

<script>
import { listSubsidy, delSubsidy } from "@/api/lef/subsidy";

export default {
  name: "mySubsidies",
  components: {},
  props: {},
  data() {
    return {
      // 无限加载组件状态
      status: "more",
      // 无限加载组件样式
      style: "",
      // 无限加载组件显隐
      loadMoreIf: true,
      // 确认删除是否点击
      isClConDel: false,

      // 字典对象及字典对应数据id列表
      dictLists: {},
      // 确认删除是否点击
      isClConDel: false,
      // modal提示显隐计数
      modalhideCount: 0,
      // 当前选定的id是否为待删除
      isIdDel: false,
      // 控制贷款申请项点击反馈是否为路由
      clickNavigate: true,
      // 已选定待删除数组
      switchedList: [],
      // 确认删除按钮向右偏移数
      confirmDelPush: 4,
      // 长按计数器
      touchstartTimeOut: {},
      // 计数器
      touchCount: 0,
      // 控制删除相关控件
      isDel: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 用户贷款申请列表数据
      subsidyList: [],
      // 查询参数
      queryParams: {
        // 查询条目数
        pageSize: 10,
        baseName: null,
        baseid: null,
        time: null,
        typeId: null,
        amoun: null,
      },
      // 无限加载组件各个状态对应字符串
      contentText: {
        contentdown: "查看更多",
        contentrefresh: "加载中",
        contentnomore: "暂无更多",
      },
      // 保险条目数
      total: 0,
      // 每次上拉时加载条目数的增值
      loadAddCount: 8,
      // 查询条目与结果条目数是否相等
      equals: false,
    };
  },
  computed: {},
  methods: {
    // 返回此页面后需展示的用户操作反馈提示信息
    getMsg(yes_no) {
      if (yes_no === true) {
        this.$modal.msgSuccess("新增成功");
      } else if (yes_no === false) {
        this.$modal.msgSuccess("修改成功");
      } else if (yes_no === undefined) {
      } else {
        this.$modal.msgError("提交失败");
      }
    },
    // 确认删除按钮点击事件
    confirmDel() {
      this.isClConDel = true;
      this.saveIds().then((ids) => {
        if (ids.length === 0) {
          this.$modal.msgError("请选择需删除的条目");
        } else {
          this.$modal
            .confirm("是否确认删除？")
            .then(() => {
              return delSubsidy(ids);
            })
            .then(() => {
              this.getList();
            })
            .catch(() => { })
            .then(() => {
              this.$modal.msgSuccess("删除成功");
            })
            .catch(() => { });
        }
      });
    },
    // 存放需刪除的ids
    async saveIds() {
      let idList = [];
      this.switchedList.forEach((element, index) => {
        if (element === true) {
          idList.push(index);
        }
      });
      this.ids = idList;
      return idList;
    },
    // 取消全选按钮点击事件
    unSelectAll() {
      this.switchedList.forEach((element, index) => {
        this.isIdDel = false;
        this.setABIds(index);
      });
    },
    // 选择全部按钮点击事件
    selectAll() {
      this.subsidyList.forEach((element, index) => {
        this.isIdDel = true;
        this.setABIds(element.id);
      });
    },
    // 开关切换事件
    switchChange(e) {
      this.clickNavigate = false;
      this.isIdDel = e.value;
    },
    // 切换删除功能视图显隐属性
    changeDelShow() {
      this.touchCount++;
      this.isDel = !this.isDel;
    },
    // 列表项鼠标按下事件（长按开始）
    switchTrue() {
      this.touchstartTimeOut = setTimeout(() => {
        this.changeDelShow();
        this.clickNavigate = false;
      }, 888);
    },
    // 列表项鼠标抬起事件（长按结束）
    checked() {
      clearTimeout(this.touchstartTimeOut);
    },
    /** 查询用户贷款申请列表 */
    getList() {
      this.status = "loading";

      this.loading = true;
      listSubsidy(this.queryParams).then((response) => {
        let list = [];
        response.rows.forEach((element, index) => {
          list = element.rows.rows;
        });
        this.subsidyList = list;
        this.total = response.total;
        this.loading = false;
        list.forEach((element, index) => {
          this.$set(this.subsidyList[index], "id", element.subsidyId);
        });
        this.status =
          this.total > this.queryParams.pageSize ? "more" : "noMore";
      });
    },
    // 设置列表多选开关状态
    setABIds(key) {
      this.$set(this.switchedList, [key], this.isIdDel);
    },
    // 列表项鼠标点击事件
    clicked(e) {
      let item = e.currentTarget.dataset.subsidiesitemx;
      if (this.clickNavigate === true) {
        item.link = "pages/formPages/subsidy/subsidyForm/index?id=" + item.id;
        item.openType = "navigateTo";
        this.navigator(item);
      } else {
        this.setABIds(item.id);
      }
      this.clickNavigate = true;
    },
    // 贷款修改表单路由
    navigator(item, isNew) {
      if (this.$auth.hasRole("admin") || !this.$auth.hasRole("enterprise")) {
        this.$modal.confirm("非主体用户无法拥有主体！").then(() => { });
      } else {
        this.$tab[item.openType]("/" + item.link).then((res) => {
          if (res[0] !== null) {
            this.$modal.showToast("模块建设中~");
          }
        });
      }
    },
    // 点击页面隐藏提示
    clickMySubsidies() {
      if (this.isClConDel === true) {
        this.modalhideCount++;
        if (this.modalhideCount % 2 === 0) {
          this.hideModal();
          this.isClConDel = false;
          this.modalhideCount = 0;
        }
      }
    },
    // 隐藏提示显示
    hideModal() {
      this.$modal.hideMsg();
    },
    // 调用字典数据函数的箭头函数
    async initializeDict() {
      this.dictByType("subsidy_type");
    },
    // 获取相应字典字段的键值数据
    dictByType(type) {
      this.getDicts(type).then((response) => {
        let dicts = [];
        for (let dict of response.data) {
          dicts[parseInt(dict.dictValue)] = dict.dictLabel;
        }
        this.$set(this.dictLists, type, dicts);
      });
    },
    // 加载更多触发函数
    loadMore(diff) {
      this.$set(
        this.queryParams,
        "pageSize",
        this.queryParams.pageSize + this.loadAddCount - (diff > 0 ? diff : 0)
      );
    },
    // 上拉时判断是否加载更多
    changeParamPageSize() {
      if (this.queryParams.pageSize + this.loadAddCount <= this.total) {
        this.loadMore();
      } else if (!this.equals) {
        this.loadMore(this.queryParams.pageSize + 3 - this.total);
        this.equals = true;
      } else {
        this.queryParams.pageSize--;
        this.queryParams.pageSize++;
      }
    },
  },
  watch: {
    // 加载提示
    loading: {
      handler: function (val, oldVal) {
        if (val === true) {
          this.$modal.loading("加载中，请耐心等待...");
        } else {
          this.$modal.closeLoading();
        }
      },
      deep: true,
    },
    queryParams: {
      handler: function (val) {
        this.getList();
      },
      deep: true,
    },
  },

  mounted() {
    this.$nextTick(function () {
      let pageWidth = 0;
      let confirmDelPush = 0;

      let dimLimitDom = uni.createSelectorQuery().select(".page");
      dimLimitDom
        .fields({ size: true }, (data) => {
          pageWidth = data.width;

          confirmDelPush =
            pageWidth > 440
              ? pageWidth > 1700
                ? 20
                : pageWidth > 1530
                  ? 19
                  : pageWidth > 1330
                    ? 19
                    : pageWidth > 1240
                      ? 18
                      : pageWidth > 1085
                        ? 17
                        : pageWidth > 875
                          ? 16 - 1
                          : pageWidth > 800
                            ? 15 - 1
                            : pageWidth > 730
                              ? 14 - 1
                              : pageWidth > 660
                                ? 13 - 1
                                : pageWidth > 600
                                  ? 12 - 1
                                  : pageWidth > 560
                                    ? 11 - 1
                                    : pageWidth > 520
                                      ? 10 - 1
                                      : pageWidth > 490
                                        ? 9 - 1
                                        : 7
              : pageWidth > 440
                ? 8
                : pageWidth > 420
                  ? 7
                  : pageWidth > 390
                    ? 6
                    : pageWidth > 370
                      ? 5
                      : pageWidth > 355
                        ? 4
                        : pageWidth > 340
                          ? 3
                          : pageWidth > 325
                            ? 2
                            : pageWidth > 310
                              ? 1
                              : 0;
        })
        .exec();

      this.confirmDelPush = confirmDelPush;
    });
  },
  // 页面周期函数--监听页面加载
  onLoad() {
    this.initializeDict();
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() { },
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {
    this.getList();
  },
  // 页面周期函数--监听页面隐藏
  onHide() { },
  // 页面周期函数--监听页面卸载
  onUnload() {
    const that = this
    return that.$listenOB.goBack()
  },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  onReachBottom() {
    this.changeParamPageSize();
  },
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 100%;

  .top_view {
    margin-bottom: 10px;

    .del {
      height: 50px;
      width: 100%;
      background: white;

      .buttom_row {
        width: 100%;
        display: inline-flex;
        border: none;
        align-items: center;
      }
    }
  }

  .del_fixed {
    position: fixed;
    z-index: 9;
  }

  .page-body {
    display: flex;
    justify-content: center;

    /deep/ .uset-apply-list {
      width: 100vw;

      .wx-switch-input:not([class*="bg-"]),
      .uni-switch-input:not([class*="bg-"]) {
        background: none !important;
        background-color: rgb(223, 223, 223) !important;
        border-color: rgb(223, 223, 223) !important;
      }

      .uni-switch-wrapper {
        margin-left: 10px;
      }

      .wx-switch-input-checked:not([class*="bg-"]),
      .uni-switch-input-checked:not([class*="bg-"]) {
        background-color: rgb(255, 0, 0) !important;
        border-color: rgb(255, 0, 0) !important;
      }
    }
  }

  .empty {
    font-size: 12px;
    position: absolute;
    top: 40%;
  }
}
</style>