<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :span="24">
            <a-form-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-device placeholder="请选择设备名称" :multiple="false" v-decorator="['deviceId',{rules: [{ required: true, message: '请选择设备名称!' }]}]"
                               dicCode="bu_device,device_name,id" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="传感器名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name',{rules: [{ required: true, message: '请输入传感器名称' }]}]" placeholder="请输入传感器名称" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="传感器类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="list" v-decorator="['typeId',{rules: [{ required: true, message: '请选择传感器类型!' }]}]" :trigger-change="true" dictCode="bu_sensor_type,name,id" placeholder="请选择传感器类型" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="检测项目" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['checkItem']" placeholder="请输入检测项目" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="传感器顺序" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['dataUnit']" placeholder="请输入传感器顺序" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="传感器安装位置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['location']" placeholder="请输入传感器安装位置" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="二维码" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div class="image-container">
                <img class="centered-image" :src="imageSrc"  alt="返回列表点击二维码确定" @mouseover="showButton = imageSrc ===''? false:true" @mouseleave="showButton = false">
                <a-button class="centered-button" v-show="showButton" type="danger" @click="removeImage" @mouseover="showButton = true" @mouseleave="showButton = false">删除</a-button>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>

  import { httpAction } from '@api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JSelectDevice from '@comp/jeecgbiz/JSelectDevice'
  import { duplicateCheck } from '../../../api/api'

  export default {
    name: "BuSensorModal",
    components: {
      JDictSelectTag,
      JSelectDevice,
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title:"操作",
        width:800,
        userId:"",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules: {
          ipAddress: {
            rules: [
              { required: true, message: '请输入IP地址' },
              { validator: this.validateIpAddress }
            ]
          },
        },
        url: {
          add: "/sensor/buSensor/add",
          edit: "/sensor/buSensor/edit",
          userId:"/sys/user/generateUserId",
        },
        imageSrc:'',
        showButton: false,
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        console.log("record",record)
        this.imageSrc = record.code
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.userId = record.id;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'deviceId','name','typeId','location','checkItem','dataUnit','code'))
        })
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      validateIpAddress(rule, value, callback) {
        var params = {
          tableName: 'bu_sensor',
          fieldName: 'ip_address',
          fieldVal: value,
          dataId: this.userId
        };
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback("该IP已存在!")
          }
        })
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'typeId','useTime','deviceId','name','dataUnit','warningLimit','alarmLimit',
          'dataValue','alarmMin','warningMin','tableName','tableNameAlarm','ipAddress','checkItem','collectTime'))
      },

      removeImage(){
        this.imageSrc = ''
        this.model.code = ''
      }


    }
  }
</script>
<style scoped>
/* 容器需要设置为相对定位 */
.image-container {
  position: relative;
  width: fit-content; /* 或者你想要的宽度 */
}

/* 图片样式 */
.centered-image {
  display: block; /* 防止底部出现空隙 */
  width: 100%; /* 根据需要调整 */
  height: auto; /* 保持宽高比 */
}

/* 按钮样式 */
.centered-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 将按钮向左上移动自身宽高的一半 */
  /* 添加其他样式，如背景色、边框、圆角等 */
}
</style>