<!-- 添加/编辑 -->
<template>
  <el-dialog :title="title" :visible.sync="isShow" :append-to-body="true" :close-on-click-modal="false" class="drawer-box" width="800px" @close="handleCancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top">
      <el-row>
        <el-col :span="8">
          <el-form-item label="图片:" required>
            <div class="upload-box" style="margin-right: 16px; border-right: 1px solid #ccc;">
              <imageUpload v-model="form.logo" :value="form.logo" :limit="1" @change="handleFileList" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="materielName">
                <el-input v-model="form.materielName" placeholder="请输入物料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类别" prop="materielType">
                <el-select v-model="form.materielType" class="wd100" placeholder="请选择">
                  <el-option v-for="it of materialTypeList" :key="it.id" :value="it.value" :label="it.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料编码" prop="materielCode">
                <el-input :controls="false" class="wd100" v-model="form.materielCode" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单台用量" prop="dosage">
                <el-input-number :controls="false" class="wd100" v-model="form.dosage" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="产品属性" class="pro-item-box">
                <div class="pro-box">
                  <div class="item-box" v-for="(item,index) in form.extendList" :key="index">
                    <div class="box-lf">
                      <el-input v-model="item.key" placeholder="属性名" />
                    </div>
                    <div class="box-rt">
                      <el-input v-model="item.name" placeholder="属性值" />
                    </div>
                    <!-- <div class=""></div> -->
                    <i class="el-icon-delete" v-if="form.extendList.length!==1" @click="handleDel(index)" style="margin-left:10px"></i>
                  </div>
                </div>
                <div class="add-box">
                  <el-button type="primary" @click="handleAdd" size="mini" plain>新增</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="btnLoading" @click="handleCancel" size="small">取消</el-button>
      <el-button type="primary" :loading="btnLoading" size="small" @click="handleSave">{{!id?'添加':'编辑'}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createMateriel, updateMateriel, getMateriel } from "@/api/bs/materiel";
import VerifyFunc from '@/utils/verity'
import dayjs from 'dayjs';
import ImageUpload from '@/components/ImageUpload';
export default {
  name: '',
  props: {
    materialTypeList: Array,
    id: [String, Number],
    isOpen: Boolean,
  },
  components: {
    CommonName: () => import('@/components/CommonName'),
    ImageUpload,
  },
  watch: {
    isOpen: {
      handler(val) {
        this.isShow = val
        this.title = this.id ? '编辑物料' : '添加物料'
        if (val) {
          this.handleInitForm()
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      btnLoading: false,
      isShow: false,
      rules: {
        logo: [{ required: true, message: "请选择", trigger: "change" }],
        materielName: [{ required: true, message: "请输入", trigger: "blur" }],
        materielCode: [{ required: true, message: "请输入", trigger: "blur" }],
        materielType: [{ required: true, message: "请选择", trigger: "change" }],
        dosage: [{ required: true, message: "请选择", trigger: "blur" }, { validator: VerifyFunc.newNumber }]
      },
      form: {
        materielName: null,
        materielType: null,
        dosage: undefined,
        materielCode: null,
        extendList: [{ key: '', name: '' }],
      },
      materialType: [],
      nameArr: [],
      fileList: [],
      isDisabled: true,
    }
  },

  methods: {
    handleFileList(fileList) {
      this.fileList = fileList
      this.$set(this.form, 'logo', this.form.logo)
    },
    handleDel(index) {
      this.form.extendList.splice(index, 1)
    },
    handleAdd() {
      this.form.extendList.push({ key: '', name: '' })
    },
    handlePictureCardPreview() {

    },
    handlePayCancel() {
      this.payShow = false
    },
    handleBeginScan() {
      if (!(this.fileList && this.fileList.length)) {
        return this.$fm('请上传物料图片！')
      }
    },
    // id 不存在 新增 否则编辑
    handleInitForm(id = this.id) {
      // 初始化参数
      if (!id) {
        this.form = {
          logo: null,
          materielName: null,
          materielType: undefined,
          extendList: [{ key: '', name: '' }],
          dosage: undefined,
          materielCode: null
        }
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.resetFields()
          this.$refs.form && this.$refs.form.clearValidate()
        })
      } else {
        getMateriel(id).then(res => {
          this.form = {
            ...(res.data || {}),
            logo: res.data.files && res.data.files[0].url,
            extendList: res.data.extendList && res.data.extendList.length ? res.data.extendList : [{ key: '', name: '' }]
          }
          this.fileList = this.form.files
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
        })
      }
    },
    handleClose() {
      this.$emit('onClose')
    },
    handleSave() {
      this.$nextTick(() => {
        this.$refs.form.validate((bool) => {
          if (bool) {
            if (!(this.fileList && this.fileList.length)) {
              this.$modal.msgWarning(`请上传图片！`);
              return
            }
            let form = {
              ...this.form,
              files: this.fileList,
              extendList: this.form.extendList.length && this.form.extendList[0].key ? this.form.extendList : []
            }
            if (this.id) {
              this.btnLoading = true
              updateMateriel(form).then((res) => {
                this.btnLoading = false
                this.$modal.msgSuccess(`编辑成功啦！`);
                this.$emit('onConfirm')
              }).catch(() => {
                this.btnLoading = false
              })
            } else {
              this.btnLoading = true
              createMateriel(form).then((res) => {
                this.btnLoading = false
                this.$emit('onConfirm')
                this.$modal.msgSuccess(`新增成功啦！`);
              }).catch(() => {
                this.btnLoading = false
              })
            }

          } else {
            this.$nextTick(() => {
              this.$scErr()
            })
          }
        })
      })
    },
    handleCancel() {
      this.$emit('onCancel')
    },
    handleRemove(file, files) {
      this.fileList = []
      this.form.logoUrl = null
    },
    onUploadChange(file, files) {
      console.log('files..', file.raw);
      if (['image/png', 'image/jpeg', 'image/jpeg'].includes(file.raw.type)) {
        if (file.size / 1024 > 5000) {
          setTimeout(() => {
            this.$fm('文件超过5Mb，请压缩后上传!')
          }, 10)
          files.splice(files.length - 1, 1)
          return
        }
        this.fileList = []
        this.fileList.push(file)
      } else {
        this.$fm('不支持此文件类型，请重试！')
      }
    },
  }
}

</script>
<style lang='scss' scoped>
@import '@/assets/styles/edit/index.scss';
// ::v-deep .el-form-item__error {
//   padding-top: 4px !important;
// }
.pro-box {
  display: flex;
  width: 100%;
  justify-content: flex-start;
  flex-wrap: wrap;
  max-height: 150px;
  overflow-y: auto;
  .item-box {
    display: flex;
    max-width: 40%;
    align-items: center;
    ::v-deep .el-input__inner {
      border: none !important;
    }
    .box-lf {
      ::v-deep .el-input__inner {
        border-right: 1px solid #dcdfe6 !important;
        border-radius: 0 !important;
      }
    }
    // justify-content: ;
  }
  .add-box {
    margin-left: 10px;
  }
}
.pro-item-box {
  position: relative;
  .add-box {
    position: absolute;
    top: 0;
    right: 20px;
  }
}
</style>