<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="6" :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="6" :sm="24">
            <a-form-model-item label="扫描时间">
              <rangeDate ref="rangeDate" v-model="time" @change="dateChange" />
            </a-form-model-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="VIN">
                <a-input id="vinAnaly-VIN" v-model.trim="queryParam.vinCode" allowClear placeholder="请输入VIN"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="车辆品牌">
                <a-input id="vinAnaly-salesBillNo" v-model.trim="queryParam.brandName" allowClear placeholder="请输入车辆品牌"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="车型">
                <a-input id="vinAnaly-salesManName" v-model.trim="queryParam.modelInfo" allowClear placeholder="请输入车型"/>
              </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="isSearch">
      <!-- 合计 -->
      <a-alert type="info" style="margin-bottom:10px" v-if="queryCountData">
        <div class="ftext" slot="message">
          <div>
            累计扫描VIN：<strong>{{ queryCountData.scanCount }}</strong>次；
          </div>
          <div>
            空调滤清器 有适配：<strong>{{ queryCountData.airConditionerFilterOnShelfCount }}</strong>次，<strong>{{ queryCountData.airConditionerFilterOnShelfRate }}</strong>；无适配：<strong>{{ queryCountData.airConditionerFilterOffShelfCount }}</strong>次，<strong>{{ queryCountData.airConditionerFilterOffShelfRate }}</strong>；空(--)：<strong>{{ queryCountData.airConditionerFilterNotExistCount }}</strong>次，<strong>{{ queryCountData.airConditionerFilterNotExistRate }}</strong>；
          </div>
          <div>
            空气滤清器 有适配：<strong>{{ queryCountData.airFilterOnShelfCount }}</strong>次，<strong>{{ queryCountData.airFilterOnShelfRate }}</strong>；无适配：<strong>{{ queryCountData.airFilterOffShelfCount }}</strong>次，<strong>{{ queryCountData.airFilterOffShelfRate }}</strong>；空(--)：<strong>{{ queryCountData.airFilterNotExistCount }}</strong>次，<strong>{{ queryCountData.airFilterNotExistRate }}</strong>；
          </div>
          <div>
            机油滤清器 有适配：<strong>{{ queryCountData.engineOilFilterOnShelfCount }}</strong>次，<strong>{{ queryCountData.engineOilFilterOnShelfRate }}</strong>；无适配：<strong>{{ queryCountData.engineOilFilterOffShelfCount }}</strong>次，<strong>{{ queryCountData.engineOilFilterOffShelfRate }}</strong>；空(--)：<strong>{{ queryCountData.engineOilFilterNotExistCount }}</strong>次，<strong>{{ queryCountData.engineOilFilterNotExistRate }}</strong>；
          </div>
        </div>
      </a-alert>
      <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>
          <a-checkbox-group v-model="showCol" :options="showColItem"/>
        </div>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        bordered>
        <!-- vin -->
        <template slot="vin" slot-scope="text, record">
          <div>
            <span class="table-td-link" @click="handleDetail(record)">{{ record.vinCode }}</span>
          </div>
        </template>
      </s-table>
    </div>
    <div class="unChoose" v-show="!isSearch">
      <a-icon type="exclamation-circle" theme="filled" :style="{ fontSize: '18px', color: '#ff9900', verticalAlign: 'sub', marginRight: '5px' }" />
      <span>请选择一个货架后点击查询按钮</span>
    </div>
    <!-- 详情 -->
    <detailModal :openModal="showDetail" :itemData="curItem" @close="showDetail=false"></detailModal>
  </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 detailModal from './detailModal'
