<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.toolName")+"："' prop="name">
        <el-input v-model="tenant.name" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>
    	<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.type")+"："' prop="type">
        <template>
				  <el-radio v-model="tenant.type" label="1">{{$t("lineSide.common.tool")}}</el-radio>
				  <el-radio v-model="tenant.type" label="0">{{$t("lineSide.common.local")}}</el-radio>
				</template>
      </el-form-item>-->
      <el-form-item :label='$t("lineSide.form.toolType")+"："' prop="toolType">
        <template>
          <el-radio v-model="tenant.toolType"  label="0">{{$t("lineSide.common.central")}}</el-radio>
          <el-radio v-model="tenant.toolType"  label="1">{{$t("lineSide.common.lathe")}}</el-radio>
          <el-radio v-model="tenant.toolType"  label="2">机器人随行货架</el-radio>
          <el-radio v-model="tenant.toolType"  label="3">机床刀具缓存库</el-radio>
          <el-radio v-model="tenant.toolType"  label="4">接驳位</el-radio>
          <el-radio v-model="tenant.toolType"  label="5">随行工装</el-radio>
        </template>
      </el-form-item>
      <el-form-item :label='$t("lineSide.form.pic")+"："' prop="pic">
          <el-input v-model="tenant.pic" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>
      <el-form-item :label='$t("lineSide.form.address")+"："' prop="address">
        <el-input v-model="tenant.address" :placeholder='$t("common.pleaseEnter")'/>
      </el-form-item>

<!--      <el-form-item :label='$t("lineSide.form.parentTool")' prop="parentId">
        &lt;!&ndash; 调用树形下拉框组件 &ndash;&gt;
		    <tree-select
		    	key='100'
		      :props="props"
		      :options="list"
		      :value="tenant.parentId"
		      :clearable="isClearable"
		      :accordion="isAccordion"
		      @getValue="getValue($event)"
		      style="width: 100%;"
		    />
      </el-form-item>-->
      <el-form-item :label='$t("lineSide.form.deviceId")' prop="deviceId"  >
          <el-select v-model="tenant.deviceId"   style="width: 50%">
            <el-option v-for="(item, index) in deviceList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
<!--      <el-form-item :label='$t("lineSide.form.weight")+"："' prop="weight">
      	<el-input-number v-model="tenant.weight" :min="0" :max="9999999999"></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.show")}}</el-radio>
				  <el-radio v-model="tenant.status" label="0">{{$t("common.hide")}}</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 toolManagementApi from "@/api/modelingCenter/toolManagement";
import TreeSelect from "@/components/TreeSelect/TreeSelect";

export default {
  name: 'TenantEdit',
  components: {
    TreeSelect
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data () {
    let validateExsit = (rule, value, callback) => {
      //后台方法
      if(this.type=="edit" && value === this.oldName){
        return callback()
      }
      this.checkExist(value).then(res => {
        res = res.data
        if (res && res.data) {
          callback(new Error('名称已存在'))
        }else{
          callback()
        }
      })
    }
    return {
    	isClearable: true, // 可清空（可选）
      isAccordion: true, // 可收起（可选）
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
        children: "children"
        // disabled:true
      },
      // 选项列表（必选）
      list: [],
      deviceList: [],
      type: 'add',
      oldName: '',
      tenant: this.initTenant(),
      screenWidth: 0,
      width: this.initWidth(),
      confirmDisabled: false,
      showToolType: false,
      dicts:{
        NATION: {}
      },
      roles: [],
      rules: {
        name: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'blur' },
          { validator: validateExsit, trigger: 'blur'}
        ],
        no: [
        	{ required: true, message: this.$t("lineSide.rules.no"), trigger: 'blur' }
        ],
        type: [
        	{ required: true, message: this.$t("rules.require"), trigger: 'blur' }
        ],
        toolType: [
          { required: true, message: this.$t("rules.require"), trigger: 'blur' }
        ],
      }
    }
  },
  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
	  created() {
		},
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible
      },
      set () {
        this.close()
        this.reset()
      }
    }
  },
  mounted () {
    window.onresize = () => {
      return (() => {
        this.width = this.initWidth()
      })()
    }
  },
  methods: {
  	// 取值
    getValue(value) {
      this.tenant.parentId = value;
      console.log(this.tenant.parentId);
    },
    getDeviceValue(value) {
      this.tenant.deviceId = value;
      console.log("tenant.deviceId：", this.tenant.deviceId);
    },
    initTenant () {
      return {
        id: '',
        name: '',
        parentId: '',
        deviceId: '',
        weight: null,
        status: '1',
        pic: null,
        address: null
      }
    },
    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) {
    	if(val){
    		this.tenant = { ...val }
        this.oldName = val.name
    		console.log("row数据：", val)
    	}else{
    		// 新增没有数据
    		this.tenant.parentId = '0'
    	}
      // 字典表
      this.dicts = dicts
      // 加载列表数据
	  	this.getTreeList()
      this.getProductionresourceList()
    },
    close () {
      this.$emit('close')
    },
    checkExist(name){
      return toolManagementApi.checkField({"name":name})
    },
    reset () {
      // 先清除校验，再清除表单，不然有奇怪的bug
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.tenant = this.initTenant()
      // 清楚数据
      this.tenant.parentId = ''
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmDisabled = true
          if (this.type === 'add') {
            this.save()
          } else {
            this.update()
          }
        } else {
          return false
        }
      })
    },
    save () {
      toolManagementApi.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 () {
      toolManagementApi.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
        })
    },
    // 获取【上级货架】下拉数据
		getTreeList(){
			toolManagementApi.getTreeList({}).then(res => {
				res = res.data
				if(res.isSuccess){
					console.log("获取【上级货架】下拉数据: ", res)
					this.list = res.data
				}
			})
		},
    /*updateShowToolType() {
      // 根据选择的 type 控制是否显示 toolType 输入框
      this.showToolType = this.tenant.toolType === '1'; // 或者根据其他条件设置 showToolType 的值
    },*/
    // 获取【上级货架】下拉数据
    getProductionresourceList(){
      toolManagementApi.getAllList({}).then(res => {
        res = res.data
        if(res.isSuccess){
          console.log("获取【设备】下拉数据: ", res)
          this.deviceList = res.data
          if (this.deviceList.length == 1) {
            this.deviceId = this.deviceList[0].id;
          }
        }
      })
    }
  }
}
</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>
