<template>
  <div>
    <a-card size="small" :bordered="false" class="productSourceList-wrap searchBox">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form
          id="productSourceList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="审核时间">
                <rangeDate ref="rangeDate" id="productSourceList-time" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="业务单号">
                <a-input
                  id="productSourceList-bizCode"
                  v-model.trim="queryParam.bizCode"
                  allowClear
                  placeholder="请输入业务单号" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品编码">
                <a-input
                  id="productSourceList-productCode"
                  v-model.trim="queryParam.productCode"
                  allowClear
                  placeholder="请输入产品编码" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="唯一码">
                <a-input
                  id="productSourceList-traceCode"
                  v-model.trim="queryParam.traceCode"
                  allowClear
                  placeholder="请输入唯一码" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="单据类型">
                  <a-select @change="handleBizStatus" id="productSourceList-bizStatus" v-model="queryParam.bizStatus" placeholder="请选择单据类型" allowClear>
                    <a-select-option value="XS">
                      销售单
                    </a-select-option>
                    <a-select-option value="DB">
                      调拨单
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品名称">
                  <a-input
                    id="productSourceList-productName"
                    v-model.trim="queryParam.productName"
                    allowClear
                    placeholder="请输入产品名称" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="客户名称">
                  <a-input
                    id="productSourceList-buyerName"
                    v-model.trim="queryParam.buyerName"
                    allowClear
                    placeholder="请输入客户名称" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="质保状态">
                  <a-select v-model="queryParam.warrantyState" id="productSourceList-warrantyState" placeholder="请选择质保状态" allowClear>
                    <a-select-option value="NOTSTART">
                      未开始
                    </a-select-option>
                    <a-select-option value="RUN">
                      进行中
                    </a-select-option>
                    <a-select-option value="END">
                      已过期
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="24" :sm="24" style="text-align: center;">
              <a-button
                style="margin-left: 5px"
                type="primary"
                @click="$refs.table.refresh(true)"
                :disabled="disabled"
                id="productSourceList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="productSourceList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_productSourceExport')"
                id="productSourceList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px" id="productSourceList-advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </a-col>
          </a-row>
          </a-form-model>
        </a-form></div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 统计 -->
        <div style="display:flex;align-items:center;margin-bottom:10px;">
          <a-button
            type="primary"
            id="productSourceList-import-btn"
            :loading="loading"
            v-if="$hasPermissions('B_productSourceImport')"
            @click="openGuideModal = true">导入</a-button>
          <div class="tongji-bar" style="margin-left:10px;">
            产品总款数：<strong>{{ totalData&&(totalData.productTypeNum || totalData.productTypeNum==0) ? totalData.productTypeNum : '0' }}</strong>；
            产品总数量：<strong>{{ totalData&&(totalData.productNum || totalData.productNum==0) ? totalData.productNum : '--' }}</strong>；
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight-10 }"
          :defaultLoadData="false"
          bordered>
          <!-- 质保时间 -->
          <template slot="warrantyTime" slot-scope="text, record">
            <span v-if="record.warrantyStartDate">
              {{ record.warrantyStartDate }}{{ record.warrantyEndDate?'至'+record.warrantyEndDate:'' }}
            </span>
            <span v-else>--</span>
          </template>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              :id="'productSourceList-info'+record.id"
              v-if="$hasPermissions('B_productSourceSeeInfo')&&record.warrantyState!='NOTSTART'"
              size="small"
              type="link"
              class="button-warning"
              @click="handleInfoModal(record)">质保信息</a-button>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-spin>
      <!-- 质保信息-->
      <warranty-info-modal v-drag :openModal="openInfoModal" :productCode="productCodeInfo" :itemSn="warrantyInfoId" @close="closeWarranty" />
      <!-- 导入轮胎唯一码 -->
      <importGuideModal :openModal="openGuideModal" @close="openGuideModal=false" @ok="handleGuideOk" />
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import warrantyInfoModal from './warrantyInfoModal.vue'
import importGuideModal from './importGuideModal.vue'
// 接口
import { traceCodeInsertBatch, traceCodeQueryCount, traceCodeList, excelOnlineList } from '@/api/reportData'
export default {
  name: 'ProductSourceList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, warrantyInfoModal, importGuideModal },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      loading: false, // 表格加载状态
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      // 审核时间
      time: [
        getDate.getThreeMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      queryParam: { //  查询条件
        beginDate: getDate.getThreeMonthDays().starttime, // 审核开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 审核结束时间
        productCode: '', // 产品编码
        productName: '', // 产品名称
        bizCode: undefined, // 业务单号
        traceCode: undefined, // 唯一码
        buyerName: undefined, // 客户名称
        bizStatus: undefined, // 单据类型
        warrantyState: undefined// 质保状态
      },
      openInfoModal: false, // 质保信息弹窗
      columns: [{ title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '业务单号', dataIndex: 'bizCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核时间', dataIndex: 'auditDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '导入时间', dataIndex: 'importDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '唯一码', dataIndex: 'traceCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'buyerName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '质保状态', dataIndex: 'warrantyStateDictValue', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '质保时间', scopedSlots: { customRender: 'warrantyTime' }, width: '10%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '12%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        // 获取表格数据 有分页
        return traceCodeList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 获取统计数据
            this.getCount(params)
            // 计算表格序号
            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
        })
      },
      totalData: null, // 统计数据
      openGuideModal: false, // 导入弹窗
      warrantyInfoId: null, // 质保信息id
      productCodeInfo: null// 当前行产品编码
    }
  },
  watch: {
    // 展开/关闭 监听表格高度变化
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 单据类型操作
    handleBizStatus (val) {
      this.queryParam.bizStatus = val
    },
    // 导入成功
    handleGuideOk (resData) {
      traceCodeInsertBatch(resData).then(res => {
        if (res.status == 200) {
          this.resetSearchForm()
        }
      })
    },
    // 统计
    getCount (params) {
      traceCodeQueryCount(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  审核时间  change
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    // 质保信息
    handleInfoModal (row) {
      this.warrantyInfoId = row.warrantyid
      this.productCodeInfo = row.productCode
      this.openInfoModal = true
    },
    // 关闭质保信息弹窗
    closeWarranty () {
      this.warrantyInfoId = null
      this.productCodeInfo = null
      this.openInfoModal = false
    },

    //  重置
    resetSearchForm () {
      this.time = [
        getDate.getThreeMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.totalData = null
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.bizCode = undefined
      this.queryParam.traceCode = undefined
      this.queryParam.buyerName = undefined
      this.queryParam.bizStatus = undefined
      this.queryParam.warrantyState = undefined
      this.$refs.table.refresh(true)
    },
    //  导出
    handleExport () {
      const _this = this
      const params = _this.queryParam
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(excelOnlineList, params, '唯一码追溯列表', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 247
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
