<template>
  <div class="app-container">
    <el-card class="app-container__search">
      <xd-search
        dateFilter
        v-if="searchForm.length > 0"
        v-model="searchParams"
        :list="searchForm"
        @onSearch="handleSearch"
        @onDone="getList"
      ></xd-search>
    </el-card>
    <el-card class="app-container__list">
      <div class="app-container__list-pagination">
        <div></div>
        <div class="table-stat">
          <p>共计 销量<span>{{ totalData.product_num }}</span>个，
            建议售价金额<span>{{divide(totalData.sale_amount)}}</span>元，
            货源进货价金额<span>{{divide(totalData.purchase_amount)}}</span>元，
            平台进货价金额<span>{{divide(totalData.dist_amount)}}</span>元</p>
          <el-button type="primary" @click="doExport">条件导出</el-button>
        </div>
      </div>
      <div class="app-container__list-table">
        <xd-table
          :headers="headers"
          :list="tables"
          :defaultSort="{prop: 'total_product_num', order: 'descending'}"
          is-border
          @onSortChange="handleSortChange"
        ></xd-table>
      </div>
      <div class="app-container__list-pagination">
        <xd-pagination
          :page="page_token"
          :total="total"
          :limit.sync="page_size"
          :autoScroll="false"
          @onPagination="handlePagination"
        ></xd-pagination>
      </div>
    </el-card>
  </div>
</template>


<script>
import XdSearch from "@/components/XdSearch";
import XdPagination from "@/components/XdPagination.vue";
import XdTable from "@/components/XdTable";
import { baseJsDateToTime } from "@/utils/xd.base";
import { getOptions } from "@/utils/options"
import { mapActions } from "vuex"

