<template>
  <Page name="search-org-schedule">
    <template #header>
      <search-bar v-model="searchForm.query" placeholder="请输入区域名称" auto @confirm="onSearch" />
    </template>
    <template #content>
      <List ref="list" v-model="list" :api="searchAPI">
        <template v-for="(item, index) in newList">
          <zui-cell :key="index" @click="onSelect(item, index)">
            <template #title>
              <text>{{ item.name }}</text>
            </template>
            <template #right>
              <view class="collect" hover-class="active" hover-start-time="50" hover-stay-time="70">
                <view class="c-img">
                  <image :src="formatImagePath(item.collectFlag ? 'selected' : 'heart-unselected')" />
                </view>
                <view :class="['c-info', item.collectFlag ? 'orange' : 'grey']">{{ item.collectFlag ? '取消' : '添加' }}</view>
              </view>
            </template>
          </zui-cell>
        </template>
      </List>
    </template>
  </Page>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      searchForm: {
        query: '',
      },
      username: '',
      regionList: [],
    };
  },
  onLoad(option) {
    this.username = option.username;
    this.regionList = JSON.parse(option.region) || [];
  },
  computed: {
    newList() {
      let nList = this.list;
      nList.forEach((item) => {
        this.regionList.forEach((k) => {
          if (item.code === k.orgCode) {
            this.$set(item, 'collectFlag', true);
          }
        });
      });
      return nList;
    },
  },
  methods: {
    searchAPI(params) {
      return uni.$u.api.filter.org({ ...params, ...this.searchForm });
    },
    onSelect(item, index) {
      let fIndex = this.regionList.findIndex((t) => t.orgCode === item.code);
      if (fIndex !== -1) {
        this.regionList.splice(fIndex, 1);
      }
      if (item.collectFlag) {
        uni.$u.api.pricingSchedule.removeArea({ username: this.username, orgCode: item.code }).then(() => {});
        this.$set(this.list, index, { ...this.list[index], collectFlag: false });
      } else {
        uni.$u.api.pricingSchedule.addArea({ username: this.username, orgCode: item.code }).then(() => {});
        this.$set(this.list, index, { ...this.list[index], collectFlag: true });
      }
    },
  },
};
</script>

<style lang="scss">
.page-search-org-schedule {
  &__header {
    padding: 15rpx 22rpx !important;
  }
  .collect {
    display: flex;
    flex-direction: column;
    align-items: center;
    .c-img {
      width: 42rpx;
      height: 42rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
    .orange {
      color: #ff710b;
    }
    .c-info {
      font-size: 22rpx;
    }
    .grey {
      color: #666666;
    }
  }
}
</style>
