<!-- 工单-搜索页 -->
<template>
  <view class="search-wrap">
    <view class="top-item">
      <u-search
        v-model="search.keyword"
        bg-color="#FFFFFF"
        placeholder="扳手会工单·用户姓名·手机号·地址"
        search-icon-color="#999999"
        color="#333333"
        placeholder-color="#999999"
        height="72"
        margin="0 30rpx"
        :animation="true"
        :show-action="true"
        :action-style="{
          'font-size': '32rpx',
          'font-weight': 500,
          color: '#2272FF',
        }"
        :focus="true"
        @change="keywordChange"
        @focus="onfocus"
        @blur="loseFocus"
        @search="searchOrder"
        @custom="searchOrder"
      ></u-search>
    </view>
    <view class="association-wrap" v-show="showAssociation">
      <view
        v-for="(item, index) in associationList"
        :key="index"
        class="association-cell u-border-top"
        @click="handleClick(item, orderType, true)"
      >
        <view class="u-m-l-40">
          <u-parse
            :html="item.contactNameHighlight"
            :tag-style="style"
          ></u-parse>
        </view>
        <view class="u-m-l-10">
          <u-parse
            :html="item.contactPhoneHighlight"
            :tag-style="style"
          ></u-parse>
        </view>
      </view>
      <view class="u-border-top" />
    </view>
    <view class="content-item" v-show="showOrderCell">
      <view v-if="orderList && orderList.length > 0" class="order-row">
        <view v-for="item in orderList" :key="item.orderId">
          <OrderCell
            :orderData="item"
            :orderType="orderType"
            :location="dataValue"
            @click="handleClick"
            @action="handleClickCellButton"
          >
          </OrderCell>
        </view>
        <u-loadmore :status="loadStatus" bgColor="#F4F5F7"></u-loadmore>
      </view>
      <view v-else-if="loaded" class="empty-result">
        <u-image width="374" height="256" :src="searchEmpty">
          <u-loading slot="loading"></u-loading>
        </u-image>
        <text class="empty-message"> 当前暂无搜索结果 </text>
      </view>
    </view>
  </view>
</template>