export default {
  name: "ComponentTableSupplier",
  components: {
    XdPagination, //翻译插件
    XdSearch, //搜查插件
    XdTable
  },
  data() {
    return {

      //分页参数
      page_token: 1, //当前页面数量
      page_size: 20, //搜索参数
      searchForm: [], //搜索区域模块表单
      searchParams: null, //搜索参数
      totalData: {},
      total: 0,
      sort_by: "total_product_num", //排序字段
      sort_direct: "desc", //排序方向 asc递增 desc递减

      //列表对象
      tables: [],
      headers: [
        { "type": "normal", "prop": "product_id", "align": "left", "width": 80, "label": "商品ID" },
        { "type": "normal", "prop": "product_name", "align": "center", "minWidth": 200, "label": "商品名称" },
        { "type": "normal", "prop": "product_type", "align": "center", "width": 80, "label": "商品类型" },
        { "type": "normal", "prop": "supplier_name", "align": "center", "width": 100, "label": "所属供应商" },
        { "type": "normal", "prop": "total_product_num", "align": "center", "width": 100, "label": "总销量", "sort": "custom" },
        { "type": "price", "prop": "total_sale_amount", "align": "center", "width": 100, "label": "建议售价金额", "unit": "元", "sort": "custom" },
        { "type": "price", "prop": "total_purchase_amount", "align": "center", "width": 100, "label": "货源进货价金额", "unit": "元", "sort": "custom" },
        { "type": "price", "prop": "total_dist_amount", "align": "center", "width": 100, "label": "平台进货价金额", "unit": "元", "sort": "custom" },
        { "type": "normal", "prop": "total_real_product_num", "align": "center", "minWidth": 100, "label": "实际销量", "sort": "custom" },
        { "type": "price", "prop": "total_real_sale_amount", "align": "center", "width": 100, "label": "实际建议售价金额", "unit": "元", "sort": "custom" },
        { "type": "normal", "prop": "total_aftersale_product_num", "align": "center", "minWidth": 100, "label": "售后次数", "sort": "custom" },
        { "type": "price", "prop": "total_aftersale_amount", "align": "center", "width": 100, "label": "售后建议售价金额", "unit": "元", "sort": "custom" },
      ]
    }
  },
  created() {
    this.initSearchForm();
  },
  methods: {
    ...mapActions("supplierStat", ['productCycSales']),
    divide(price) {
      return this.$xdHelper.divisionFloatNumber(price, 100);
    },
    getOtherParams(){
      let { supplier_id, like_product_id, ...other } = this.searchParams;
      if(supplier_id && supplier_id.length > 0){
        other.supplier_id = supplier_id[0].value;
      }
      if(like_product_id && like_product_id.length > 0){
        other.like_product_id = like_product_id[0].value;
      }
      return other;
    },
    doExport(){
      this.$prompt('请输入导出文件名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /[\S]+/,
        inputErrorMessage: '请填写正确的名称'
      }).then(({ value }) => {
        let other = this.getOtherParams();
        let params = {
          ...other,
          export: true,
          file_ext: "xlsx",
          file_name: value,
        };
        let loading = this.$loading({});
        this.productCycSales(params).then(res => {
          loading.close();
          this.$alert('导出任务已经开始执行，请去任务管理查看下载状态', '提示', {
            confirmButtonText: '确定',
          });
        }).catch(err => {
          this.$message.error(err.msg);
          loading.close();
        })
      })
    },
    /**
     * @description 获取数据列表
     */
    getList() {
      let other = this.getOtherParams();
      //请求数据
      let params = {
        ...other,
        page_token: this.page_token,
        page_size: this.page_size,
        sort_by: this.sort_by,
        sort_direct: this.sort_direct,
      };
      console.log(params)
      let loading = this.$loading({});

      //正式数据需要自己实现
      this.productCycSales(params).then(res => {
        loading.close();
        this.tables = res.data.list;
        this.totalData = res.data.total;
        this.total = res.data.total_page_size
      }).catch(err => {
        loading.close();
      })
    },
    handleSortChange({ prop, order }) {
      if(order === null){
        this.sort_by = '';
        this.sort_direct = '';
        this.getList();
        return;
      }
      this.sort_by = prop;
      this.sort_direct = order === 'ascending' ? 'asc' : 'desc';
      this.getList();
    },

    /**
     * @description 点击搜索进行搜索操作
     * @param action 动作
     * @param form 搜索请求参数
     */
    handleSearch({ action, form }) {
      this.page_token = 1;
      this.getList();
    },
    /**
     * @description 初始化搜索模块
     */
    initSearchForm() {
      let yesterDay = new Date().getTime() - 24 * 60 * 60 * 1000;
      yesterDay = baseJsDateToTime(yesterDay/1000);
      yesterDay = yesterDay.split(' ')[0];

      this.searchForm = [
        {
          label: '交易时间:', //label
          ele: 'xd-date', //package 名称
          valueKey: ['time_range_start', 'time_range_end'], //form[valueKey]
          value: [yesterDay, yesterDay], //v-model
          format: 'yyyy-MM-dd', //时间显示格式
          formatValue: 'yyyy-MM-dd', //输出时间格式
          placeholder: ['开始时间', '结束时间'],
        },
        {
          label: "商品ID",
          ele: "el-input",
          valueKey: "product_id",
          value: "",
          placeholder: "请输入商品ID"
        },
        // {
        //   label: "商品名称",
        //   ele: "el-input",
        //   valueKey: "product_name",
        //   value: "",
        //   placeholder: "请输入商品名称"
        // },
        {
          label: "商品名称:", //label
          ele: "xd-remote-select", //package 名称
          valueKey: "like_product_id", //form[valueKey]s
          value: [], //v-model
          placeholder: "请选择商品名称",
          multiple: false,
          collapseTags: false,
          className: 'input40',
          remoteSearch: (query, resolve) => {
            getOptions({
              server: 'product-partner',
              fn: 'released-products',
              path: 'p1',
              params: {
                keyword: query,
                page_token: 1,
                page_size: 500,
              }
            })
              .then(res => {
                resolve(res.data.items)
              })
              .catch(err => {
                console.log(err, 'err')
              })
          }
        },
        {
          label: "商品类型",
          ele: "xd-select-list",
          valueKey: "product_type",
          value: "",
          placeholder: "请选择商品类型",
          list: [
            { label: "全部", value: "" },
            { label: "实物商品", value: "good" },
            { label: "电子票券", value: "card" },
            { label: "生活服务", value: "network" },
            { label: "线上显示", value: "show" },
          ]
        },
        {
          label: "供应商名称:", //label
          ele: "xd-remote-select", //package 名称
          valueKey: "supplier_id", //form[valueKey]s
          value: [], //v-model
          placeholder: "请选择供应商",
          multiple: false,
          collapseTags: false,
          className: 'input40',
          remoteSearch: (query, resolve) => {
            getOptions({
              server: 'supplier-partner',
              fn: 'supplier',
              path: 'p1',
              params: {
                keyword: query,
                page_token: 1,
                page_size: 500,
              }
            })
              .then(res => {
                resolve(res.data.list)
              })
              .catch(err => {
                console.log(err, 'err')
              })
          }
        },
      ];
    },
    /**
     * @description 翻页处理方法
     * @param page {Number} 访问页面页码数
     */
    handlePagination(page) {
      this.page_token = page;
      this.getList();
    }, //todo
  }
}
</script>

<style scoped lang="scss">
  .table-stat{
    display: flex;
    justify-content: space-between;
    align-items: center;
    p{
      font-size: 14px;
      color: #2E3033;
      span{
        color: #FF6A00;
        font-weight: 600;
      }
    }

  }

</style>

