<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="50%"
    @close="close"
  >
    <div class="manage-container">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="230px"
        label-position="right"
      >
        <el-form-item :label="$t('device.xzxm')" prop="projectId">
          <el-select
            v-model="form.projectId"
            size="small"
            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')" prop="name">
          <el-input v-model="form.name" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.zdbh')" prop="code">
          <el-input v-model="form.code" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.xlh')" prop="serial">
          <el-input v-model="form.serial" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.txxy')" prop="commPro">
          <el-select
            v-model="form.commPro"
            size="small"
            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.zdgy')" prop="technology">
          <el-select
            v-model="form.technology"
            size="small"
            filterable
            placeholder="请选择站点工艺"
          >
            <el-option
              v-for="item in deviceTechnologyData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.zdcz')" prop="material">
          <el-select
            v-model="form.material"
            size="small"
            filterable
            placeholder="请选择站点材质"
          >
            <el-option
              v-for="item in deviceMaterialData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.csbz')" prop="outStandard">
          <el-select
            v-model="form.outStandard"
            size="small"
            filterable
            placeholder="请选择出水标准"
          >
            <el-option
              v-for="item in outStandardData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.lxys')" prop="offlineDelay">
          <el-input v-model="form.offlineDelay" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.xzjd')" prop="townCode">
          <el-select
            v-model="form.townCode"
            size="small"
            filterable
            placeholder="请选择乡镇街道"
            @change="changeTown"
          >
            <el-option
              v-for="item in townsData"
              :key="item.townCode"
              :label="item.townName"
              :value="item.townCode + ',' + item.townName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sq')" prop="community">
          <el-input v-model="form.community" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sbgg')" prop="specifications">
          <el-input
            v-model="form.specifications"
            type="number"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.sblx')" prop="type">
          <el-select
            v-model="form.type"
            size="small"
            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')" prop="userNum">
          <el-input
            v-model="form.userNum"
            size="small"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.wlwk')" prop="simNum">
          <el-input v-model="form.simNum" size="small" type="text"></el-input>
        </el-form-item>
        <!--        <el-form-item label="报警用户" prop="alarmUser">-->
        <!--          <el-select-->
        <!--            v-model="form.alarmUser"-->
        <!--            size="small"-->
        <!--            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="报警方式" prop="alarmType">-->
        <!--          <el-select-->
        <!--            v-model="form.alarmType"-->
        <!--            size="small"-->
        <!--            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('device.ztdp')" prop="screenView">
          <el-select
            v-model="form.screenView"
            size="small"
            filterable
            placeholder="请选择组态大屏"
          >
            <el-option
              v-for="item in screenViewData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dataEnquiry.ywry')">
          <el-input v-model="form.leader" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('project.lxfs')">
          <el-input v-model="form.contact" size="small"></el-input>
        </el-form-item>

        <el-form-item :label="$t('device.gsp')">
          <el-upload
            class="avatar-uploader"
            :action="fileUpdateUrl"
            :headers="{ token: token }"
            :multiple="true"
            name="files"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="fileUrl + imageUrl" class="avatar" />
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <div style="position: relative">
          <el-form-item
            :label="$t('project.wd')"
            prop="latitude"
            style="width: 85%"
          >
            <el-input v-model="form.latitude" size="small"></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('project.jd')"
            prop="longitude"
            style="width: 85%"
          >
            <el-input v-model="form.longitude" size="small"></el-input>
          </el-form-item>
          <el-button
            style="position: absolute; right: 0; top: 30px"
            type="success"
            size="small"
            plain
            @click="checkLocation"
          >
            {{ $t('device.xzrw') }}
          </el-button>
        </div>

        <el-divider content-position="left">
          {{ $t('device.sbbxxx') }}
        </el-divider>
        <el-form-item :label="$t('device.sbbxdqsj')" prop="screenView">
          <el-date-picker
            v-model="form.warrantyPeriod"
            type="date"
            :popper-options="{
              modifiers: [
                {
                  name: 'flip',
                  options: {
                    fallbackPlacements: ['top'],
                    allowedAutoPlacements: ['top'],
                  },
                },
              ],
            }"
            :placeholder="$t('defalult.xzrq')"
            @change="changeBasic"
          ></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('device.sbbb')" prop="screenView">
          <el-select
            v-model="form.deviceVersion"
            size="small"
            filterable
            placeholder=""
          >
            <el-option
              v-for="item in deviceVersionData"
              :key="item.dataCode"
              :label="item.dataValue"
              :value="item.dataCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('device.zdkhlxr')">
          <el-input
            v-model="form.ownerName"
            size="small"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.zdkhlxfs')">
          <el-input
            v-model="form.ownerPhone"
            size="small"
            placeholder=""
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" size="small" @click="save">
          {{ $t('defalult.tjtn') }}
        </el-button>
      </div>
    </div>
    <frame-map ref="map" @setLatAndLng="setLatAndLng"></frame-map>
  </el-dialog>
</template>