<script>
import OrderCell from "@/components/order/index.vue";
export default {
  components: {
    OrderCell,
  },
  data() {
    return {
      search: {
        type: "",
        keyword: "",
        pageSize: 10,
        pageNumber: 0,
        orderStatusRangeType: "",
      },
      orderList: [],
      associationList: [],
      loaded: false,
      focused: true,
      total: 10,
      loadStaus: "loadmore",
      style: {
        // 字符串的形式
        span: "color: red",
      },
    };
  },
  onLoad() {
    getApp().trackPage("订单搜索页");
    // this.searchOrder()
  },
  onReachBottom() {
    let len = (this.orderList && this.orderList.length) || 0;
    if (!this.loaded || len >= this.total) return;
    this.loadStaus = "loading";
    this.search.pageNumber = ++this.search.pageNumber;
    this.getOrderList("onReachBottom");
  },
  computed: {
    searchEmpty() {
      return process.uniEnv.qn_base_url + "SearchEmpty.png";
    },
    showAssociation() {
      return this.focused && this.search.keyword && !this.$u.test.isEmpty(this.associationList);
    },
    showOrderCell() {
      return !this.focused;
    },
  },
  methods: {
    searchOrder(index) {
      this.search.pageNumber = 1;
      this.loadStaus = "loading";
      if (this.search.keyword) {
        getApp().track("search_order", { keyword: this.search.keyword });
        this.getOrderList();
        this.focused = false;
      }
    },
    // 高亮文本
    highlights() {
      const keyword = this.search.keyword;
      this.associationList = this.associationList.map((item) => {
        for (let key in item) {
          if (key === "contactName" || key === "contactPhone") {
            let replaceReg = new RegExp(keyword, "g"); // 匹配关键字正则
            let replaceString = "<span>" + keyword + "</span>"; // 高亮替换v-html值
            item[key + "Highlight"] = item[key].replace(
              replaceReg,
              replaceString
            ); // 开始替换
          }
        }
        return item;
      });
    },
    /** 联想工单 */
    async associationOrder() {
      let res = await this.$u.api.association(this.search);
      if (res && res.code == 200) {
        this.associationList = res.data;
      }
      this.highlights();
    },
    /** 搜索关键字变更 */
    keywordChange(value) {
      if (this.$u.test.isEmpty(value)) {
        this.associationList = [];
      } else {
        this.associationOrder();
      }
    },
    /** 获得焦点 */
    onfocus() {
      this.focused = true;
    },
    /** 失去焦点 */
    loseFocus() {
      
    },
    // 页面数据
    getOrderList(event) {
      let self = this;
      if (!self.search.keyword) {
        return false;
      }

      // 状态处理
      self.loaded = false;
      self.$u.api.listOrder(self.search).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            let list = res.data.list || [];
            self.total = res.data.total || 0;
            if (event == "onReachBottom") {
              self.orderList.push(...list);
            } else {
              self.orderList = list;
            }
            self.loadStatus =
              res.data.total > self.orderList.length ? "loadmore" : "nomore";
          }
        } else {
          self.$u.toast("请求失败");
        }
        self.loaded = true;
      });
    },
    handleClickCellButton(item) {
      // 去完工
      uni.navigateTo({
          url:
            'pages/order/complete?orderId=' +
            item.orderId +
            '&categoryId=' +
            item.categoryId +
            '&orderServiceType=' +
            item.orderServiceType +
            '&inGuaranteePeriod=' +
            item.inGuaranteePeriod +
            '&partnerCompanyId=' +
            item.partnerCompanyId +
            '&maintainStep=' +
            item.maintainStep +
            '&orderStatus=' +
            item.orderStatus +
            '&brandId=' +
            item.lianbaoBrandId +
            '&auditResults=' +
            (item.auditResults ? item.auditResults.join() : '') +
            '&orderNumber=' +
            item.orderNumber,
        })
    },
    handleClick(item, type, showCountTime) {
      // type:类型，showCountTime：是否显示倒计时。详情页面情况太多，提前传值可以避免页面晃动
      //type类型
      // 'waitAccept': 待接单、待抢单;'waitAppointment': 待预约;'waitCheckIn': 待签到;'waitFinish': 待完工;'audit': 审核中;'exception': 异常单;'finish': 已完工;'other': 工单结算信息
      uni.navigateTo({
        url:
          "pages/order/detail?id=" +
          item.orderId +
          "&type=" +
          type +
          "&showCountTime=" +
          showCountTime,
      });
    },
  },
};
</script>

<style lang="scss">
.search-wrap {
  display: flex;
  flex-direction: column;
  height: 100vh;
  .top-item {
    position: sticky;
    padding: 20rpx 0;
    top: 0rpx;
    background-color: #f4f5f7;
    z-index: 2;
    /deep/ .u-search .u-content {
      padding: 0 20rpx 0 40rpx;
    }
    /deep/ .u-search .u-input {
      margin: 0 24rpx;
    }
    /deep/ .u-search .u-icon--right .u-iconfont {
      font-size: 36rpx !important;
    }
    /deep/ .u-search .u-close-wrap .u-iconfont {
      color: #cccccc;
    }
  }

  .content-item {
    padding: 10rpx 30rpx 20rpx 30rpx;

    .empty-result {
      padding-top: 354rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .empty-message {
        padding-top: 28rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: #666666;
        line-height: 28rpx;
      }
    }
  }

  .association-wrap {
    height: 100%;
    padding-bottom: 44rpx;
    overflow: auto;
    .association-cell {
      display: flex;
      padding: 26rpx 32rpx;
      font-size: 28rpx;
      line-height: 54rpx;
      color: #606266;
      background: #ffffff;
    }
  }
}
</style>
