<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="设备编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入设备编码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入设备名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备ip" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ip">
              <a-input v-model="model.ip" placeholder="请输入设备ip"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ip">
              <a-select placeholder="选择设备类型" v-model="model.type">
                <a-select-option v-for="type in types" :key="type">
                  {{ type }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="楼栋" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buildingName">
              <a-select placeholder="选择楼栋" v-model="model.buildingName" @change="buildingChange">
                <a-select-option v-for="buildingInfo in buildingInfos" :key="buildingInfo.name">
                  {{ buildingInfo.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="楼层" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="floor">
              <a-select placeholder="选择楼层" v-model="model.floor">
                <a-select-option v-for="floor in targetFloorList" :key="floor">
                  {{ floor }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="开门时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="doorOpenTime">
              <a-input-number :min="0" :formatter="value => `${value}s`"
                              :parser="value => value.replace('s', '')" v-model="model.doorOpenTime"
                              placeholder="请输入开门时间" style="width: 100%" suffix="RMB"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="设备位置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="place">
              <a-input v-model="model.place" placeholder="请输入设备位置"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="出产日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateOfProduction">
              <j-date placeholder="请选择生产日期" v-model="model.dateOfProduction" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="安装日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="installationDate">
              <j-date placeholder="请选择安装日期" v-model="model.installationDate" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="生产厂商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="manufacturer">
              <a-input v-model="model.manufacturer" placeholder="请输入生产厂商"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="保修截止日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warrantyPeriod">
              <j-date placeholder="请选择保修截止日期" v-model="model.warrantyPeriod" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <a-select placeholder="选择状态" v-model="model.status" @change="statusChange">
                <a-select-option v-for="status in statusList" :key="status.value">
                  {{ status.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="xy值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coordinateTmp">
              <a-input v-model="model.coordinateTmp" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <div style="position: relative">
              <img src="@/assets/floor.png" alt="floor" width="100%" height="100%"
                   @click="imgClick($event)" @load="floorImgLoadComplete($event)"/>
              <img :src="doorIconPath" alt="door"
                   :style="doorIconStyle"
                   v-show="doorIconPath"/>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import {httpAction, getAction} from '@/api/manage'
import {validateDuplicateValue} from '@/utils/util'

export default {
  name: 'PmAccessControlDeviceForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        doorOpenTime: 0,
        coordinateTmp: null,
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      confirmLoading: false,
      validatorRules: {
        code: [
          {
            required: true,
            message: '请输入设备编码',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入设备名称',
            trigger: 'blur'
          }
        ],
        ip: [
          {
            required: true,
            message: '请输入设备ip',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '选择设备类型',
            trigger: 'change'
          }
        ],
        buildingName: [
          {
            required: true,
            message: '选择楼栋',
            trigger: 'change'
          }
        ],
        floor: [
          {
            required: true,
            message: '选择楼层',
            trigger: 'change'
          }
        ],
        doorOpenTime: [
          {
            required: true,
            message: '请输入开门时间',
            trigger: 'blur'
          }
        ],
        place: [
          {
            required: true,
            message: '请输入设备位置',
            trigger: 'blur'
          }
        ],
        dateOfProduction: [
          {
            required: true,
            message: '请选择生产日期',
            trigger: 'change'
          }
        ],
        installationDate: [
          {
            required: true,
            message: '请选择安装日期',
            trigger: 'change'
          }
        ],
        manufacturer: [
          {
            required: true,
            message: '请输入生产厂商',
            trigger: 'blur'
          }
        ],
        warrantyPeriod: [
          {
            required: true,
            message: '请选择保修截止日期',
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '选择状态',
            trigger: 'change'
          }
        ],
        coordinateTmp: [
          {
            required: true,
            message: '请点击平面图设置设备坐标',
            trigger: ['change', 'blur']
          }
        ],
      },
      url: {
        add: "/pm/pmAccessControlDevice/add",
        edit: "/pm/pmAccessControlDevice/edit",
        queryById: "/pm/pmAccessControlDevice/queryById"
      },
      statusList: [
        {name: '正常', value: 'NORMAL', imgPath: require('@/assets/door-close.png')},
        {name: '离线', value: 'OFFLINE', imgPath: require('@/assets/door-offline.png')},
        {name: '损坏', value: 'BREAKDOWN', imgPath: require('@/assets/door-warning.png')}],
      doorIconStyle: {
        position: 'absolute',
        top: '0px',
        left: '0px',
        width: '40px'
      },
      doorIconPath: null,
      buildingInfos: [],
      targetFloorList: [],
      types: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    getAction('/pm/pmBuildingInfo/list')
      .then(value => this.buildingInfos = value.result);
    getAction('/pm/pmAccessControlDevice/types')
      .then(value => this.types = value.result);
  },
  methods: {
    add() {
      this.edit(this.modelDefault);
    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            // 设置创建用户Id
            this.model.createUserId = this.$store.getters.userInfo.id;
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }

          // 初始化坐标对象并赋值
          let coordinate = this.model.coordinateTmp.split(',');
          this.model.coordinate = {
            x: coordinate[0],
            y: coordinate[1]
          }
          // 设置修改用户Id
          this.model.modifyUserId = this.$store.getters.userInfo.id;

          httpAction(httpurl, this.model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }
      })
    },
    imgClick(e) {
      // 获取点击目标的x,y坐标
      let target = e.target;
      let fixX = target.x;
      let fixY = target.y;
      console.log(fixX, fixY);
      console.log(e.x, e.y);
      let offsetWidth = target.offsetWidth;
      let offsetHeight = target.offsetHeight;
      let offsetX = (e.x - fixX);
      let offsetY = (e.y - fixY);
      this.doorIconStyle.top = offsetY - 20 + 'px';
      this.doorIconStyle.left = offsetX - 20 + 'px';
      let x = ((e.x - fixX) / offsetWidth).toFixed(4);
      let y = ((e.y - fixY) / offsetHeight).toFixed(4);
      this.model.coordinateTmp = x + "," + y;
      this.$refs.form.validateField('coordinateTmp');
    },
    statusChange(value) {
      let targetList = this.statusList.filter(status => status.value === value);
      this.doorIconPath = targetList.length > 0 ? targetList[0].imgPath : null;
    },
    buildingChange(value) {
      let targetList = this.buildingInfos.filter(buildingInfo => buildingInfo.name === value);
      if (targetList != null && targetList.length > 0) {
        this.targetFloorList = targetList[0].floorList;
      } else {
        this.targetFloorList = [];
      }
    },
    floorImgLoadComplete(e) {
      if (this.model.coordinate) {
        this.model.coordinateTmp = this.model.coordinate.x + ',' + this.model.coordinate.y;
        this.statusChange(this.model.status);
        let target = e.target;
        let fixX = 20;
        let fixY = 20;
        let offsetWidth = target.offsetWidth;
        let offsetHeight = target.offsetHeight;
        this.doorIconStyle.top = this.model.coordinate.y * offsetHeight - fixY + 'px'
        this.doorIconStyle.left = this.model.coordinate.x * offsetWidth - fixX + 'px';
      }
    },
  }
}
</script>