<template>
  <div class="productInfoList-wrap">
    <!-- 搜索条件 -->
    <div class="table-page-search-wrapper">
      <a-form-model
        ref="ruleForm"
        class="form-model-con"
        layout="inline"
        :rules="rules"
        :model="queryParam"
        @keyup.enter.native="$refs.table.refresh(true)" >
        <a-row :gutter="5">
          <a-col :md="6" :sm="24">
            <a-form-model-item label="车架号(VIN)" prop="vinCode">
              <a-input id="productInfoList-vinCode" v-model.trim="queryParam.vinCode" allowClear placeholder="请输入车架号(VIN)">
                <a-icon @click="uploadFun" :type="vinLoading?'loading':'camera'" slot="addonAfter" :style="{ fontSize: '18px', verticalAlign: 'bottom' }" />
              </a-input>
              <input type="file" id="filed" hidden="" @change="filePreview">
            </a-form-model-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-model-item label="产品编码">
              <a-input id="productInfoList-code" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-model-item label="产品名称">
              <a-input id="productInfoList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-model-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-model-item label="原厂编码">
                <a-input id="productInfoList-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-cascader
                  @change="changeProductType"
                  change-on-select
                  v-model="productType"
                  expand-trigger="hover"
                  :options="productTypeList"
                  :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                  id="productInfoList-productType"
                  placeholder="请选择产品分类"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-model-item label="产品品牌">
                <a-select
                  placeholder="请选择产品品牌"
                  id="productInfoList-productBrandSn"
                  allowClear
                  v-model="queryParam.brandSn"
                  :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="5" :sm="24">
              <a-form-model-item label="仓库">
                <a-select
                  placeholder="请选择仓库"
                  id="productInfoList-warehouseSn"
                  allowClear
                  v-model="queryParam.warehouseSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in warehouseList" :key="item.warehouseSn" :value="item.warehouseSn">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :md="8" :sm="24" style="margin-bottom: 10px;">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" id="productInfoList-reset">重置</a-button>
            <a @click="advanced=!advanced" style="margin:0 5px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
            <a-checkbox v-model="cost" id="salesQuery-cost">成本价</a-checkbox>
            <a-checkbox v-model="cityPrice" id="salesQuery-cityPrice">市级价</a-checkbox>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="small"
      :rowKey="(record) => record.productSn+record.currentQty"
      :columns="columns"
      :data="loadData"
      :customRow="handleClickRow"
      :defaultLoadData="false"
      :scroll="{ x: 1290, y: 300 }"
      bordered>
      <!-- 售价 -->
      <template slot="salePrice" slot-scope="text, record">
        <div @dblclick.stop>
          <a-input-number
            size="small"
            v-model="record.salePrice"
            :precision="2"
            :min="0"
            :max="999999"
            placeholder="请输入" />
        </div>
      </template>
      <!-- 销售数量 -->
      <template slot="nums" slot-scope="text, record">
        <div @dblclick.stop>
          <a-input-number
            size="small"
            v-model="record.salesNums"
            :precision="0"
            :min="0"
            :max="999999"
            placeholder="请输入" />
        </div>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="primary"
          class="button-info"
          @click="handleAdd(record)"
          id="productInfoList-edit-btn">添加</a-button>
        <a-button
          size="small"
          type="primary"
          class="button-success"
          @click="handleDetail(record)"
          id="productInfoList-detail-btn"
          style="margin-left: 5px;">销售记录</a-button>
      </template>
    </s-table>
    <!-- 销售记录 -->
    <product-salesRecord-modal ref="salseRecord" :openModal="openModal" @close="closeModal" />
  </div>
</template>

