<template>
  <a-spin :spinning="spinning" tip="Loading...">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form-model
        id="vinAnaly-form"
        ref="ruleForm"
        class="form-model-con"
        layout="inline"
        :model="queryParam"
        :rules="rules"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        @keyup.enter.native="handleSearch" >
        <a-row :gutter="15">
          <a-col :md="5" :sm="24">
            <a-form-model-item label="货架名称" prop="shelfSn">
              <shelfSList v-model="queryParam.shelfSn" @change="shelfChange"></shelfSList>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-model-item label="产品编码">
              <a-input id="vinAnaly-VIN" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-model-item label="产品名称">
              <a-input id="vinAnaly-VIN" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-model-item label="原厂编码">
              <a-input id="vinAnaly-VIN" v-model.trim="queryParam.origCode" allowClear placeholder="请输入原厂编码"/>
            </a-form-model-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="5" :sm="24">
              <a-form-item label="产品品牌">
                <ProductBrand placeholder="请选择产品品牌" v-model="queryParam.brandSn"></ProductBrand>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="产品分类">
                <ProductType placeholder="请选择产品分类" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="VIN扫描时间">
                <rangeDate ref="scanDate" v-model="time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" @click="handleSearch" :disabled="disabled" id="vinAnaly-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="vinAnaly-reset">重置</a-button>
            <a-button
              type="primary"
              style="margin-left: 5px"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              class="button-warning"
              id="vinAnaly-export-btn">导出</a-button>
            <a @click="advanced=!advanced" style="margin-left: 5px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div v-show="isSearchFlag">
      <div class="t-title" style="display: flex;align-items: center;justify-content: space-between;padding:5px 0;">
        <div style="border-left:2px solid #eee;padding:0 5px;font-weight: bold;font-size:14px;">{{ shelfName||'' }}</div>
        <div></div>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        bordered>
        <template slot="type" slot-scope="text, record">
          <div>
            {{ record.productTypeName2 }}->{{ record.productTypeName3 }}
          </div>
        </template>
      </s-table>
    </div>
    <div class="unChoose" v-show="!isSearchFlag">
      <a-icon type="exclamation-circle" theme="filled" :style="{ fontSize: '18px', color: '#ff9900', verticalAlign: 'sub', marginRight: '5px' }" />
      <span>请选择一个货架后点击查询按钮</span>
    </div>
    </div>
  </a-spin>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { downloadExcel } from '@/libs/JGPrint.js'
import shelfSList from '@/views/common/shelfList'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { reportPage, exportReport } from '@/api/vinLog'
export default {
  components: { STable, VSelect, rangeDate, shelfSList, ProductType, ProductBrand },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      productType: [],
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        shelfSn: undefined,
        productCode: undefined, //  产品编码
        productName: undefined, //  产品名称
        origCode: undefined, // 原厂编码
        brandSn: undefined, //  产品品牌
        productTypeSn1: undefined, //  产品一级分类
        productTypeSn2: undefined, //  产品二级分类
        productTypeSn3: undefined //  产品三级分类
      },
      isSearchFlag: false,
      time: [],
      rules: {
        'shelfSn': [{ required: true, message: '请选择货架', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      order_by: '',
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        this.disabled = true
        const newParameter = parameter
        if (newParameter.sortField && newParameter.sortField == 'inStockCount') { // 有货
          if (newParameter.sortOrder) {
            if (newParameter.sortOrder != 'ascend') { // 降序
              newParameter.orderBy = 'xvfp.in_stock_count desc,xp.code asc'
            } else {
              newParameter.orderBy = 'xvfp.in_stock_count asc,xp.code asc'
            }
            this.order_by = newParameter.orderBy
          } else {
            this.order_by = ''
          }
        }
        if (newParameter.sortField && newParameter.sortField == 'notStockCount') { // 无货
          if (newParameter.sortOrder) {
            if (newParameter.sortOrder != 'ascend') { // 降序
              newParameter.orderBy = 'xvfp.not_stock_count desc,xp.code asc'
            } else {
              newParameter.orderBy = 'xvfp.not_stock_count asc,xp.code asc'
            }
            this.order_by = newParameter.orderBy
          } else {
            this.order_by = ''
          }
        }

        const params = Object.assign(newParameter, this.queryParam, { orderBy: this.order_by })
        delete params.time
        return reportPage(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      shelfName: '',
      filters: [{ text: '有', value: '1' }, { text: '无', value: '0' }, { text: '空(--)', value: '' }]
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'origCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品品牌', dataIndex: 'brandName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', slots: { title: 'type' }, scopedSlots: { customRender: 'type' }, width: '10%', align: 'center' },
        { title: '适配有货次数', dataIndex: 'inStockCount', width: '10%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' }, sorter: (a, b) => a.inStockCount - b.inStockCount },
        { title: '适配缺货次数', dataIndex: 'notStockCount', width: '10%', align: 'center', customRender: function (text) { return (text || text == 0) ? text : '--' }, sorter: (a, b) => a.notStockCount - b.notStockCount }
        // { title: '最近VIN扫描时间', dataIndex: 'scanVinDate', width: '7%', align: 'center', customRender: function (text) { return text || '--' }, sorter: true }
      ]
      return arr
    }
  },
  methods: {
    shelfChange (v, row) {
      this.shelfName = row ? row.shelfName : ''
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  创建时间  change
    dateChange (date) {
      this.time = date
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.isSearchFlag = true
          this.$refs.table.refresh(true)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.isSearchFlag = false
      this.queryParam = {
        beginDate: '',
        endDate: '',
        shelfSn: undefined,
        productCode: undefined, //  产品编码
        productName: undefined, //  产品名称
        origCode: undefined, // 原厂编码
        brandSn: undefined, //  产品品牌
        productTypeSn1: undefined, //  产品一级分类
        productTypeSn2: undefined, //  产品二级分类
        productTypeSn3: undefined //  产品三级分类
      }
      this.time = []
      this.productType = []
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
      if (this.advanced) {
        this.$refs.scanDate.resetDate()
      }
      this.handleSearch()
    },
    // 导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          params.orderBy = this.order_by
          _this.exportLoading = true
          _this.spinning = true
          exportReport(params).then(res => {
            downloadExcel(res, '适配产品统计')
            _this.exportLoading = false
            _this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleDetail (row) {
      this.curItem = row
      this.showDetail = true
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less" scoped>
  .unChoose {
    text-align: center;
    margin: 280px 0 340px;
    font-size: 16px;
  }
</style>
