<template>
  <a-card size="small" :bordered="false" class="chainStockReportList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          id="chainStockReportList-form"
          ref="ruleForm"
          :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="dealerSn">
                <a-select
                  placeholder="请选择连锁店"
                  id="chainStockReportList-dealerSn"
                  allowClear
                  v-model="queryParam.dealerSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in linkageGroupData" :key="item.dealerSn" :value="item.dealerSn">{{ item.dealerName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品编码">
                <a-input id="chainStockReportList-code" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品名称">
                <a-input id="chainStockReportList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="原厂编码">
                  <a-input id="chainStockReportList-origCode" v-model.trim="queryParam.productOrigCode" allowClear placeholder="请输入原厂编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品品牌">
                  <a-select
                    placeholder="请选择产品品牌"
                    id="chainStockReportList-productBrandSn"
                    allowClear
                    v-model="queryParam.productBrandSn"
                    :showSearch="true"
                    option-filter-prop="children"
                    :filter-option="filterOption">
                    <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn">{{ item.brandName }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品分类">
                  <a-cascader
                    @change="changeProductType"
                    change-on-select
                    v-model="productType"
                    expand-trigger="hover"
                    :options="productTypeList"
                    :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                    id="chainStockReportList-productType"
                    placeholder="请选择产品分类"
                    allowClear />
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-top: 3px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="chainStockReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="chainStockReportList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- 合计 -->
      <a-alert type="info" showIcon style="margin-bottom:15px">
        <div class="ftext" slot="message">
          现有库存总数量（个）：<strong> {{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }} </strong>；
          现有库存总成本(￥)：<strong> {{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? totalData.totalCost : '--' }} </strong>。
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.productSn + record.stockSn"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        :scroll="{ x: 1170 }"
        bordered>
        <!-- 现有库存数量 -->
        <template slot="currentStockQty" slot-scope="text, record">
          {{ (Number(record.currentStockQty) + Number(record.freezeQty)) || 0 }}
          <span v-if="Number(record.freezeQty)">（冻结{{ record.freezeQty }}）</span>
        </template>
        <template slot="currentStockCost" slot-scope="text, record">
          {{ (Number(record.currentStockCost)*1000 + Number(record.freezeCost)*1000)/1000 || 0 }}
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button size="small" type="link" class="button-success" @click="goDetail(record)" id="chainStockReportList-detail-btn">详情</a-button>
        </template>
      </s-table>
    </a-spin>
    <!-- 详情 -->
    <chain-stock-report-detail-modal :openModal="openModal" :productSn="productSn" @close="closeModal" />
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import chainStockReportDetailModal from './detailModal.vue'
import { dealerProductBrandQuery } from '@/api/dealerProductBrand'
import { dealerProductTypeList } from '@/api/dealerProductType'
import { linkageGroupList } from '@/api/reportData'
import { reportStockList, reportStockCount } from '@/api/reportStock'
export default {
  components: { STable, VSelect, chainStockReportDetailModal },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        dealerSn: undefined,
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品分类1
        productTypeSn2: '', //  产品分类2
        productTypeSn3: '' //  产品分类3
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      rules: {
        'dealerSn': [{ required: true, message: '请选择连锁店', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center', fixed: 'left' },
        { title: '产品编码', dataIndex: 'productCode', width: 220, align: 'center', customRender: function (text) { return text || '--' }, sorter: true },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '现有库存数量(个)', dataIndex: 'currentStockQty', scopedSlots: { customRender: 'currentStockQty' }, width: 165, align: 'center', sorter: true },
        { title: '现有库存成本(￥)', dataIndex: 'currentStockCost', scopedSlots: { customRender: 'currentStockCost' }, width: 165, align: 'center', sorter: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 100, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        if (params.dealerSn) {
          if (params.dealerSn == 'all') {
            params.dealerSn = ''
          }
          return reportStockList(params).then(res => {
            // 总计
            this.getCount(params)
            const 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
          })
        } else {
          const _this = this
          return new Promise(function (resolve, reject) {
            const data = {
              pageNo: 1,
              pageSize: 10,
              list: [],
              count: 0
            }
            _this.disabled = false
            _this.spinning = false
            _this.$message.info('请选择连锁店')
            resolve(data)
          })
        }
      },
      productType: [],
      linkageGroupData: [],
      productBrandList: [], //  品牌下拉数据
      productTypeList: [], //  分类下拉数据
      allocateTypeList: [], //  调拨类型
      totalData: null, //  合计
      productSn: '',
      openModal: false //  弹框
    }
  },
  methods: {
    // 合计
    getCount (params) {
      reportStockCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.dealerSn = undefined
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.productType = []
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    //  详情
    goDetail (row) {
      this.productSn = row.productSn
      this.openModal = true
    },
    //  关闭弹框
    closeModal () {
      this.productSn = ''
      this.openModal = false
    },
    //  产品分类  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] : ''
    },
    //  产品品牌  列表
    getProductBrand () {
      dealerProductBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  列表
    getProductType () {
      dealerProductTypeList({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 连锁店
    getLinkageGroup () {
      linkageGroupList({}).then(res => {
        const all = [{ dealerName: '全部', dealerSn: 'all' }]
        if (res.status == 200) {
          const data = res.data || []
          this.linkageGroupData = [...all, ...data]
        } else {
          this.linkageGroupData = all
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getLinkageGroup()
      vm.getProductBrand()
      vm.getProductType()
    })
  }
}
</script>
