<template>
  <el-dialog 
  	:close-on-click-modal="false" 
  	:close-on-press-escape="false" 
  	:title="title" 
  	:append-to-body="true"
  	:visible.sync="isVisible" 
  	:width="width" 
  	top="50px"
  >
    <el-form ref="form" :model="tenant" :rules="rules" label-position="right" label-width="130px">
      <el-form-item :label='$t("lineSide.form.no")+ "："' prop="no">
          <el-input v-model="tenant.no" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>
      <el-form-item :label='$t("lineSide.form.name")+ "："' prop="name">
          <el-input v-model="tenant.name" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>
       <el-form-item :label='$t("lineSide.form.parentFloor")+ "："' prop="shelvesId">
          <el-input :disabled="true" v-model="currNodeName" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>
      <el-form-item :label='$t("lineSide.form.wareType")+ "："' prop="storgeTypeId">
          <el-select v-model="tenant.storgeTypeId" :placeholder='$t("common.pleaseSelect")' style="width: 100%;">
		        	<el-option v-for="item in wareTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
		      	</el-select>
      </el-form-item>
      <el-form-item :label='$t("common.weight")+"："' prop="weight">
          <el-input-number v-model="tenant.weight" :min="0" :max="99999999999" label=""></el-input-number>
      </el-form-item>
      <el-form-item :label='$t("lineSide.form.status")+"："' prop="status">
        <template>
				  <el-radio v-model="tenant.status" label="1">{{$t("common.status.valid")}}</el-radio>
				  <el-radio v-model="tenant.status" label="0">{{$t("common.status.stop")}}</el-radio>
				</template>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="isVisible = false">{{ $t('common.cancel') }}</el-button>
      <el-button plain type="primary" :disabled="confirmDisabled" @click="submitForm">{{ $t('common.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 【仓库类型管理】-API
import warehouseTypeMgrApi from "@/api/modelingCenter/warehouseTypeMgr"
// 【库位管理】-API
import locationMgrApi from "@/api/lineSideLibrary/locationMgr"
export default {
  name: 'TenantEdit',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data () {
    let validateExsit = (rule, value, callback) => {
      //后台方法
      this.checkExist(value).then(res => {
        res = res.data;       
        // console.log("check验证：", res);
        if (res && res.data) { 
          callback(new Error('名称已存在'))
        }else{
          callback()
        }
      })
    }
    return {
      type: 'add',
      currNodeName: '',
      tenant: this.initTenant(),
      screenWidth: 0,
      width: this.initWidth(),
      confirmDisabled: false,
      wareTypeList: [], // 库位类型下拉数据
      dicts:{
        NATION: {}
      },
      roles: [],
      rules: {
      	no: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'blur' }
        ],
        name: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'blur' },
          { validator: validateExsit, trigger: 'blur'}
        ],
        storgeTypeId: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'change' }
        ],
        weight: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'change' }
        ],
        status: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'change' }
        ]
      }
    }
  },
  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
  created() {
  	// 获取【库位类型】数据
  	this.getWareTypeList()
	},
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible
      },
      set () {
        this.close()
        this.reset()
      }
    }
  },
  mounted () {
    window.onresize = () => {
      return (() => {
        this.width = this.initWidth()
      })()
    }
  },
  methods: {
    initTenant () {
      return {
        id: '',
        no: '',
        name: '',
        shelvesId: '',
        storgeTypeId: '',
        status: '1'
      }
    },
    initWidth () {
      this.screenWidth = document.body.clientWidth
      if (this.screenWidth < 991) {
        return '90%'
      } else if (this.screenWidth < 1400) {
        return '45%'
      } else {
        return '800px'
      }
    },
    setTenant (val, dicts, currNode) {
    	console.log("货架数据：", currNode)
    	if(val){
    		this.tenant = { ...val }
    	}else{  // 如果是新增
    		// 给【上级层】显示使用
	    	this.currNodeName = currNode.name
	    	// 给【上级层】赋值id
	    	this.tenant.shelvesId = currNode.id
    	}
      // 字典表
      this.dicts = dicts
    },
    close () {
      this.$emit('close')
    },
    checkExist(name){
      return locationMgrApi.checkField({"name":name})
    },
    reset () {
      // 先清除校验，再清除表单，不然有奇怪的bug
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.tenant = this.initTenant()
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmDisabled = true
          if (this.type === 'add') {
            this.save()
          } else {
            this.update()
          }
        } else {
          return false
        }
      })
    },
    save () {
      locationMgrApi.save(this.tenant)
        .then((response) => {
          const res = response.data
          if (res.isSuccess) {
            this.isVisible = false
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            // 通知列表
	          this.$emit("success");
	          // 通知列表-并关闭弹出框
	          this.$emit("close");
          }
        }).finally(() => {
          this.confirmDisabled = false
          return true
        })
    },
    update () {
      locationMgrApi.update(this.tenant)
        .then((response) => {
          const res = response.data
          if (res.isSuccess) {
            this.isVisible = false
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            // 通知列表
	          this.$emit("success");
	          // 通知列表-并关闭弹出框
	          this.$emit("close");
          }
        }).finally(() => {
          this.confirmDisabled = false
          return true
        })
    },
    // 【库位类型】数据
		getWareTypeList(){
			warehouseTypeMgrApi.getList({}).then(res => {
				res = res.data 
				if(res.isSuccess){
					this.wareTypeList = res.data
				}
			})
		}
  }
}
</script>
<style lang="scss" >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.checkUsed{
	display: inline-block;
	margin-left: 10px;
	color: #1890ff;
}
</style>
