<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="项目组" prop="groupId">
        <el-select
          v-model="form.groupId"
          size="small"
          filterable
          placeholder="选择项目组"
        >
          <el-option
            v-for="item in groupData"
            :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 alarmType"
            :key="item.dataCode"
            :label="item.dataValue"
            :value="item.dataCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('project.xmmc')" prop="name">
        <el-input
          v-model.trim="form.name"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="省" prop="areaData">
        <el-cascader
          ref="cascaderItem"
          v-model="areaData"
          size="small"
          placeholder="请选择"
          :options="cityData"
          :props="optionProps"
          popper-class="cascader"
        ></el-cascader>
      </el-form-item>
      <el-form-item :label="$t('project.rzr')" prop="leader">
        <el-input
          v-model.trim="form.leader"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('project.lxfs')" prop="contact">
        <el-input
          v-model.trim="form.contact"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('project.lxsj')" prop="approvalTime">
        <el-date-picker
          v-model="form.approvalTime"
          size="small"
          type="date"
          placeholder="选择立项时间"
          format="YYYY-MM-DD HH:MM:ss"
          value-format="YYYY-MM-DD HH:MM:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('project.jd')" prop="longitude">
        <el-input
          v-model.trim="form.longitude"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item :label="$t('project.wd')" prop="latitude">
        <el-input
          v-model.trim="form.latitude"
          size="small"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-button type="success" size="small" plain @click="checkLocation">
        选择位置
      </el-button>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="save">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
    <frame-map ref="map" @setLatAndLng="setLatAndLng"></frame-map>
  </el-dialog>
</template>

<script>
import {
  doEdit,
  doAdd,
  getProjectGroup,
  selectAlarmTypeList,
} from '@/api/project';
import { getCity } from '@/api/city';
import { toNumber } from 'lodash';
import frameMap from '../../device/components/frameMap';
export default {
  name: 'ProjectEdit',
  components: {
    frameMap,
  },
  data() {
    return {
      form: {
        id: '',
        name: '',
        provinceCode: '',
        provinceName: '',
        cityCode: '',
        cityName: '',
        areaCode: '',
        areaName: '',
        groupId: '',
        leader: '',
        contact: '',
        approvalTime: '',
        latitude: '',
        longitude: '',
        alarmType: '',
      },
      keyWords: '',
      optionProps: {
        value: 'areaCode',
        label: 'areaName',
        children: 'children',
      },
      areaData: [],
      cityData: [],
      groupData: [],
      rules: {
        groupId: [
          { required: true, trigger: 'change', message: '请选择项目组' },
        ],
        name: [{ required: true, trigger: 'blur', message: '请输入项目名称' }],
        type: [{ required: true, trigger: 'blur', message: '请选择项目类型' }],
        leader: [{ required: true, trigger: 'blur', message: '请输入负责人' }],
        contact: [
          { required: true, trigger: 'blur', message: '请输入联系方式' },
        ],
        approvalTime: [
          { required: true, trigger: 'blur', message: '请选择立项时间' },
        ],
        longitude: [{ required: true, trigger: 'blur', message: '请输入经度' }],
        latitude: [{ required: true, trigger: 'blur', message: '请输入纬度' }],
      },
      clearable: true,
      menuId: '',
      parentData: [],
      title: '',
      dialogFormVisible: false,
      diffData: {},
      ruleForm: [],
      location: [],
      alarmType: [],
    };
  },
  created() {},
  methods: {
    checkLocation() {
      this.$refs['map'].showMap(this.location);
    },
    async getCityData() {
      const { data } = await getCity();
      this.cityData = this.getTreeData(data);
    },
    setLatAndLng(coordinate) {
      this.form.longitude = coordinate.lng;
      this.form.latitude = coordinate.lat;
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children 若为空数组，则将 children 设为undefined
          data[i].children = undefined;
        } else {
          // children 若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    handleCountryChange(value) {
      if (value) {
        const len = value.length - 1;
        this.form.parentId = value[len];
      } else {
        this.form.parentId = 0;
      }
    },
    // 报警方式
    async getAlarmType() {
      const { data } = await selectAlarmTypeList();
      this.alarmType = data;
    },
    showEdit(row, status) {
      this.getCityData();
      this.getGroup();
      this.getAlarmType();
      this.location = [];
      if (status == 1) {
        this.title = '添加';
        if (row.groupId) {
          this.form.groupId = toNumber(row.groupId);
        }
      } else {
        this.title = '编辑';
        this.menuId = row.id;
        this.form = Object.assign({}, row);
        this.ruleForm = Object.assign({}, row);
        if (row.projectGroup !== undefined) {
          this.form.groupId = row.projectGroup.id;
          this.ruleForm.groupId = row.projectGroup.id;
        }
        if (row.alarmType.length > 0) {
          const alarmType = [];
          row.alarmType.forEach(function (v, k) {
            alarmType.push(v.dataCode);
          });
          this.form.alarmType = alarmType;
          this.ruleForm.alarmType = alarmType;
        }
        this.areaData = [row.provinceCode, row.cityCode, row.areaCode];
        this.location = [this.form.latitude, this.form.longitude];
      }
      console.log(this.form);
      this.dialogFormVisible = true;
    },
    async getGroup() {
      const { data } = await getProjectGroup();
      this.groupData = data;
    },
    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) {
          const areaData = this.areaData;
          const expenseItem = this.$refs['cascaderItem'].inputValue;
          const name = expenseItem.split(' / ');
          this.form.provinceCode = areaData[0] == undefined ? '' : areaData[0];
          this.form.cityCode = areaData[1] == undefined ? '' : areaData[1];
          this.form.areaCode = areaData[2] == undefined ? '' : areaData[2];
          this.form.provinceName = name[0] == undefined ? '' : name[0];
          this.form.cityName = name[1] == undefined ? '' : name[1];
          this.form.areaName = name[2] == undefined ? '' : name[2];
          this.form.alarmType = this.form.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 {
            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>
.cascader {
  height: 300px;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
