<template>
  <el-container class="goods-select">
    <el-aside class="select-aside">
      <el-select
        class="sa-m-b-16"
        v-model="categoryLevel"
        placeholder="Select"
        @change="getCategoryDetail"
      >
        <el-option
          v-for="item in category.data"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-tree
        :data="category.detail"
        empty-text=""
        :props="{
          children: 'children',
          label: 'name',
        }"
        :indent="0"
        :accordion="true"
      >
        <template #default="{ node, data }">
          <span
            class="custom-tree-node sa-flex"
            :class="data.id == searchData.category_ids ? 'is-active' : ''"
            :style="{ 'padding-left': node.level * 16 + 'px' }"
            @click.stop="changeCategoryIds(data)"
          >
            <div class="sa-table-line-1">{{ data.name }}</div>
            <el-icon
              :class="['sa-m-l-8', node.expanded ? 'expand-arrow-up' : 'expand-arrow-down']"
              v-if="data.children && data.children.length"
              @click.stop="node.expanded = !node.expanded"
            >
              <ArrowDown />
            </el-icon>
          </span>
        </template>
      </el-tree>
    </el-aside>
    <el-container>
      <el-header class="goods-search sa-flex sa-flex-wrap sa-row-between">
        <div class="sa-flex sa-flex-wrap goods-price">
          <span class="sa-m-r-12">商品价格</span>
          <el-input class="sa-w-88" v-model="searchData.price.min" placeholder="最低价格" />
          <span class="sa-m-l-12 sa-m-r-12">至</span>
          <el-input class="sa-w-88" v-model="searchData.price.max" placeholder="最高价格" />
        </div>
        <el-input
          class="sa-w-180"
          v-model="searchData.keyword"
          prefix-icon="Search"
          placeholder="请输入搜索内容"
        />
      </el-header>
      <el-main v-loading="loading">
        <el-table
          class="sa-table"
          ref="multipleTableRef"
          :data="table.list"
          @select="selectRow"
          @select-all="selectAll"
          stripe
        >
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column
            v-if="modal.params.multiple"
            type="selection"
            width="48"
          ></el-table-column>
          <el-table-column prop="id" label="ID" min-width="88" />
          <el-table-column label="商品信息" min-width="310">
            <template #default="scoped">
              <div class="sa-flex">
                <sa-image :url="scoped.row.image" size="40"></sa-image>
                <div class="sa-m-l-8">
                  <div class="title sa-m-b-6 sa-table-line-1">
                    {{ scoped.row.title }}
                  </div>
                  <div class="price">¥{{ scoped.row.price.join('~¥') }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" min-width="120"></el-table-column>
          <el-table-column v-if="!modal.params.multiple" label="操作" width="80">
            <template #default="scope">
              <template v-if="modal.params.ftype == 'score_shop'">
                <span v-if="scope.row.is_score_shop">已参加</span>
                <el-button
                  v-if="!scope.row.is_score_shop"
                  class="is-link"
                  type="primary"
                  @click="singleSelect(scope.row.id)"
                  >参加</el-button
                >
              </template>
              <template v-else>
                <el-button class="is-link" type="primary" @click="singleSelect(scope.row.id)"
                  >选择</el-button
                >
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer
        class="sa-footer--submit"
        :class="modal.params.multiple ? 'sa-row-between' : 'sa-row-right'"
      >
        <sa-pagination :pageData="pageData" layout="total, prev, pager, next" @updateFn="getData" />
        <el-button v-if="modal.params.multiple" type="primary" @click="confirm">确 定</el-button>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script>
  export default {
    name: 'GoodsSelect',
  };
</script>

<script setup>
  /**@property {Array} ids - 已经选中
   * @param {Boolean} multiple - 是否多选
   * @param {Number} max - 多选时最大数量(0 代表限制数量)
   * @param {String} ftype - 打开来源(score_shop)
   */
  import { nextTick, onMounted, reactive, ref, watch } from 'vue';
  import { api } from '../goods.service';
  import { api as categoryApi } from '@/app/shop/admin/goods/category/category.service';
  import { ElMessage } from 'element-plus';
  import { composeFilter } from '@/sheep/utils';
  import { useDebounceFn } from '@vueuse/core';
  import { usePagination } from '@/sheep/hooks';
  import { cloneDeep } from 'lodash';

  const { pageData } = usePagination();

  const emit = defineEmits(['modalCallBack']);
  const props = defineProps(['modal']);

  // 分类
  const categoryLevel = ref('');
  const category = reactive({
    data: [],
    detail: [],
  });

  async function getCategory() {
    const { data } = await categoryApi.select();
    category.data = data;
    category.data.unshift({
      children: [],
      id: 'all',
      name: '全部分类',
    });
    if (data.length > 0) {
      categoryLevel.value = data[0].id;
      getCategoryDetail();
    }
  }

  async function getCategoryDetail() {
    const data = category.data.find((item) => item.id == categoryLevel.value);
    category.detail = data.children || [];
    searchData.category_ids = data.id;
  }

  function changeCategoryIds(data) {
    searchData.category_ids = data.id;
  }

  const searchData = reactive({
    category_ids: '',
    keyword: '',
    price: {
      min: '',
      max: '',
    },
  });

  const loading = ref(true);
  const table = reactive({
    list: [],
    // selected: [],
    ids: props.modal.params.ids,
  });

  async function getData() {
    loading.value = true;
    let tempSearch = cloneDeep(searchData);
    tempSearch.category_ids = tempSearch.category_ids + '';
    if (tempSearch.price.min && tempSearch.price.max) {
      tempSearch.price = `${tempSearch.price.min} - ${tempSearch.price.max}`;
    }
    // activity_type 搜索
    if (props.modal.params.activity_type) {
      tempSearch.activity_type = props.modal.params.activity_type;
    }
    // id 搜索
    if (props.modal.params.goods_ids) {
      tempSearch.goods = { field: 'id', value: props.modal.params.goods_ids };
    }

    let search = composeFilter(tempSearch, {
      keyword: '=',
      price: 'between',
    });
    const { data } = await api.goods.select({
      page: pageData.page,
      list_rows: pageData.list_rows,
      ...search,
      data_type: props.modal.params.ftype || '',
    });
    table.list = data.data;
    pageData.page = data.current_page;
    pageData.list_rows = data.per_page;
    pageData.total = data.total;

    nextTick(() => {
      table.list.forEach((l) => {
        if (table.ids?.includes(l.id)) {
          multipleTableRef.value?.toggleRowSelection(l, true);
          toggleRowSelection('row', [l], l);
        }
      });
    });

    loading.value = false;
  }

  const debouncedFn = useDebounceFn(getData, 500);
  watch(
    () => searchData,
    () => {
      pageData.page = 1;
      debouncedFn();
    },
    {
      deep: true,
    },
  );

  const multipleTableRef = ref();
  function selectRow(selection, row) {
    if (
      !props.modal.params.max ||
      (props.modal.params.max && props.modal.params.max > table.ids.length)
    ) {
      if (table.ids.includes(row.id)) {
        let index = table.ids.findIndex((id) => id == row.id);
        table.ids.splice(index, 1);
      } else {
        table.ids.push(row.id);
      }
    }
    toggleRowSelection('row', selection, row);
  }
  function selectAll(selection) {
    if (
      !props.modal.params.max ||
      (props.modal.params.max && props.modal.params.max > table.ids.length + selection.length)
    ) {
      if (selection.length == 0) {
        table.list.forEach((l) => {
          if (table.ids.includes(l.id)) {
            let index = table.ids.findIndex((id) => id == l.id);
            table.ids.splice(index, 1);
          }
        });
      } else {
        table.list.forEach((l) => {
          if (!table.ids.includes(l.id)) {
            table.ids.push(l.id);
          }
        });
      }
    }
    toggleRowSelection('all', selection);
  }

  function toggleRowSelection(type, selection, row) {
    // 限制数量
    if (props.modal.params.max && props.modal.params.max < selection.length) {
      if (type == 'row') {
        multipleTableRef.value.toggleRowSelection(row, false);
      } else if (type == 'all') {
        multipleTableRef.value?.clearSelection();
        table.list.forEach((l) => {
          if (table.ids?.includes(l.id)) {
            multipleTableRef.value?.toggleRowSelection(l, true);
          }
        });
      }
      ElMessage({
        type: 'warning',
        message: '已到选择上限',
      });
      return false;
    }
  }

  async function singleSelect(id) {
    await getGoodsList(id);
    emit('modalCallBack', {
      event: 'confirm',
      data: tempGoods.list[0],
    });
  }

  async function confirm() {
    await getGoodsList(table.ids.join(','));
    emit('modalCallBack', {
      event: 'confirm',
      data: tempGoods.list,
    });
  }

  const tempGoods = reactive({
    list: [],
  });

  async function getGoodsList(ids) {
    const { data } = await api.goods.select(
      {
        search: JSON.stringify({ id: [ids, 'in'] }),
      },
      'select',
    );
    tempGoods.list = data;
  }

  onMounted(() => {
    getCategory();
  });
</script>
<style lang="scss" scoped>
  .goods-select {
    .select-aside {
      --el-aside-width: 180px;
      border-right: 1px solid var(--sa-border);
      padding: 20px;
      :deep() {
        .el-tree-node {
          .el-tree-node__content {
            height: auto;
            .el-tree-node__expand-icon {
              display: none;
            }
          }
        }
      }
      .custom-tree-node {
        width: 100%;
        height: 32px;
        line-height: 32px;
        border-radius: 4px;
        &.is-active {
          background: var(--t-bg-active);
          color: var(--el-color-primary);
        }
      }
    }
    .goods-search {
      --el-header-height: auto;
      padding-top: var(--sa-padding);
    }
    .title {
      height: 16px;
      line-height: 16px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-subtitle);
    }
    .price {
      line-height: 16px;
      font-size: 12px;
      font-weight: 400;
      color: #ff4d4f;
    }
    .sa-footer--submit {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      --el-footer-height: auto;
      min-height: 60px;
    }
  }
  @media only screen and (max-width: 768px) {
    .goods-price {
      display: none;
    }
  }
</style>
