<template>
  <div class="formContaner" style="height:200px;">
	    <el-form ref="form" :model="rowData" :rules="rules" label-position="right" label-width="150px">
		  <el-form-item :label='$t("runCenter.form.areaName")+"："' v-model="rowData.name" >{{rowData.name}}</el-form-item>
	      <el-form-item :label='$t("runCenter.form.setModel")+"："' >
	      	<el-select style="width:300px;" :placeholder='$t("common.pleaseSelect")' v-model="rowData.runMode"  @change="changeMode" >
	          <el-option :key="value" :label="key" :value="value" v-for="(key, value) in this.dicts.RUN_MODE" />
	        </el-select>
	      </el-form-item>
	    </el-form>

	    <div slot="footer" class="dialog-footer">
	      <el-button type="primary" icon="el-icon-check" :disabled="confirmDisabled" @click="submitForm">{{ $t('runCenter.buttons.ok') }}</el-button>
	    </div>
    </div>
</template>

<script>

	// 【区域管理】-API
	import areaMgrApi from "@/api/resourceProductMgr/areaMgr"
	import orderMgrApi from "@/api/runManageCenter/orderMgr"
	// 共通的【查询方法】
	import { initDicts, initQueryParams } from '@/utils/commons'
	// 共通【工具方法】（字典分解）
	import { convertEnum } from '@/utils/utils'
	export default {
	  name: "SetCurrentLine",
	  components: {},
	  props: {
	    rowData: Object
	  },
	  data () {
	    return {
	    dicts: {
          RUN_MODE: {}  //运行模式
        },
	      confirmDisabled: false,
		  bool: true,
		  orderCount: 0,
	      tenant: this.initTenant(),
	      rules: {
	        runMode: [
	        	{ required: true, message: this.$t("rules.require"), trigger: 'change' }
	        ]
	      }
	    }
	  },
	  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
	  created() {
	  	// 加载【字典】
	  	initDicts(['RUN_MODE'], this.dicts)
		//console.log(this.tenant)
		this.tenant = this.rowData
        this.checkCount()
		},
	  computed: {
	    currentUser () {
	      return this.$store.state.account.user
	    },
	    runModelList() {
          return convertEnum(this.dicts.RUN_MODE)
      	}
	  },
	  mounted () {
	  },
	  methods: {
	  	initTenant () {
	      return {
		    id: '',
	      	runMode: '',
	      }
	    },
	    reset () {
	      // 先清除校验，再清除表单，不然有奇怪的bug
	      this.$refs.form.clearValidate()
	      this.$refs.form.resetFields()
	      this.tenant = this.initTenant()
	    },
		changeMode(val) {
		    this.bool = true
			let runMode = this.rowData.runMode

			if ( runMode === "1" || runMode === "3"){
			    //弹框确认
				this.$confirm('确认要切换产线模式吗？', this.$t("common.tips"), {
					confirmButtonText: this.$t("common.confirm"),
					cancelButtonText: this.$t("common.cancel"),
					type: "warning"
				}).then(() => {

				}).catch(() => {
					this.$emit("close")
				});

			}
			else {
			   this.$message({
                message: "请确保手动操作在系统已登记",
                type: "success"
              });
			}

			if (runMode !== "" && runMode !== "2" && val === "2"){
				return new Promise((resolve,reject)=>{
				    orderMgrApi.getOrderStatusCount({}).then(res => {
							resolve(res)
                            //console.log(res)
							if(res.data.isSuccess){
								this.orderCount = parseInt(res.data.data.orderConductCount)
								if(this.orderCount > 0){
									this.$message({
											message: "系统有在生产的订单，请先完成订单",
											type: "error"
									})
									this.bool = false
                                    this.$emit("close")
								}
							}
					})
				})
			}

			if(this.bool){
				this.tenant.runMode = val
			}

		},
	    submitForm () {
	      this.$refs.form.validate((valid) => {
	        if (valid && this.bool) {
				  	// 获取父组件传值ID
				 	 	this.tenant.id = this.rowData.id
		        this.confirmDisabled = true
				  	console.log(this.tenant)
		        //productionLineMgrApi.update(this.tenant).then(res => {
				  	areaMgrApi.changeMode(this.tenant).then(res => {
	          	res = res.data
	          	console.log("恢复按钮 == ", res);
	          	// 恢复按钮
		          this.confirmDisabled = false
	          	if (res.isSuccess) {
		            this.$message({
		              message: this.$t('tips.optionSuccess'),
		              type: 'success'
		            })
		          } else {
		          	this.$message({
										message: res.message,
										type: "error"
								})
		          }
	          })
	        } else {
	          return false
	        }
	      })
		  this.$emit("close")
		  //location.reload()
	    },
		checkCount(){

		}
	  }
	}
</script>

<!-- 本组件的css -->
<style lang="scss" scoped>
	.formTitle{
		font-size: 16px;
		font-weight: 700;
		margin: 30px 30px 20px 30px;
		padding-bottom: 20px;
		border-bottom: 1px solid #CCCCCC;
	}
	.formContaner form{
		max-width: 600px;
	}
	.dialog-footer{
		margin-left: 180px;
	}
</style>
