<template>
  <div class="productInfoEdit-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="productInfoEdit-back" v-if="pageType=='pages'">
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle">
          <a id="productInfoEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="productInfoEdit-table-page-wrapper">
        <a-form-model
          id="productInfoEdit-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <a-form-model-item label="产品名称" prop="name">
            <a-input
              id="productInfoEdit-name"
              :maxLength="100"
              v-model.trim="form.name"
              placeholder="请输入产品名称(最多100个字符)"
              ref="name"
              @keydown.enter.native="nextFocus('name', 'code', $event)"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="产品编码" prop="code">
            <a-input
              id="productInfoEdit-code"
              :maxLength="100"
              :disabled="isEdit"
              v-model.trim="form.code"
              placeholder="请输入产品编码(最多100个字符)"
              ref="code"
              @keydown.enter.native="nextFocus('code', 'origCode', $event)"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="原厂编码" prop="origCode">
            <a-input
              id="productInfoEdit-origCode"
              :maxLength="200"
              v-model.trim="form.origCode"
              placeholder="请输入原厂编码(最多200个字符,多个编码用逗号隔开)"
              ref="origCode"
              @keydown.enter.native="nextFocus('origCode', 'unit', $event)"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="基本单位" prop="unit">
            <a-input-group compact>
              <a-input
                style="width: 70%"
                v-model.trim="form.unit"
                id="productInfoEdit-unit-input"
                placeholder="请输入基本单位"
                ref="unit"
                @keydown.enter.native="nextFocus('unit', 'UNIT', $event, 'vSelect')"
                allowClear/>
              <v-select
                style="width: 30%"
                code="UNIT"
                @change="unitChange"
                id="productInfoEdit-unit"
                ref="UNIT"
                @keydown.enter.native="nextFocus('UNIT', 'productBrandSn', $event)"
                placeholder="快速选择单位"></v-select>
            </a-input-group>
          </a-form-model-item>
          <a-form-model-item label="产品品牌" prop="productBrandSn">
            <a-select
              :showSearch="true"
              id="productInfoEdit-productBrand"
              v-model="form.productBrandSn"
              placeholder="请输入名称搜索，如果没有请点击 '+' 新增"
              :disabled="isEdit"
              :filter-option="filterOption"
              option-filter-prop="children"
              allowClear
              style="width: 90%;"
              ref="productBrandSn"
              @keydown.enter.native="nextFocus('productBrandSn', 'productType', $event)"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn" :disabled="item.enabledFlag==0">{{ item.brandName }}</a-select-option>
            </a-select>
            <a-button
              v-if="$hasPermissions('B_product_dealerProductBrand_add')"
              @click="openModal=true"
              :disabled="isEdit"
              icon="plus"
              size="small"
              id="productInfoEdit-add-btn"
              style="margin-left: 5px;"></a-button>
          </a-form-model-item>
          <a-form-model-item label="产品分类" prop="productType">
            <a-spin v-if="loadingPtype" size="small" />
            <a-cascader
              :disabled="isEdit"
              v-if="!loadingPtype&&productTypeList.length"
              @change="changeProductType"
              expand-trigger="hover"
              :options="productTypeList"
              :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
              id="productInfoEdit-productType"
              placeholder="请选择产品分类"
              allowClear
              v-model="form.productType"
              ref="productType"
              @keydown.enter.native="nextFocus('productType', 'specialPrice', $event)" />
            <a-button v-if="!loadingPtype&&productTypeList.length==0" type="link" @click="getProductType">重新加载</a-button>
          </a-form-model-item>

          <a-form-model-item label="经销批发价" prop="specialPrice">
            <a-input-number
              id="productInfoEdit-specialPrice"
              v-model="form.specialPrice"
              :min="0"
              :max="999999"
              :precision="2"
              style="width: 90%;margin-right: 5px;"
              placeholder="请输入经销批发价(1~999999)"
              ref="specialPrice"
              @keydown.enter.native="nextFocus('specialPrice', 'cost', $event)"
              allowClear /><span>元</span>
          </a-form-model-item>
         <!-- <a-form-model-item label="成本价" v-if="pageType=='pages'" prop="cost">
            <a-input-number
              id="productInfoEdit-cost"
              v-model="form.cost"
              :min="0"
              :max="999999"
              :precision="2"
              style="width: 90%;margin-right: 5px;"
              placeholder="请输入成本价(1~999999)"
              ref="cost"
              @keydown.enter.native="nextFocus('cost', 'terminalPrice', $event)"
              allowClear /><span>元</span>
          </a-form-model-item> -->
          <a-form-model-item label="终端价" prop="terminalPrice">
            <a-input-number
              id="productInfoEdit-terminalPrice"
              v-model="form.terminalPrice"
              :min="0"
              :max="999999"
              :precision="2"
              style="width: 90%;margin-right: 5px;"
              placeholder="请输入终端价(1~999999)"
              ref="terminalPrice"
              @keydown.enter.native="nextFocus('terminalPrice', 'carOwnersPrice', $event)"
              allowClear /><span>元</span>
          </a-form-model-item>
          <a-form-model-item label="车主价" prop="carOwnersPrice">
            <a-input-number
              id="productInfoEdit-carOwnersPrice"
              v-model="form.carOwnersPrice"
              :min="0"
              :max="999999"
              :precision="2"
              style="width: 90%;margin-right: 5px;"
              placeholder="请输入车主价(1~999999)"
              ref="carOwnersPrice"
              @keydown.enter.native="nextFocus('carOwnersPrice', '', $event)"
              allowClear /><span>元</span>
          </a-form-model-item>
          <a-form-model-item label="成本价" v-if="pageType=='modal'" prop="putCost">
            <a-input-number
              id="productInfoEdit-putCost"
              v-model="form.putCost"
              :min="0"
              :max="999999"
              :precision="2"
              style="width: 90%;margin-right: 5px;"
              placeholder="请输入成本价(1~999999)"
              ref="putCost"
              @keydown.enter.native="nextFocus('putCost', 'putQty', $event)"
              allowClear /><span>元</span>
          </a-form-model-item>
          <a-form-model-item label="入库数量" v-if="pageType=='modal'" prop="putQty">
            <a-input-number
              id="productInfoEdit-specialPrice"
              v-model="form.putQty"
              :precision="0"
              :min="1"
              :max="999999"
              style="width: 90%;"
              placeholder="请输入数量(1~999999)"
              ref="putQty"
              allowClear />
          </a-form-model-item>
          <a-form-model-item label="仓库仓位" v-if="pageType=='modal'" prop="warehouse">
            <Warehouse id="productInfoEdit-warehouse" ref="warehouse" @change="warehouseChange" v-model="form.warehouse"></Warehouse>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }" style="text-align: center;">
            <a-button
              type="primary"
              :loading="saveing"
              @click="handleSubmit"
              size="large"
              id="productInfoEdit-btn-submit"
              style="padding: 0 50px;">保 存</a-button>
            <a-button
              type="default"
              :loading="saveing"
              @click="handleBack"
              size="large"
              id="productInfoEdit-btn-cansel"
              style="padding: 0 50px;margin-left: 30px;">取消</a-button>
          </a-form-model-item>
        </a-form-model>
        <!-- 新增/编辑产品品牌 -->
        <product-brand-edit-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import productBrandEditModal from '../productBrand/editModal.vue'