<script>
import { getList } from '@/api/project';
import {
  getDictData,
  doEdit,
  doAdd,
  getTownsByProject,
  selectAllAlarmUser,
} from '@/api/device';
import { toNumber } from 'lodash';
import { baseURL } from '@/config';
import store from '@/store';
import frameMap from './frameMap';
import { getDate } from '@/common/times';
export default {
  name: 'DeviceEdit',
  components: {
    frameMap,
  },
  data() {
    return {
      form: {
        id: '',
        name: '',
        code: '',
        commPro: '',
        projectId: '',
        longitude: '',
        latitude: '',
        offlineDelay: 90,
        townCode: '',
        townName: '',
        community: '',
        specifications: '',
        type: '',
        userNum: '',
        // alarmUser: '',
        // alarmType: '',
        technology: '',
        material: '',
        ownerPhone: '',
        ownerName: '',
        outStandard: '',
        leader: '',
        contact: '',
        serial: '',
        boardImg: '',
        screenView: '',
        simNum: '',
      },
      filePath: baseURL + '/static/img/',
      fileUpdateUrl: '',
      token: '',
      imageUrl: [],
      siteName: '',
      siteCode: '',
      townCode: '',
      projectId: '',
      projectData: [],
      rules: {
        projectId: [
          { required: true, trigger: 'change', message: '请选择项目' },
        ],
        name: [{ required: true, trigger: 'blur', message: '请输入站点名称' }],
        code: [{ required: true, trigger: 'blur', message: '请输入站点编号' }],
        serial: [{ required: true, trigger: 'blur', message: '请输入序列号' }],
        commPro: [
          { required: true, trigger: 'change', message: '请选择通信协议' },
        ],
        deviceVersion: [
          { required: true, trigger: 'change', message: '请选择设备版本' },
        ],

        technology: [
          { required: true, trigger: 'blur', message: '请输入站点工艺' },
        ],
        material: [
          { required: true, trigger: 'blur', message: '请输入站点材质' },
        ],
        outStandard: [
          { required: true, trigger: 'blur', message: '请输入出水标准' },
        ],
        offlineDelay: [
          { required: true, trigger: 'blur', message: '请输入离线延迟' },
        ],
        townCode: [
          { required: true, trigger: 'change', message: '请选择乡镇街道' },
        ],
        specifications: [
          { required: true, trigger: 'blur', message: '请输入设备规格' },
        ],
        type: [{ required: true, trigger: 'blur', message: '请输入设备类型' }],
      },
      num: 0,
      title: '',
      dialogFormVisible: false,
      showMap: false,
      keyWords: '',
      fileUrl: baseURL + '/static/img/',
      diffData: {},
      ruleForm: [],
      commData: [],
      location: [],
      deviceTechnologyData: [],
      deviceMaterialData: [],
      outStandardData: [],
      deviceTypeData: [],
      alarmTypeData: [],
      townsData: [],
      alarmUserData: [],
      screenViewData: [],
      deviceVersionData: [],
    };
  },
  created() {},
  methods: {
    changeBasic() {},
    checkLocation() {
      this.$refs['map'].showMap(this.location);
    },
    //设置token
    setUploadUrl() {
      this.token = store.getters['user/token'];
      this.fileUpdateUrl = baseURL + '/file/uploadImg';
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      this.form.boardImg = res.data;
      this.imageUrl = res.data;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    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) {
      this.form.townCode = data.split(',')[0];
      this.form.townName = data.split(',')[1];
    },
    // async getAlarmUser() {
    //   const { data } = await selectAllAlarmUser();
    //   this.alarmUserData = data;
    // },
    setLatAndLng(coordinate) {
      this.form.longitude = coordinate.lng;
      this.form.latitude = coordinate.lat;
    },
    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;
      this.screenViewData = data.screenView;
      this.deviceVersionData = data.deviceVersion;
    },
    showEdit(row, status) {
      this.getProjectData();
      // this.getAlarmUser();
      this.getCommData();
      this.setUploadUrl();
      this.location = [];
      if (status == 1) {
        this.title = '添加';
        this.form.projectId = toNumber(row.projectId);
        this.form.boardImg = '';
        this.imageUrl = '';
        this.form.townCode = '';
      } 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.serial = data.serial;
        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;
        this.form.boardImg = data.boardImg;
        this.imageUrl = data.boardImg;
        this.simNum = data.simNum;
        this.form.ownerName = data.ownerName;
        this.form.ownerPhone = data.ownerPhone;
        this.form.warrantyPeriod = data.warrantyPeriod;
        // this.location = { lat: data.latitude, lng: data.longitude };
        // localStorage.setItem('deviceLongitude', data.longitude);
        // localStorage.setItem('deviceLatitude', data.latitude);
        // this.$refs['map'].setLocation({
        //   longitude: data.longitude,
        //   latitude: data.latitude,
        // });
        if (data.type !== null) {
          this.form.type = data.type.dataCode;
        }
        if (data.technology !== null) {
          this.form.technology = data.technology.dataCode;
        }
        if (data.screenView !== null) {
          this.form.screenView = data.screenView.dataCode;
        }
        if (data.deviceVersion !== null) {
          this.form.deviceVersion = data.deviceVersion.dataCode;
        }
        if (data.type !== null) {
          this.form.type = data.type.dataCode;
        }
        if (data.material !== null) {
          this.form.material = data.material.dataCode;
        }
        if (data.outStandard !== null) {
          this.form.outStandard = data.outStandard.dataCode;
        }
        this.form.leader = data.leader;
        this.form.contact = data.contact;
        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++) {
        //     if (null != alarmUser[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++) {
        //     if (null != alarmType[j]) {
        //       alarmType1.push(alarmType[j].dataCode);
        //     }
        //   }
        //   this.form.alarmType = alarmType1;
        // }
        this.location = [data.latitude, data.longitude];
      }
      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(',');
          // }
          this.form.warrantyPeriod &&
            (this.form.warrantyPeriod = getDate(this.form.warrantyPeriod));
          if (this.form.id) {
            const { msg } = await doEdit(this.form);
            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 lang="scss">
.select {
  width: 100%;
}
.avatar {
  width: 100px;
  height: 100px;
}
.avatar-uploader {
  width: 80px;
  height: 80px;
  text-align: center;
  border: 1px dashed #8c939d;
  .el-upload {
    line-height: 100px;
  }
}
</style>