<script>
import { dealerProductBrandQuery } from '@/api/dealerProductBrand'
import { dealerProductTypeList } from '@/api/dealerProductType'
import { querySumByProductLocation } from '@/api/stock'
import { warehouseAllList } from '@/api/warehouse'
import productSalesRecordModal from './productSalesRecordModal.vue'
import { STable, VSelect, Upload } from '@/components'
import { supperCodeByVin, vinCodeParse } from '@/api/sales'
export default {
  name: 'QueryPart',
  components: { STable, VSelect, Upload, productSalesRecordModal },
  props: {
    buyerSn: {
      type: [Number, String],
      default: ''
    },
    priceType: {
      type: [Number, String],
      default: ''
    },
    newLoading: Boolean
  },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      vinLoading: false,
      productType: [],
      queryParam: { //  查询条件
        customerSn: '',
        salePriceType: '',
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        vinCode: '',
        productCodeList: undefined, //  车架号
        brandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        warehouseSn: undefined //  仓库
      },
      rules: {
        vinCode: [ { len: 17, message: '请输入正确的车架号(VIN)', trigger: 'change' } ]
      },
      disabled: false, //  查询、重置按钮是否可操作
      productBrandList: [], //  下拉数据
      productTypeList: [], //  产品分类  下拉数据
      warehouseList: [], // 仓库列表
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.queryParam.salePriceType = this.priceType
        this.queryParam.customerSn = this.buyerSn
        // 排序
        if (parameter.sortField == 'productCode') {
          parameter.sortField = 'code'
          parameter.sortAlias = 'product '
        }
        if (parameter.sortField == 'brandName') {
          parameter.sortField = 'firstChar'
          parameter.sortAlias = 'brand'
        }
        if (parameter.sortField == 'warehouseName') {
          parameter.sortField = 'warehouseSn'
          parameter.sortAlias = 'sd'
        }
        return querySumByProductLocation(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            data.list = data.list.filter(item => item != null)
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              data.list[i].salesNums = 1
              data.list[i].currentQty = data.list[i].currentQty || 0
            }
          } else {
            data = {
              list: [],
              pageNo: 1,
              pageSize: 20
            }
          }
          this.disabled = false
          return data
        })
      },
      openModal: false, //  查看客户详情  弹框
      cost: false,
      cityPrice: false
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '产品编码', dataIndex: 'productCode', align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', width: 100, align: 'center', sorter: true, customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'currentQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'unit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价', dataIndex: 'salePrice', scopedSlots: { customRender: 'salePrice' }, width: 100, align: 'center' },
        { title: '销售数量', dataIndex: 'salesNums', scopedSlots: { customRender: 'nums' }, width: 100, align: 'center' },
        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: 150, align: 'center', fixed: 'right' }
      ]
      if (this.cost) {
        arr.splice(6, 0, { title: '成本价', dataIndex: 'putCost', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      if (this.cityPrice) {
        arr.splice(this.cost ? 7 : 6, 0, { title: '市级价', dataIndex: 'dealerProduct.cityPrice', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  created () {
    // 产品品牌
    if (this.productBrandList.length == 0) {
      this.getProductBrand()
    }
    // 产品分类
    if (this.productTypeList.length == 0) {
      this.getProductType()
    }
    // 仓库
    if (this.warehouseList.length == 0) {
      this.getWarehouse()
    }
  },
  methods: {
    // vin  change
    vinCodeChange (e) {
      if (e.target.value.length == 17) {
        supperCodeByVin({ vin: e.target.value }).then(res => {
          if (res.status == 200) {
            this.queryParam.productCodeList = res.data
          } else {
            this.queryParam.productCodeList = undefined
          }
        })
      } else {
        this.queryParam.productCodeList = undefined
      }
    },
    // 双击列表
    handleClickRow (record) {
      const _this = this
      return {
        on: {
          dblclick: (event) => {
            event.stopPropagation()
            _this.$emit('add', record)
          }
        }
      }
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productCode = ''
      this.queryParam.productName = ''
      this.queryParam.productOrigCode = ''
      this.queryParam.brandSn = undefined
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.productCodeList = undefined
      this.queryParam.vinCode = ''
      this.productType = []
      this.$refs.table.refresh(true)
      this.$refs.ruleForm.resetFields()
    },
    // 刷新当前页面
    resetCurForm () {
      this.$refs.table.refresh()
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 选择配件
    handleAdd (row) {
      this.$emit('add', row)
    },
    // 销售记录
    handleDetail (row) {
      this.openModal = true
      this.$refs.salseRecord.getDetail(this.buyerSn, row.productSn)
    },
    //  关闭弹框
    closeModal () {
      this.openModal = false
    },
    uploadFun () {
      document.getElementById('filed').click()
    },
    filePreview (e) {
      const _this = this
      var files = e.target.files[0]
      const formData = new FormData()
      formData.append('savePathType', 'local')
      formData.append('file', files)
      this.vinLoading = true
      vinCodeParse(formData).then(res => {
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            if (obj.status == 200) {
              _this.queryParam.vinCode = obj.data || ''
              // 移除表单项的校验结果
              _this.$refs.ruleForm.clearValidate('vinCode')
            } else {
              _this.$notification.error({
                message: '提示',
                description: obj.message
              })
            }
            _this.vinLoading = false
            document.getElementById('filed').value = ''
          })
          reader.readAsText(res)
        } else {
          _this.vinLoading = false
        }
      })
    },
    // 仓库
    getWarehouse () {
      warehouseAllList({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    //  产品品牌  列表
    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 = []
        }
      })
    },
    //  产品分类  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] : ''
    }
  },
  watch: {
    cost (newValue, oldValue) {
      this.$emit('isCost', newValue)
    }
  }
}
</script>
