<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1500px"
    @close="close"
  >
    <div class="manage-container">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item :label="$t('device.xzxm')">
          <el-select
            v-model="form.projectId"
            filterable
            placeholder="请选择项目"
            @change="changeProject"
          >
            <el-option
              v-for="item in projectData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.zdmc')">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('siteDetails.zdbh')">
          <el-input v-model="form.code"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.txxy')">
          <el-select
            v-model="form.commPro"
            filterable
            placeholder="请选择通信协议"
          >
            <el-option
              v-for="item in commData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.lxys')">
          <el-input v-model="form.offlineDelay"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.xzjd')">
          <el-select
            v-model="townCode"
            filterable
            placeholder="请选择乡镇街道"
            @change="changeTown"
          >
            <el-option
              v-for="item in townsData"
              :key="item.townCode"
              :label="item.townName"
              :value="{ label: item.townName, value: item.townCode }"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sq')">
          <el-input v-model="form.community"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sbgg')">
          <el-input v-model="form.specifications"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sblx')">
          <el-select
            v-model="form.type"
            filterable
            placeholder="请选择设备类型"
          >
            <el-option
              v-for="item in deviceTypeData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.fwyhs')">
          <el-input v-model="form.userNum" type="number"></el-input>
        </el-form-item>
        <el-form-item label="报警用户">
          <el-select
            v-model="form.alarmUser"
            filterable
            multiple
            placeholder="请选择报警用户"
          >
            <el-option
              v-for="item in alarmUserData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报警方式">
          <el-select
            v-model="form.alarmType"
            filterable
            multiple
            placeholder="请选择报警方式"
          >
            <el-option
              v-for="item in alarmTypeData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('project.wd')">
          <el-input v-model="form.latitude"></el-input>
        </el-form-item>
        <el-form-item :label="$t('project.jd')">
          <el-input v-model="form.longitude"></el-input>
        </el-form-item>
        <el-form ref="form" :model="keyWords" label-width="100px">
          <el-form-item label="位置信息">
            <el-input v-model="keyWords"></el-input>
          </el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="searchAddress"
          >
            {{ $t('defalult.cx') }}
          </el-button>
          <bd-map ref="baiduMap" @tellFatherName="getLatAndLng"></bd-map>
        </el-form>
        <vab-query-form>
          <el-button type="primary" @click="save">
            {{ $t('defalult.tjtn') }}
          </el-button>
        </vab-query-form>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { getList } from '@/api/project';
import {
  getDictData,
  doEdit,
  doAdd,
  getTownsByProject,
  selectAllAlarmUser,
} from '@/api/device';
import bdMap from './bdMap';
import { toNumber } from 'lodash';
export default {
  name: 'DeviceEdit',
  components: {
    bdMap,
  },
  data() {
    return {
      form: {
        id: '',
        name: '',
        code: '',
        commPro: '',
        projectId: '',
        longitude: '',
        latitude: '',
        offlineDelay: 90,
        townCode: '',
        townName: '',
        community: '',
        specifications: '',
        type: '',
        userNum: '',
        alarmUser: '',
        alarmType: '',
      },
      siteName: '',
      siteCode: '',
      townCode: '',
      projectId: '',
      projectData: [],
      rules: {},
      title: '',
      dialogFormVisible: false,
      keyWords: '',
      diffData: {},
      ruleForm: [],
      commData: [],
      deviceTechnologyData: [],
      deviceMaterialData: [],
      outStandardData: [],
      deviceTypeData: [],
      alarmTypeData: [],
      townsData: [],
      alarmUserData: [],
    };
  },
  created() {
    this.getCommData();
  },
  methods: {
    async getProjectData() {
      const params = {
        page: 1,
        size: 100,
      };
      const { data } = await getList(params);
      this.projectData = data.items;
    },
    changeProject() {
      this.getTownsByProject();
    },
    async getTownsByProject() {
      const { data } = await getTownsByProject({
        projectId: this.form.projectId,
      });
      this.townsData = data;
    },
    changeTown(data) {
      const { value, label } = data;
      this.form.townCode = value;
      this.form.townName = label;
    },
    async getAlarmUser() {
      const { data } = await selectAllAlarmUser();
      this.alarmUserData = data;
    },
    getLatAndLng(coordinate) {
      this.form.longitude = coordinate.lng;
      this.form.latitude = coordinate.lat;
    },
    searchAddress() {
      this.$refs['baiduMap'].setPlace(this.keyWords);
    },
    async getCommData() {
      const { data } = await getDictData();
      this.commData = data.communicationProtocol;
      this.deviceTechnologyData = data.deviceTechnology;
      this.deviceMaterialData = data.deviceMaterial;
      this.outStandardData = data.outStandard;
      this.deviceTypeData = data.deviceType;
      this.alarmTypeData = data.alarmType;
    },
    showEdit(row, status) {
      this.getProjectData();
      this.getAlarmUser();
      if (status == 1) {
        this.title = '添加';
        this.form.projectId = toNumber(row.projectId);
      } else {
        this.title = '编辑';
        var data = Object.assign({}, row);
        this.form.id = data.id;
        this.form.name = data.name;
        this.form.code = data.code;
        this.form.commPro = data.commPro.dataCode;
        this.form.projectId = data.project.id;
        this.form.longitude = data.longitude;
        this.form.latitude = data.latitude;
        this.form.offlineDelay = data.offlineDelay;
        this.form.townCode = data.townCode;
        this.form.townName = data.townName;
        this.form.community = data.community;
        this.form.specifications = data.specifications;
        if (data.type !== null) {
          this.form.type = data.type.dataCode;
        }
        this.form.userNum = data.userNum;
        this.siteName = data.name;
        this.siteCode = data.code;
        this.townCode = data.townName;
        var alarmUser1 = [];
        var alarmUser = data.alarmUser;
        if (alarmUser) {
          for (var i = 0; i < alarmUser.length; i++) {
            alarmUser1.push(alarmUser[i].id);
          }
          this.form.alarmUser = alarmUser1;
        }
        var alarmType1 = [];
        var alarmType = data.alarmType;
        if (alarmType) {
          for (var j = 0; j < alarmType.length; j++) {
            alarmType1.push(alarmType[j].dataCode);
          }
          this.form.alarmType = alarmType1;
        }
      }
      this.getTownsByProject();
      this.dialogFormVisible = true;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    getDiffData() {
      this.diffData = {};
      Object.keys(this.form).forEach(item => {
        if (this.form[item] != this.ruleForm[item]) {
          this.diffData[item] = this.form[item];
        }
      });
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (this.siteName == this.form.name) {
            delete this.form.name;
          }
          if (this.siteCode == this.form.code) {
            delete this.form.code;
          }
          var alarmUser = this.form.alarmUser;
          if (alarmUser) {
            this.form.alarmUser = alarmUser.join(',');
          }
          var alarmType = this.form.alarmType;
          if (alarmType) {
            this.form.alarmType = alarmType.join(',');
          }
          if (this.form.id) {
            this.getDiffData();
            if (Object.keys(this.diffData).length != 0) {
              this.diffData.id = this.form.id;
              const { msg } = await doEdit(this.diffData);
              this.$notify({
                title: msg,
                type: 'success',
              });
            }
          } else {
            delete this.form.id;
            const { msg } = await doAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style>
.select {
  width: 100%;
}
</style>
