<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <div class="tab-header webtop">
        <div>{{ viewTitle }}</div>
        <div>
          <el-button type="primary" size="small" :disabled="submitdisabled" @click="handleSave()">保存</el-button>
          <el-button type="info" size="small" @click="handleReturn()">关闭</el-button>
        </div>
      </div>
      <div class="listconadd">
        <el-form ref="form_obj" :model="formobj" :rules="rules" class="formaddcopy02">
          <el-row style="border-top: 1px solid #e0e3eb">
            <el-col :span="12">
              <div class="span-sty"><span class="icon">*</span>产品名称</div>
              <el-form-item prop="goodsSid">
                <el-select class="addinputInfo" v-model="formobj.goodsSid" placeholder="请选择" @change="productChange" filterable>
                  <el-option v-for="item in product_list" :key="item.sid" :label="item.goodsName" :value="item.sid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="span-sty">比例类型</div>
              <el-form-item>
                <el-radio-group class="addinputInfo" v-model="formobj.rateType">
                  <el-radio label="0">产出率</el-radio>
                  <el-radio label="1">配比</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="title titleOne">
            <div>原料列表</div>
            <div>
              <el-button style="margin-left: 10px" type="primary" class="btntopblueline" size="small" @click="productAdd">添加</el-button>
            </div>
          </div>
          <el-table :key="tableKey" :data="formobj.list" :index="index" border style="width: 100%">
            <el-table-column fixed width="60" label="序号" type="index" :index="index + 1" align="center" />
            <el-table-column label="操作" align="center" width="80">
              <template slot-scope="scope">
                <el-button type="danger" size="small" @click="productDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="materialName" label="原料名称" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.materialSid" placeholder="请选择" @change="materialChange(scope.row, $event)" filterable>
                  <el-option v-for="item in product_list" :disabled="item.goodsCode == formobj.productCode" :key="item.sid" :label="item.goodsName" :value="item.sid"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="materialCode" label="原料编码" align="center" />
            <el-table-column v-if="formobj.rateType == '0'" label="产出率(%)" align="center">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.rate = getNumber(scope.row.rate, 2)" v-model="scope.row.rate" clearable placeholder="" />
              </template>
            </el-table-column>
            <el-table-column v-if="formobj.rateType == '1'" label="配比(%)" align="center">
              <template slot-scope="scope">
                <el-input @keyup.native="scope.row.rate = getNumber(scope.row.rate, 2)" v-model="scope.row.rate" clearable placeholder="" />
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import req from '@/api/goods/product/product'
import { getGoodsForProduct } from '@/api/Common/dictcommons'

export default {
  name: 'ProductAdd',
  data() {
    return {
      viewTitle: '',
      viewState: 1,
      submitdisabled: false,
      tableKey: 1,
      index: 0,
      product_list: [],
      formobj: {
        sid: '',
        createBySid: '',
        createOrgSid: '',
        useOrgSid: '',
        goodsSid: '',
        productName: '',
        productCode: '',
        rateType: '',
        list: []
      },
      rules: {
        goodsSid: [{ required: true, message: '产品名称不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    init() {
      getGoodsForProduct({ queryName: '', useOrgSid: window.sessionStorage.getItem('defaultDeptSid') }).then((res) => {
        if (res.success) {
          this.product_list = res.data
        }
      })
    },
    getNumber(val, limit) {
      val = val.replace(/[^0-9.]/g, '') // 保留数字
      val = val.replace(/^00/, '0.') // 开头不能有两个0
      val = val.replace(/^\./g, '0.') // 开头为小数点转换为0.
      val = val.replace(/\.{2,}/g, '.') // 两个以上的小数点转换成一个
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.'); // 只保留一个小数点
      /^0\d+/.test(val) ? val = val.slice(1) : '' // 两位以上数字开头不能为0
      const str = '^(\\d+)\\.(\\d{' + limit + '}).*$'
      const reg = new RegExp(str)
      if (limit === 0) {
        // 不需要小数点
        val = val.replace(reg, '$1')
      } else {
        // 通过正则保留小数点后指定的位数
        val = val.replace(reg, '$1.$2')
      }
      return val
    },
    showAdd() {
      this.viewTitle = '【新增】产品'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      this.formobj.createBySid = window.sessionStorage.getItem('userSid')
      this.formobj.createOrgSid = window.sessionStorage.getItem('orgSid')
      this.formobj.useOrgSid = window.sessionStorage.getItem('defaultDeptSid')
      this.formobj.rateType = '0'
    },
    showEdit(sid) {
      this.viewTitle = '【编辑】产品'
      this.$nextTick(() => {
        this.$refs['form_obj'].clearValidate()
      })
      this.init()
      req.fetchBySid({ sid: sid }).then((res) => {
        if (res.success) {
          this.formobj = res.data
        }
      })
    },
    productChange(value) {
      const choose = this.product_list.filter((item) => item.sid === value)
      if (choose !== null && choose.length > 0) {
        this.formobj.productName = choose[0].goodsName
        this.formobj.productCode = choose[0].goodsCode
      } else {
        this.formobj.productName = ''
        this.formobj.productCode = ''
      }
    },
    productAdd() {
      if (this.formobj.productName === '') {
        this.$message({ showClose: true, type: 'error', message: '请先选择产品名称' })
        return
      }
      this.formobj.list.push({
        sid: '',
        materialSid: '',
        materialName: '',
        materialCode: '',
        rate: ''
      })
    },
    materialChange(row, value) {
      const choose = this.product_list.filter((item) => item.sid === value)
      if (choose !== null && choose.length > 0) {
        row.materialName = choose[0].goodsName
        row.materialCode = choose[0].goodsCode
      } else {
        row.materialName = ''
        row.materialCode = ''
      }
    },
    productDelete(index) {
      this.formobj.list.splice(index, 1)
    },
    handleSave() {
      this.$refs['form_obj'].validate((valid) => {
        if (valid) {
          if (this.formobj.list.length === 0) {
            this.$message({ showClose: true, type: 'error', message: '原料列表不能为空' })
            return
          } else {
            if (this.formobj.list.length > 1) {
              for (var i = 0; i < this.formobj.list.length; i++) {
                if (this.formobj.list[i].materialCode === this.formobj.list[this.formobj.list.length - 1].materialCode) {
                  this.$message({ showClose: true, type: 'error', message: '原料列表中需选择不同的原料进行操作' })
                  return
                }
              }
            }
          }
          this.submitdisabled = true
          req.saveOrUpdate(this.formobj).then((res) => {
            if (res.success) {
              this.$message({ showClose: true, type: 'success', message: '保存成功' })
              this.handleReturn('true')
            } else {
              this.submitdisabled = false
            }
          }).catch(() => {
            this.submitdisabled = false
          })
        }
      })
    },
    handleReturn(isreload) {
      if (isreload === 'true') this.$emit('reloadlist')
      this.formobj = {
        sid: '',
        createBySid: '',
        createOrgSid: '',
        useOrgSid: '',
        goodsSid: '',
        productName: '',
        productCode: '',
        rateType: '',
        list: []
      }
      this.$emit('doback')
    }
  }
}
</script>

<style scoped>
.span-sty {
  width: 130px !important;
}
.addinputInfo {
  margin-left: 120px !important;
}
.titleOne {
  padding: 7px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
/deep/ .el-form-item__error {
  margin-left: 120px !important;
}
.formaddcopy02 .el-row .el-col /deep/ .el-form-item .el-radio-group {
  display: inline;
  line-height: 1px;
  vertical-align: middle;
}
</style>
