<template>
  <a-drawer
    :zIndex="zIndex"
    :title="title"
    placement="right"
    :visible="visible"
    :width="width"
    :get-container="false"
    :wrap-style="{ position: 'absolute' }"
    @close="onClose"
    wrapClassName="chooseProduct-drawer jg-drawer-wrap">
    <a-spin :spinning="spinning||newLoading" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="searchBox" 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 type="flex" :gutter="5">
            <a-col flex="1">
              <a-form-model-item label="产品编码">
                <a-input id="productInfoList-code" ref="searchProductCode" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <a-col flex="1">
              <a-form-model-item label="产品名称">
                <a-input id="productInfoList-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
              </a-form-model-item>
            </a-col>
            <a-col flex="1">
              <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 flex="1">
              <a-form-model-item label="产品品牌">
                <ProductBrand id="productInfoList-productBrandSn" v-model="queryParam.brandSn"></ProductBrand>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row type="flex" :gutter="5">
            <a-col flex="1.5">
              <a-form-model-item label="产品分类">
                <ProductType id="productInfoList-productType" :isDealer="true" @change="changeProductType" v-model="productType"></ProductType>
              </a-form-model-item>
            </a-col>
            <a-col flex="1.5">
              <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>
            <a-col flex="2" v-if="$hasPermissions('B_salerVinFindProduct')">
              <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" accept="image/jpeg,image/png" hidden="" @change="filePreview">
              </a-form-model-item>
            </a-col>
            <a-col flex="200px">
              <a-form-item label="是否有库存">
                <a-select @change="handleHasQty" allowClear :value="queryParam.existStockFlag" placeholder="请选择是否">
                  <a-select-option value="1">
                    是
                  </a-select-option>
                  <a-select-option value="0">
                    否
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="auto">
              <a-button type="primary" @click="searchForm()" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" id="productInfoList-reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form-model>

        <div v-if="hasVaild&&showTable" class="vinInfo-box">
          <div>
            <div class="vinInfo-error" v-if="vinInfoData&&!vinInfoData.vinInfo">
              <a-icon type="exclamation-circle" :style="{ color: '#E70012', fontSize: '15px', verticalAlign: 'sub', marginRight: '3px' }" />抱歉！暂未找到匹配VIN码的车型！
            </div>
            <div v-if="vinInfoData&&vinInfoData.vinInfo" @click="openCarInfoModal=true">
              <div style="display: flex;justify-content: space-between;align-items: center;" @click="openCarInfoModal=true">
                <div>
                  <img :src="vinInfoData.vinInfo && vinInfoData.vinInfo.icon?(vinInfoData.vinInfo.icon+'?x-oss-process=image/resize,h_30,m_lfit'):defImg" width="30" height="30" class="imageUrl" style="border-radius: 50%;vertical-align: middle;margin-right: 3px;" />
                  <span style="vertical-align: middle;">{{ vinInfoData.vinInfo.text }}</span>
                </div>
                <div style="color: #f90;cursor: pointer;">
                  <span>查看更多</span> >
                </div>
              </div>
            </div>
          </div>
          <div>
            <a-dropdown v-model="showCell">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                <a-icon type="setting" /> 显示
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="$hasPermissions('M_ShowAllCost')" >
                  <a-checkbox v-model="cost" id="salesQuery-cost">成本价</a-checkbox>
                </a-menu-item>
                <a-menu-item v-if="$hasPermissions('M_ShowAllCityPrice')&&$store.state.user.dealerLevel != 'SPECIAL'">
                  <a-checkbox v-model="cityPrice" id="salesQuery-cityPrice">市级价</a-checkbox>
                </a-menu-item>
                <a-menu-item v-if="$store.state.user.isShowSpecialPrice==1" >
                  <a-checkbox v-model="tyuePrice"id="salesQuery-tyuePrice">特约价</a-checkbox>
                </a-menu-item>
                <a-menu-item>
                  <a-checkbox v-model="zdPrice" id="salesQuery-zdPrice">终端价</a-checkbox>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </div>
      </div>

      <!-- 列表 -->
      <s-table
        v-if="hasVaild&&showTable"
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.no"
        rowKeyName="no"
        :columns="columns"
        :data="loadData"
        @dblclick="handleClickRow"
        :pageSize="30"
        :scroll="{ y: tableHeight, x: tableWidth }"
        bordered>
        <div slot="costTitle">
          <a-tooltip placement="top">
            <template slot="title">
              产品所在仓库仓位的最近一次入库成本，不包含盘盈入库和仓库调拨入库。
            </template>
            <span style="margin-right: 5px;">参考成本价</span> <a-icon type="question-circle" />
          </a-tooltip>
        </div>
        <!-- 售价 -->
        <template slot="salePrice" slot-scope="text, record">
          <div style="display: flex;align-items: center;" @dblclick.stop>
            <a-input-number
              size="small"
              v-model="record.price"
              :precision="2"
              :min="0"
              :max="999999"
              style="width: 100%;"
              placeholder="请输入" />
            <span style="color: red;margin: 0 2px;font-size: 14px;" v-if="record.origSalePriceFlag == 1">原</span>
            <span v-else>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
          </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"
              style="width: 100%;"
              placeholder="请输入" />
          </div>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click="handleAdd(record)"
            id="productInfoList-edit-btn">添加</a-button>
          <a-button
            size="small"
            type="link"
            class="button-primary"
            @click="handleDetail(record)"
            id="productInfoList-detail-btn"
            style="margin-left: 5px;">销售记录</a-button>
        </template>
      </s-table>
      <div style="padding-top: 30px;" v-else>
        <a-empty
          :image="simpleImage"
          :image-style="{
            height: '60px',
          }"
        >
          <span style="color:red" slot="description">请输入查询条件</span>
        </a-empty>
      </div>

      <!-- 查看车辆信息 -->
      <car-info-modal ref="carInfoModal" :openModal="openCarInfoModal" :infoData="vinInfoData&&vinInfoData.vinInfo" @close="openCarInfoModal=false" />
    </a-spin>
  </a-drawer>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { commonMixin } from '@/utils/mixin'