import Warehouse from '@/views/common/warehouse.js'
import { dealerProductBrandQuery } from '@/api/dealerProductBrand'
import { dealerProductTypeList } from '@/api/dealerProductType'
import { dealerProductSave, dealerProductDetail } from '@/api/dealerProduct'
export default {
  name: 'ProductInfoEdit',
  components: { STable, VSelect, productBrandEditModal, Warehouse },
  mixins: [commonMixin],
  props: {
    pageType: { // 页面表现形式，pages 新页签打开的页面，modal 弹框里的页面
      type: String,
      default: 'pages'
    },
    paramsData: {
      type: Object,
      default: function () {
        return null
      }
    },
    saveing: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isEdit () {
      return this.pageType == 'pages' ? !!this.$route.params.id : false
    }
  },
  watch: {
    paramsData (newValue, oldValue) {
      this.formData = newValue
    }
  },
  data () {
    return {
      spinning: false,
      loadingPtype: false,
      formItemLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 }
      },
      formData: this.paramsData,
      form: {
        name: '', // 产品名称
        code: '', //  产品编码
        origCode: '', //  原厂编码
        unit: '', //  基本单位
        productBrandSn: undefined, //  产品品牌
        productTypeSn3: '', //  产品三级分类
        productType: [], //  产品分类
        specialPrice: '', //  经销价
        terminalPrice: '', //  终端价
        carOwnersPrice: '', //  车主价
        putCost: '',
        putQty: '',
        warehouse: []
      },
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入产品编码', trigger: 'blur' }
        ],
        productBrandSn: [
          { required: true, message: '请选择产品品牌', trigger: 'change' }
        ],
        productType: [
          { required: true, message: '请选择产品分类', trigger: 'change' }
        ],
        putCost: [
          { required: true, type: 'number', message: '请输入成本价', trigger: 'change' }
        ],
        putQty: [
          { required: true, type: 'number', message: '请输入数量', trigger: 'change' }
        ],
        warehouse: [
          { required: true, message: '请选择仓库仓位', trigger: 'blur' }
        ]
      },
      fetching: false,
      productBrandList: [], //  品牌下拉数据
      productTypeList: [], //  分类下拉数据
      openModal: false //  新增编辑  弹框
    }
  },
  methods: {
    warehouseChange () {
      this.$refs.ruleForm.clearValidate('warehouse')
    },
    // 搜索品牌
    searchBrand (value, defval) {
      console.log('fetching user', value)
      this.fetching = true
      dealerProductBrandQuery({ 'queryWord': value }).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data || []
          this.fetching = false
          // 默认值
          if (defval) {
            const row = this.productBrandList.find(item => item.brandName == defval)
            this.form.productBrandSn = row.brandSn
            this.$refs.ruleForm.clearValidate('productBrandSn')
          }
        } else {
          this.productBrandList = []
          this.fetching = false
        }
      })
    },
    filterOption (input, option) {
      console.log(input, option.data.attrs.pinyin)
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
        option.data.attrs.pinyin && option.data.attrs.pinyin.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 选择单位
    unitChange (a, b) {
      this.form.unit = b.dispName
    },
    //  获取产品信息
    getGoodsDetail () {
      dealerProductDetail({ id: this.$route.params.id }).then(res => {
        if (res.status == 200) {
          this.form = Object.assign(this.form, res.data)
          const productTypeSn1 = res.data.productTypeSn1 ? res.data.productTypeSn1 : ''
          const productTypeSn2 = res.data.productTypeSn2 ? res.data.productTypeSn2 : ''
          const productTypeSn3 = res.data.productTypeSn3 ? res.data.productTypeSn3 : ''
          this.form.productType = [productTypeSn1, productTypeSn2, productTypeSn3]
          if (res.data.productBrandName) {
            this.searchBrand(res.data.productBrandName)
          }
        } else {
          this.$refs.ruleForm.resetFields()
        }
      })
    },
    //  保存
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          if (!form.productTypeSn3) {
            this.$message.warning('产品分类未选到第三级，请修改后再提交！')
            return false
          }
          // 编辑
          if (this.isEdit) {
            form.id = _this.$route.params.id ? _this.$route.params.id : undefined
          }
          delete form.productType
          _this.spinning = true
          dealerProductSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              if (_this.pageType == 'pages') {
                _this.$router.push({ path: '/productManagement/productInfo/list' })
              } else {
                _this.$emit('saveOk', _this.form)
              }
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 回车键快捷定位表单下一项
    nextFocus (nowRef, nextRef, event, isComponent) {
      const _this = this
      if (_this.$refs[nowRef]) {
        _this.$nextTick(() => {
          if (_this.$refs[nextRef]) {
            event.target.blur()
            if (isComponent == 'vSelect') {
              _this.$refs[nextRef].$children[0].focus()
            } else {
              _this.$refs[nextRef].focus()
            }
          }
        })
      }
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.form.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  新增品牌  成功
    handleOk (val) {
      if (val) { //  需将新增加的品牌回填到产品品牌的地方，即不需要用户再选一下
        this.searchBrand('', val)
      }
    },
    //  返回
    handleBack () {
      if (this.pageType == 'pages') {
        this.$router.push({ path: '/productManagement/productInfo/list' })
      } else {
        this.$emit('cansel')
      }
    },
    //  产品分类  列表
    getProductType () {
      this.loadingPtype = true
      dealerProductTypeList({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
        this.loadingPtype = false
      })
    },
    pageInit () {
      this.$refs.ruleForm.resetFields()
      this.getProductType()
      this.searchBrand('')

      //  编辑页
      if (this.$route.params.id && this.pageType == 'pages') {
        this.getGoodsDetail()
      }

      this.$nextTick(() => {
        // 默认首项获取焦点
        this.$refs['name'].focus()
        // 如果是其它页面新建产品
        if (this.pageType == 'modal') {
          console.log(this.paramsData)
          this.form = Object.assign(this.form, this.paramsData)
          this.$refs.warehouse.setDefaultVal()
        }
      })
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .productInfoEdit-wrap{
    height: 100%;
    >.ant-spin-nested-loading{
      height: 100%;
	  overflow-y: auto;
      .ant-spin-container{
        height: 90%;
      }
    }
    .productInfoEdit-table-page-wrapper{
      height: 100%;
    }
    .productInfoEdit-back{
      margin-bottom: 10px;
    }
  }
</style>