import { queryPage, queryCount, queryDetail, exportVinLog } from '@/api/vinLog'
export default {
  components: { STable, VSelect, rangeDate, shelfSList, detailModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        vinCode: undefined,
        shelfSn: undefined,
        brandName: undefined,
        modelInfo: undefined
      },
      airConditionerFilterData: null,
      airFilterFlagData: null,
      engineOilFilterFlagData: null,
      isSearch: false,
      time: [],
      rules: {
        'shelfSn': [{ required: true, message: '请选择货架', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const dataObj = parameter
        if (dataObj.airConditionerFilterFlagDesc) {
          dataObj.airConditionerFilterFlag = dataObj.airConditionerFilterFlagDesc.toString()
          this.airConditionerFilterData = dataObj.airConditionerFilterFlagDesc.toString()
          delete dataObj.airConditionerFilterFlagDesc
        }
        if (dataObj.airFilterFlagDesc) {
          dataObj.airFilterFlag = dataObj.airFilterFlagDesc.toString()
          this.airFilterFlagData = dataObj.airFilterFlagDesc.toString()
          delete dataObj.airFilterFlagDesc
        }
        if (dataObj.engineOilFilterFlagDesc) {
          dataObj.engineOilFilterFlag = dataObj.engineOilFilterFlagDesc.toString()
          this.engineOilFilterFlagData = dataObj.engineOilFilterFlagDesc.toString()
          delete dataObj.engineOilFilterFlagDesc
        }
        this.disabled = true
        const params = Object.assign(dataObj, this.queryParam, { airConditionerFilterFlag: this.airConditionerFilterData,
          airFilterFlag: this.airFilterFlagData,
          engineOilFilterFlag: this.engineOilFilterFlagData })
        this.spinning = true

        return queryPage(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.getQueryCount(params)
          this.spinning = false
          return data
        })
      },
      queryCountData: null,
      shelfName: '',
      showColItem: [
        { label: '空调滤清器', value: 'kt' },
        { label: '空气滤清器', value: 'kq' },
        { label: '机油滤清器', value: 'jy' }
      ],
      showCol: ['kt', 'kq', 'jy'],
      filters: [{ text: '有', value: 1 }, { text: '无', value: 2 }, { text: '空(--)', value: 0 }],
      showDetail: false,
      curItem: null
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '扫描时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: 'VIN', dataIndex: 'vinCode', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: 'VIN', scopedSlots: { customRender: 'vin' }, width: '15%', align: 'center' },
        { title: '车辆品牌', dataIndex: 'brandName', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '车型', dataIndex: 'modelInfo', width: '24%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true }
      ]
      this.showCol.map(item => {
        if (item == 'kt') {
          arr.push({ title: '空调滤清器适配', dataIndex: 'airConditionerFilterFlagDesc', filters: this.filters, filterMultiple: false, width: '120px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        }
        if (item == 'kq') {
          arr.push({ title: '空气滤清器适配', dataIndex: 'airFilterFlagDesc', filters: this.filters, filterMultiple: false, width: '120px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        }
        if (item == 'jy') {
          arr.push({ title: '机油滤清器适配', dataIndex: 'engineOilFilterFlagDesc', filters: this.filters, filterMultiple: false, width: '120px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        }
      })
      return arr
    }
  },
  methods: {
    shelfChange (v, row) {
      this.shelfName = row ? row.shelfName : ''
    },
    // 累积扫描VIN次数统计
    getQueryCount (ajaxData) {
      queryCount(ajaxData).then(res => {
        if (res.status == 200) {
          this.queryCountData = res.data
        } else {
          this.queryCountData = null
        }
      })
    },
    //  扫描时间  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.$refs.table.refresh(true)
          this.isSearch = true
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.isSearch = false
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.vinCode = undefined
      this.queryParam.shelfSn = undefined
      this.queryParam.brandName = undefined
      this.queryParam.modelInfo = undefined
      this.time = []
      this.$refs.rangeDate.resetDate(this.time)
      this.$refs.ruleForm.resetFields()
      // this.$refs.table.refresh(true)
      this.handleSearch()
    },

    // 导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const newFilterObj = {
            exportAirConditionerFilterFlag: this.showCol.includes('kt') ? 1 : 0,
            exportAirFilterFlag: this.showCol.includes('kq') ? 1 : 0,
            exportEngineOilFilterFlag: this.showCol.includes('jy') ? 1 : 0,

            airConditionerFilterFlag: this.airConditionerFilterData,
            airFilterFlag: this.airFilterFlagData,
            engineOilFilterFlag: this.engineOilFilterFlagData
          }
          const params = Object.assign(this.queryParam, newFilterObj)
          _this.exportLoading = true
          _this.spinning = true
          exportVinLog(params).then(res => {
            downloadExcel(res, 'VIN扫描记录')
            _this.exportLoading = false
            _this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleDetail (row) {
      queryDetail({ id: row.id }).then(res => {
        if (res.status == 200) {
          const detailObj = {
            vinCode: row.vinCode,
            scanTime: row.createDate,
            carType: row.modelInfo
          }
          Object.assign(res.data, detailObj)
          this.curItem = res.data
          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;
  }
  .sTable{
    min-width:1004px;
  }
</style>