import { querySumByProductLocation } from '@/api/stock'
import { warehouseAllList } from '@/api/warehouse'
import carInfoModal from './carInfoModal.vue'
import ProductType from '../../common/productType.js'
import ProductBrand from '../../common/productBrand.js'
import { STable, VSelect, Upload } from '@/components'
import { supperCodeByVin, vinCodeParse } from '@/api/sales'
import defImg from '@/assets/def_img@2x.png'
export default {
  mixins: [commonMixin],
  components: { STable, VSelect, Upload, carInfoModal, ProductType, ProductBrand },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    width: {
      type: [String, Number],
      default: '80%'
    },
    zIndex: {
      type: Number,
      default: 100
    },
    newLoading: {
      type: Boolean
    },
    checkedList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    showModal (newValue, oldValue) {
      this.visible = newValue
      if (newValue) {
        this.$refs.searchProductCode.focus()
        this.setTableH()
      }
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  data () {
    return {
      showCell: false,
      spinning: false,
      showTable: false,
      visible: this.showModal,
      title: '添加产品',
      tableHeight: 0,
      tableWidth: 1760,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      advanced: false, // 高级搜索 展开/关闭
      vinLoading: false,
      productType: [],
      defImg,
      queryParam: { //  查询条件
        customerSn: '',
        salesBillSn: '',
        salePriceType: '',
        productCode: '', //  产品编码
        productName: '', //  产品名称
        productOrigCode: '', //  原厂编码
        vinCode: '',
        productCodeList: undefined, //  车架号
        brandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        warehouseSn: undefined, //  仓库、
        enableFlag: '1',
        existStockFlag: undefined
      },
      priceType: '',
      buyerSn: '',
      rules: {
        vinCode: [ { len: 17, message: '请输入正确的车架号(VIN)', trigger: 'change' } ]
      },
      disabled: false, //  查询、重置按钮是否可操作
      warehouseList: [], // 仓库列表
      vinInfoData: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const _this = this
        _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'
        }
        const params = Object.assign(parameter, _this.queryParam)
        if (_this.queryParam.vinCode && _this.queryParam.vinCode.length == 17 && !this.onlyList) { //  输入vin，查出vin码信息后请求列表数据
          _this.disabled = true
          return supperCodeByVin({ vin: _this.queryParam.vinCode }).then(res => {
            if (res.status == 200) {
              _this.vinInfoData = res.data
              params.productCodeList = res.data.partCodeList || []
              return _this.getList(params)
            } else {
              _this.vinInfoData = null
              _this.$refs.table.localLoading = false
              _this.$refs.table.clearTable()
            }
          })
        } else if (_this.queryParam.vinCode && _this.queryParam.vinCode.length < 17 && !this.onlyList) { // 输入vin，但vin码不符合标准，不查vin码信息，不请求列表数据
          _this.$refs.table.localLoading = false
          _this.$refs.table.clearTable()
        } else if (this.onlyList) {
          _this.disabled = true
          if (_this.queryParam.vinCode && _this.vinInfoData) {
            return _this.getList(Object.assign(params, { productCodeList: _this.vinInfoData.partCodeList }))
          } else {
            return _this.getList(params)
          }
        } else { //  未输入vin码信息，只查列表数据
          _this.disabled = true
          return _this.getList(params)
        }
      },
      openModal: false, //  查看客户详情  弹框
      cost: false, // 成本价
      cityPrice: false, // 城市价
      tyuePrice: false, // 特约价
      zdPrice: false, // 终端价
      openCarInfoModal: false,
      onlyList: false
    }
  },
  computed: {
    hasVaild () {
      return this.queryParam.productCode || this.queryParam.productName || this.queryParam.brandSn || this.queryParam.productTypeSn1 || this.queryParam.warehouseSn || this.queryParam.existStockFlag || this.queryParam.vinCode
    },
    columns () {
      const _this = this
      const arr = [
        { title: '产品编码', dataIndex: 'productCode', width: '150px', align: 'center', sorter: true, customRender: function (text) { return text || '--' }, fixed: 'left' },
        { title: '产品名称', dataIndex: 'productName', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '150px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'brandName', width: '120px', align: 'center', sorter: true, customRender: function (text) { return text || '--' } }
      ]
      if (this.cost) {
        this.tableWidth += 100
        arr.push({ slots: { title: 'costTitle' }, dataIndex: 'putCost', width: '100px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      } else {
        this.tableWidth -= 100
      }
      if (this.cityPrice && this.$hasPermissions('M_ShowAllCityPrice')) {
        this.tableWidth += 80
        arr.push({ title: '市级价', dataIndex: 'dealerProduct.cityPrice', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      } else {
        this.tableWidth -= 80
      }
      if (this.tyuePrice) {
        this.tableWidth += 80
        arr.push({ title: '特约价', dataIndex: 'dealerProduct.specialPrice', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      } else {
        this.tableWidth -= 80
      }
      if (this.zdPrice) {
        this.tableWidth += 80
        arr.push({ title: '终端价', dataIndex: 'dealerProduct.terminalPrice', width: '80px', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      } else {
        this.tableWidth -= 80
      }

      return arr.concat([
        { title: '仓库', dataIndex: 'warehouseName', width: '120px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '120px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'unit', width: '60px', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'currentQty', width: '100px', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') }, fixed: 'right' },
        { title: '售价', dataIndex: 'salePrice', scopedSlots: { customRender: 'salePrice' }, width: '120px', align: 'center', fixed: 'right' },
        { title: '销售数量', dataIndex: 'salesNums', scopedSlots: { customRender: 'nums' }, width: '100px', align: 'center', fixed: 'right' },
        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '120px', align: 'center', fixed: 'right' }
      ])
    }
  },
  created () {
    // 仓库
    if (this.warehouseList.length == 0) {
      this.getWarehouse()
    }
  },
  methods: {
    // 查询
    searchForm () {
      if (this.hasVaild) {
        this.showTable = true
        if (this.$refs.table) {
          this.$refs.table.refresh(true)
        }
      } else {
        this.showTable = false
        this.$message.info('请输入查询条件')
      }
    },
    getList (params) {
      const _this = this
      return querySumByProductLocation(params).then(res => {
        let data
        this.onlyList = false
        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 = data.list[i].productSn + '_' + (no + i + 1)
            data.list[i].salesNums = 1
            data.list[i].currentQty = data.list[i].currentQty || 0
            data.list[i].price = data.list[i].origSalePriceFlag == 0 ? data.list[i].lastSalePrice : data.list[i].origSalePriceFlag == 1 ? data.list[i].salePrice : data.list[i].selfSaleprice
            data.list[i].productOrigCode = data.list[i].productOrigCode ? data.list[i].productOrigCode.trim() : ''
          }
          if (!params.vinCode) {
            _this.vinInfoData = null
          }
        } else {
          data = {
            list: [],
            pageNo: 1,
            pageSize: 10
          }
        }
        _this.disabled = false
        console.log(data)
        return data
      })
    },
    // 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) {
      this.$emit('add', record)
    },
    //  重置
    resetSearchForm (flag) {
      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.existStockFlag = undefined
      this.queryParam.vinCode = ''
      this.productType = []
      this.$refs.ruleForm.resetFields()
      this.vinInfoData = null
      this.showTable = false

      if (!flag) {
        this.$refs.table.refresh(true)
      }
    },
    pageInit (buyerSn, priceType, salesBillSn) {
      this.priceType = priceType || ''
      this.buyerSn = buyerSn || ''
      this.queryParam.salesBillSn = salesBillSn || ''
    },
    // 刷新当前页面
    resetCurForm () {
      this.$refs.table.refresh()
    },
    // 清空数据
    clearTable () {
      this.vinInfoData = null
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 选择配件
    handleAdd (row) {
      const _this = this
      console.log(row.price, row.lastSalePrice, row.salePrice, row.lastSalePrice < row.salePrice)
      if (row.lastSalePrice && (row.price < row.salePrice)) {
        _this.$confirm({
          title: '提示',
          content: '售价低于定价，是否仍继续添加？',
          centered: true,
          closable: true,
          onOk () {
            _this.$emit('add', row)
          }
        })
      } else {
        _this.$emit('add', row)
      }
    },
    // 销售记录
    handleDetail (row) {
      this.$emit('viewRecord', row)
    },
    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({ wasteFlag: 0 }).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    //  产品分类  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] : ''
    },
    // 查看是否有库存、
    handleHasQty (val) {
      this.queryParam.existStockFlag = val
    },
    onClose () {
      this.resetSearchForm(true)
      this.$emit('close')
    },
    setTableH () {
      this.$nextTick(() => {
        const searchBoxH = this.$refs.searchBox.offsetHeight
        this.tableHeight = window.innerHeight - searchBoxH - 245
      })
    }
  }
}
</script>

<style lang="less">
.chooseProduct-drawer {
  .ant-drawer-header{
    padding: 13px 20px;
  }
  .ant-drawer-body {
    padding: 15px 20px;
    height: calc(100% - 50px);
    display: flex;
    flex-direction: column;
    overflow: auto;
    > div {
      height: 100%;
    }
    .noStock{
      text-decoration: line-through;
      color: red;
    }
    .ant-input-number-sm input{
      text-align: center;
    }
    .vinInfo-box{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .vinInfo-error{
        color: red;
      }
    }
  }
}
</style>
